001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.regionserver;
019
020import java.io.IOException;
021import java.math.BigInteger;
022import java.security.PrivilegedAction;
023import java.security.SecureRandom;
024import java.util.ArrayList;
025import java.util.HashMap;
026import java.util.List;
027import java.util.Map;
028import java.util.concurrent.ConcurrentHashMap;
029import java.util.function.Consumer;
030
031import org.apache.commons.lang3.mutable.MutableInt;
032import org.apache.hadoop.conf.Configuration;
033import org.apache.hadoop.fs.FileStatus;
034import org.apache.hadoop.fs.FileSystem;
035import org.apache.hadoop.fs.FileUtil;
036import org.apache.hadoop.fs.Path;
037import org.apache.hadoop.fs.permission.FsPermission;
038import org.apache.hadoop.hbase.DoNotRetryIOException;
039import org.apache.hadoop.hbase.HConstants;
040import org.apache.hadoop.hbase.TableName;
041import org.apache.hadoop.hbase.client.Connection;
042import org.apache.hadoop.hbase.ipc.RpcServer;
043import org.apache.hadoop.hbase.regionserver.HRegion.BulkLoadListener;
044import org.apache.hadoop.hbase.security.User;
045import org.apache.hadoop.hbase.security.UserProvider;
046import org.apache.hadoop.hbase.security.token.FsDelegationToken;
047import org.apache.hadoop.hbase.security.token.TokenUtil;
048import org.apache.hadoop.hbase.util.Bytes;
049import org.apache.hadoop.hbase.util.FSHDFSUtils;
050import org.apache.hadoop.hbase.util.FSUtils;
051import org.apache.hadoop.hbase.util.Methods;
052import org.apache.hadoop.hbase.util.Pair;
053import org.apache.hadoop.io.Text;
054import org.apache.hadoop.security.UserGroupInformation;
055import org.apache.hadoop.security.token.Token;
056import org.apache.yetus.audience.InterfaceAudience;
057import org.slf4j.Logger;
058import org.slf4j.LoggerFactory;
059import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
060import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos;
061import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.BulkLoadHFileRequest;
062import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.CleanupBulkLoadRequest;
063import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.PrepareBulkLoadRequest;
064
065/**
066 * Bulk loads in secure mode.
067 *
068 * This service addresses two issues:
069 * <ol>
070 * <li>Moving files in a secure filesystem wherein the HBase Client
071 * and HBase Server are different filesystem users.</li>
072 * <li>Does moving in a secure manner. Assuming that the filesystem
073 * is POSIX compliant.</li>
074 * </ol>
075 *
076 * The algorithm is as follows:
077 * <ol>
078 * <li>Create an hbase owned staging directory which is
079 * world traversable (711): {@code /hbase/staging}</li>
080 * <li>A user writes out data to his secure output directory: {@code /user/foo/data}</li>
081 * <li>A call is made to hbase to create a secret staging directory
082 * which globally rwx (777): {@code /user/staging/averylongandrandomdirectoryname}</li>
083 * <li>The user moves the data into the random staging directory,
084 * then calls bulkLoadHFiles()</li>
085 * </ol>
086 *
087 * Like delegation tokens the strength of the security lies in the length
088 * and randomness of the secret directory.
089 *
090 */
091@InterfaceAudience.Private
092public class SecureBulkLoadManager {
093
094  public static final long VERSION = 0L;
095
096  //320/5 = 64 characters
097  private static final int RANDOM_WIDTH = 320;
098  private static final int RANDOM_RADIX = 32;
099
100  private static final Logger LOG = LoggerFactory.getLogger(SecureBulkLoadManager.class);
101
102  private final static FsPermission PERM_ALL_ACCESS = FsPermission.valueOf("-rwxrwxrwx");
103  private final static FsPermission PERM_HIDDEN = FsPermission.valueOf("-rwx--x--x");
104  private SecureRandom random;
105  private FileSystem fs;
106  private Configuration conf;
107
108  //two levels so it doesn't get deleted accidentally
109  //no sticky bit in Hadoop 1.0
110  private Path baseStagingDir;
111
112  private UserProvider userProvider;
113  private ConcurrentHashMap<UserGroupInformation, MutableInt> ugiReferenceCounter;
114  private Connection conn;
115
116  SecureBulkLoadManager(Configuration conf, Connection conn) {
117    this.conf = conf;
118    this.conn = conn;
119  }
120
121  public void start() throws IOException {
122    random = new SecureRandom();
123    userProvider = UserProvider.instantiate(conf);
124    ugiReferenceCounter = new ConcurrentHashMap<>();
125    fs = FileSystem.get(conf);
126    baseStagingDir = new Path(FSUtils.getRootDir(conf), HConstants.BULKLOAD_STAGING_DIR_NAME);
127
128    if (conf.get("hbase.bulkload.staging.dir") != null) {
129      LOG.warn("hbase.bulkload.staging.dir " + " is deprecated. Bulkload staging directory is "
130          + baseStagingDir);
131    }
132    if (!fs.exists(baseStagingDir)) {
133      fs.mkdirs(baseStagingDir, PERM_HIDDEN);
134    }
135  }
136
137  public void stop() throws IOException {
138  }
139
140  public String prepareBulkLoad(final HRegion region, final PrepareBulkLoadRequest request)
141      throws IOException {
142    User user = getActiveUser();
143    region.getCoprocessorHost().prePrepareBulkLoad(user);
144
145    String bulkToken =
146        createStagingDir(baseStagingDir, user, region.getTableDescriptor().getTableName())
147            .toString();
148
149    return bulkToken;
150  }
151
152  public void cleanupBulkLoad(final HRegion region, final CleanupBulkLoadRequest request)
153      throws IOException {
154    try {
155      region.getCoprocessorHost().preCleanupBulkLoad(getActiveUser());
156
157      Path path = new Path(request.getBulkToken());
158      if (!fs.delete(path, true)) {
159        if (fs.exists(path)) {
160          throw new IOException("Failed to clean up " + path);
161        }
162      }
163      LOG.info("Cleaned up " + path + " successfully.");
164    } finally {
165      UserGroupInformation ugi = getActiveUser().getUGI();
166      try {
167        if (!UserGroupInformation.getLoginUser().equals(ugi) && !isUserReferenced(ugi)) {
168          FileSystem.closeAllForUGI(ugi);
169        }
170      } catch (IOException e) {
171        LOG.error("Failed to close FileSystem for: " + ugi, e);
172      }
173    }
174  }
175
176  private Consumer<HRegion> fsCreatedListener;
177
178  @VisibleForTesting
179  void setFsCreatedListener(Consumer<HRegion> fsCreatedListener) {
180    this.fsCreatedListener = fsCreatedListener;
181  }
182
183
184  private void incrementUgiReference(UserGroupInformation ugi) {
185    // if we haven't seen this ugi before, make a new counter
186    ugiReferenceCounter.compute(ugi, (key, value) -> {
187      if (value == null) {
188        value = new MutableInt(1);
189      } else {
190        value.increment();
191      }
192      return value;
193    });
194  }
195
196  private void decrementUgiReference(UserGroupInformation ugi) {
197    // if the count drops below 1 we remove the entry by returning null
198    ugiReferenceCounter.computeIfPresent(ugi, (key, value) -> {
199      if (value.intValue() > 1) {
200        value.decrement();
201      } else {
202        value = null;
203      }
204      return value;
205    });
206  }
207
208  private boolean isUserReferenced(UserGroupInformation ugi) {
209    // if the ugi is in the map, based on invariants above
210    // the count must be above zero
211    return ugiReferenceCounter.containsKey(ugi);
212  }
213
214  public Map<byte[], List<Path>> secureBulkLoadHFiles(final HRegion region,
215    final BulkLoadHFileRequest request) throws IOException {
216    return secureBulkLoadHFiles(region, request, null);
217  }
218
219  public Map<byte[], List<Path>> secureBulkLoadHFiles(final HRegion region,
220      final BulkLoadHFileRequest request, List<String> clusterIds) throws IOException {
221    final List<Pair<byte[], String>> familyPaths = new ArrayList<>(request.getFamilyPathCount());
222    for(ClientProtos.BulkLoadHFileRequest.FamilyPath el : request.getFamilyPathList()) {
223      familyPaths.add(new Pair<>(el.getFamily().toByteArray(), el.getPath()));
224    }
225
226    Token userToken = null;
227    if (userProvider.isHadoopSecurityEnabled()) {
228      userToken = new Token(request.getFsToken().getIdentifier().toByteArray(), request.getFsToken()
229              .getPassword().toByteArray(), new Text(request.getFsToken().getKind()), new Text(
230              request.getFsToken().getService()));
231    }
232    final String bulkToken = request.getBulkToken();
233    User user = getActiveUser();
234    final UserGroupInformation ugi = user.getUGI();
235    if (userProvider.isHadoopSecurityEnabled()) {
236      try {
237        Token tok = TokenUtil.obtainToken(conn);
238        if (tok != null) {
239          boolean b = ugi.addToken(tok);
240          LOG.debug("token added " + tok + " for user " + ugi + " return=" + b);
241        }
242      } catch (IOException ioe) {
243        LOG.warn("unable to add token", ioe);
244      }
245    }
246    if (userToken != null) {
247      ugi.addToken(userToken);
248    } else if (userProvider.isHadoopSecurityEnabled()) {
249      //we allow this to pass through in "simple" security mode
250      //for mini cluster testing
251      throw new DoNotRetryIOException("User token cannot be null");
252    }
253
254    if (region.getCoprocessorHost() != null) {
255      region.getCoprocessorHost().preBulkLoadHFile(familyPaths);
256    }
257    Map<byte[], List<Path>> map = null;
258
259    try {
260      incrementUgiReference(ugi);
261      // Get the target fs (HBase region server fs) delegation token
262      // Since we have checked the permission via 'preBulkLoadHFile', now let's give
263      // the 'request user' necessary token to operate on the target fs.
264      // After this point the 'doAs' user will hold two tokens, one for the source fs
265      // ('request user'), another for the target fs (HBase region server principal).
266      if (userProvider.isHadoopSecurityEnabled()) {
267        FsDelegationToken targetfsDelegationToken = new FsDelegationToken(userProvider,"renewer");
268        targetfsDelegationToken.acquireDelegationToken(fs);
269
270        Token<?> targetFsToken = targetfsDelegationToken.getUserToken();
271        if (targetFsToken != null
272            && (userToken == null || !targetFsToken.getService().equals(userToken.getService()))){
273          ugi.addToken(targetFsToken);
274        }
275      }
276
277      map = ugi.doAs(new PrivilegedAction<Map<byte[], List<Path>>>() {
278        @Override
279        public Map<byte[], List<Path>> run() {
280          FileSystem fs = null;
281          try {
282            fs = FileSystem.get(conf);
283            for(Pair<byte[], String> el: familyPaths) {
284              Path stageFamily = new Path(bulkToken, Bytes.toString(el.getFirst()));
285              if(!fs.exists(stageFamily)) {
286                fs.mkdirs(stageFamily);
287                fs.setPermission(stageFamily, PERM_ALL_ACCESS);
288              }
289            }
290            if (fsCreatedListener != null) {
291              fsCreatedListener.accept(region);
292            }
293            //We call bulkLoadHFiles as requesting user
294            //To enable access prior to staging
295            return region.bulkLoadHFiles(familyPaths, true,
296                new SecureBulkLoadListener(fs, bulkToken, conf), request.getCopyFile(),
297              clusterIds, request.getReplicate());
298          } catch (Exception e) {
299            LOG.error("Failed to complete bulk load", e);
300          }
301          return null;
302        }
303      });
304    } finally {
305      decrementUgiReference(ugi);
306      if (region.getCoprocessorHost() != null) {
307        region.getCoprocessorHost().postBulkLoadHFile(familyPaths, map);
308      }
309    }
310    return map;
311  }
312
313  private Path createStagingDir(Path baseDir,
314                                User user,
315                                TableName tableName) throws IOException {
316    String tblName = tableName.getNameAsString().replace(":", "_");
317    String randomDir = user.getShortName()+"__"+ tblName +"__"+
318        (new BigInteger(RANDOM_WIDTH, random).toString(RANDOM_RADIX));
319    return createStagingDir(baseDir, user, randomDir);
320  }
321
322  private Path createStagingDir(Path baseDir,
323                                User user,
324                                String randomDir) throws IOException {
325    Path p = new Path(baseDir, randomDir);
326    fs.mkdirs(p, PERM_ALL_ACCESS);
327    fs.setPermission(p, PERM_ALL_ACCESS);
328    return p;
329  }
330
331  private User getActiveUser() throws IOException {
332    // for non-rpc handling, fallback to system user
333    User user = RpcServer.getRequestUser().orElse(userProvider.getCurrent());
334    // this is for testing
335    if (userProvider.isHadoopSecurityEnabled() &&
336        "simple".equalsIgnoreCase(conf.get(User.HBASE_SECURITY_CONF_KEY))) {
337      return User.createUserForTesting(conf, user.getShortName(), new String[] {});
338    }
339
340    return user;
341  }
342
343  private static class SecureBulkLoadListener implements BulkLoadListener {
344    // Target filesystem
345    private final FileSystem fs;
346    private final String stagingDir;
347    private final Configuration conf;
348    // Source filesystem
349    private FileSystem srcFs = null;
350    private Map<String, FsPermission> origPermissions = null;
351
352    public SecureBulkLoadListener(FileSystem fs, String stagingDir, Configuration conf) {
353      this.fs = fs;
354      this.stagingDir = stagingDir;
355      this.conf = conf;
356      this.origPermissions = new HashMap<>();
357    }
358
359    @Override
360    public String prepareBulkLoad(final byte[] family, final String srcPath, boolean copyFile)
361        throws IOException {
362      Path p = new Path(srcPath);
363      Path stageP = new Path(stagingDir, new Path(Bytes.toString(family), p.getName()));
364
365      // In case of Replication for bulk load files, hfiles are already copied in staging directory
366      if (p.equals(stageP)) {
367        LOG.debug(p.getName()
368            + " is already available in staging directory. Skipping copy or rename.");
369        return stageP.toString();
370      }
371
372      if (srcFs == null) {
373        srcFs = FileSystem.newInstance(p.toUri(), conf);
374      }
375
376      if(!isFile(p)) {
377        throw new IOException("Path does not reference a file: " + p);
378      }
379
380      // Check to see if the source and target filesystems are the same
381      if (!FSHDFSUtils.isSameHdfs(conf, srcFs, fs)) {
382        LOG.debug("Bulk-load file " + srcPath + " is on different filesystem than " +
383            "the destination filesystem. Copying file over to destination staging dir.");
384        FileUtil.copy(srcFs, p, fs, stageP, false, conf);
385      } else if (copyFile) {
386        LOG.debug("Bulk-load file " + srcPath + " is copied to destination staging dir.");
387        FileUtil.copy(srcFs, p, fs, stageP, false, conf);
388      } else {
389        LOG.debug("Moving " + p + " to " + stageP);
390        FileStatus origFileStatus = fs.getFileStatus(p);
391        origPermissions.put(srcPath, origFileStatus.getPermission());
392        if(!fs.rename(p, stageP)) {
393          throw new IOException("Failed to move HFile: " + p + " to " + stageP);
394        }
395      }
396      fs.setPermission(stageP, PERM_ALL_ACCESS);
397      return stageP.toString();
398    }
399
400    @Override
401    public void doneBulkLoad(byte[] family, String srcPath) throws IOException {
402      LOG.debug("Bulk Load done for: " + srcPath);
403      closeSrcFs();
404    }
405
406    private void closeSrcFs() throws IOException {
407      if (srcFs != null) {
408        srcFs.close();
409        srcFs = null;
410      }
411    }
412
413    @Override
414    public void failedBulkLoad(final byte[] family, final String srcPath) throws IOException {
415      try {
416        Path p = new Path(srcPath);
417        if (srcFs == null) {
418          srcFs = FileSystem.newInstance(p.toUri(), conf);
419        }
420        if (!FSHDFSUtils.isSameHdfs(conf, srcFs, fs)) {
421          // files are copied so no need to move them back
422          return;
423        }
424        Path stageP = new Path(stagingDir, new Path(Bytes.toString(family), p.getName()));
425
426        // In case of Replication for bulk load files, hfiles are not renamed by end point during
427        // prepare stage, so no need of rename here again
428        if (p.equals(stageP)) {
429          LOG.debug(p.getName() + " is already available in source directory. Skipping rename.");
430          return;
431        }
432
433        LOG.debug("Moving " + stageP + " back to " + p);
434        if (!fs.rename(stageP, p)) {
435          throw new IOException("Failed to move HFile: " + stageP + " to " + p);
436        }
437
438        // restore original permission
439        if (origPermissions.containsKey(srcPath)) {
440          fs.setPermission(p, origPermissions.get(srcPath));
441        } else {
442          LOG.warn("Can't find previous permission for path=" + srcPath);
443        }
444      } finally {
445        closeSrcFs();
446      }
447    }
448
449    /**
450     * Check if the path is referencing a file.
451     * This is mainly needed to avoid symlinks.
452     * @param p
453     * @return true if the p is a file
454     * @throws IOException
455     */
456    private boolean isFile(Path p) throws IOException {
457      FileStatus status = srcFs.getFileStatus(p);
458      boolean isFile = !status.isDirectory();
459      try {
460        isFile = isFile && !(Boolean)Methods.call(FileStatus.class, status, "isSymlink", null, null);
461      } catch (Exception e) {
462      }
463      return isFile;
464    }
465  }
466}