View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.security.access;
20  
21  import com.google.protobuf.RpcCallback;
22  import com.google.protobuf.RpcController;
23  import com.google.protobuf.Service;
24  
25  import org.apache.commons.lang.StringUtils;
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  import org.apache.hadoop.hbase.classification.InterfaceAudience;
29  import org.apache.hadoop.conf.Configuration;
30  import org.apache.hadoop.fs.FileStatus;
31  import org.apache.hadoop.fs.FileSystem;
32  import org.apache.hadoop.fs.FileUtil;
33  import org.apache.hadoop.fs.Path;
34  import org.apache.hadoop.fs.permission.FsPermission;
35  import org.apache.hadoop.hbase.Coprocessor;
36  import org.apache.hadoop.hbase.CoprocessorEnvironment;
37  import org.apache.hadoop.hbase.TableName;
38  import org.apache.hadoop.hbase.DoNotRetryIOException;
39  import org.apache.hadoop.hbase.coprocessor.BulkLoadObserver;
40  import org.apache.hadoop.hbase.coprocessor.CoprocessorService;
41  import org.apache.hadoop.hbase.coprocessor.ObserverContext;
42  import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
43  import org.apache.hadoop.hbase.ipc.RpcServer;
44  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
45  import org.apache.hadoop.hbase.protobuf.ResponseConverter;
46  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
47  import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.SecureBulkLoadService;
48  import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.PrepareBulkLoadRequest;
49  import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.PrepareBulkLoadResponse;
50  import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.CleanupBulkLoadRequest;
51  import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.CleanupBulkLoadResponse;
52  import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.SecureBulkLoadHFilesRequest;
53  import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.SecureBulkLoadHFilesResponse;
54  import org.apache.hadoop.hbase.regionserver.Region;
55  import org.apache.hadoop.hbase.regionserver.Region.BulkLoadListener;
56  import org.apache.hadoop.hbase.security.SecureBulkLoadUtil;
57  import org.apache.hadoop.hbase.security.User;
58  import org.apache.hadoop.hbase.security.UserProvider;
59  import org.apache.hadoop.hbase.security.token.FsDelegationToken;
60  import org.apache.hadoop.hbase.util.Bytes;
61  import org.apache.hadoop.hbase.util.FSHDFSUtils;
62  import org.apache.hadoop.hbase.util.Methods;
63  import org.apache.hadoop.hbase.util.Pair;
64  import org.apache.hadoop.io.Text;
65  import org.apache.hadoop.security.UserGroupInformation;
66  import org.apache.hadoop.security.token.Token;
67  
68  import java.io.IOException;
69  import java.math.BigInteger;
70  import java.security.PrivilegedAction;
71  import java.security.SecureRandom;
72  import java.util.ArrayList;
73  import java.util.Arrays;
74  import java.util.HashMap;
75  import java.util.HashSet;
76  import java.util.List;
77  import java.util.Map;
78  import java.util.Set;
79  
80  /**
81   * Coprocessor service for bulk loads in secure mode.
82   * This coprocessor has to be installed as part of enabling
83   * security in HBase.
84   *
85   * This service addresses two issues:
86   *
87   * 1. Moving files in a secure filesystem wherein the HBase Client
88   * and HBase Server are different filesystem users.
89   * 2. Does moving in a secure manner. Assuming that the filesystem
90   * is POSIX compliant.
91   *
92   * The algorithm is as follows:
93   *
94   * 1. Create an hbase owned staging directory which is
95   * world traversable (711): /hbase/staging
96   * 2. A user writes out data to his secure output directory: /user/foo/data
97   * 3. A call is made to hbase to create a secret staging directory
98   * which globally rwx (777): /user/staging/averylongandrandomdirectoryname
99   * 4. The user moves the data into the random staging directory,
100  * then calls bulkLoadHFiles()
101  *
102  * Like delegation tokens the strength of the security lies in the length
103  * and randomness of the secret directory.
104  *
105  */
106 @InterfaceAudience.Private
107 public class SecureBulkLoadEndpoint extends SecureBulkLoadService
108     implements CoprocessorService, Coprocessor {
109 
110   public static final long VERSION = 0L;
111 
112   //320/5 = 64 characters
113   private static final int RANDOM_WIDTH = 320;
114   private static final int RANDOM_RADIX = 32;
115 
116   private static final Log LOG = LogFactory.getLog(SecureBulkLoadEndpoint.class);
117 
118   private final static FsPermission PERM_ALL_ACCESS = FsPermission.valueOf("-rwxrwxrwx");
119   private final static FsPermission PERM_HIDDEN = FsPermission.valueOf("-rwx--x--x");
120 
121   public static final String FS_WITHOUT_SUPPORT_PERMISSION_KEY =
122       "hbase.secure.bulkload.fs.permission.lacking";
123   public static final String FS_WITHOUT_SUPPORT_PERMISSION_DEFAULT =
124       "s3,s3a,s3n,wasb,wasbs,swift,adfs,abfs,viewfs";
125 
126   private SecureRandom random;
127   private FileSystem fs;
128   private Configuration conf;
129 
130   //two levels so it doesn't get deleted accidentally
131   //no sticky bit in Hadoop 1.0
132   private Path baseStagingDir;
133 
134   private RegionCoprocessorEnvironment env;
135 
136   private UserProvider userProvider;
137 
138   @Override
139   public void start(CoprocessorEnvironment env) {
140     this.env = (RegionCoprocessorEnvironment)env;
141     random = new SecureRandom();
142     conf = env.getConfiguration();
143     baseStagingDir = SecureBulkLoadUtil.getBaseStagingDir(conf);
144     this.userProvider = UserProvider.instantiate(conf);
145     Set<String> fsSet = getFileSystemSchemesWithoutPermissionSupport(conf);
146 
147     try {
148       fs = baseStagingDir.getFileSystem(conf);
149       if (!fs.exists(baseStagingDir)) {
150         fs.mkdirs(baseStagingDir, PERM_HIDDEN);
151       }
152       FileStatus status = fs.getFileStatus(baseStagingDir);
153       if (status == null) {
154         throw new IllegalStateException("Failed to create staging directory");
155       }
156 
157       // If HDFS UMASK value has limited scope then staging directory permission may not be 711
158       // after creation, so we should set staging directory permission explicitly.
159       if (!status.getPermission().equals(PERM_HIDDEN)) {
160         fs.setPermission(baseStagingDir, PERM_HIDDEN);
161         status = fs.getFileStatus(baseStagingDir);
162       }
163 
164       // no sticky bit in hadoop-1.0, making directory nonempty so it never gets erased
165       Path doNotEraseDir = new Path(baseStagingDir, "DONOTERASE");
166       if (!fs.exists(doNotEraseDir)) {
167         fs.mkdirs(doNotEraseDir, PERM_HIDDEN);
168         fs.setPermission(doNotEraseDir, PERM_HIDDEN);
169       }
170 
171       String scheme = fs.getScheme().toLowerCase();
172       if (!fsSet.contains(scheme) && !status.getPermission().equals(PERM_HIDDEN)) {
173         throw new IllegalStateException(
174             "Staging directory of " + baseStagingDir + " already exists but permissions aren't set to '-rwx--x--x' ");
175       }
176     } catch (IOException e) {
177       throw new IllegalStateException("Failed to get FileSystem instance",e);
178     }
179   }
180 
181   Set<String> getFileSystemSchemesWithoutPermissionSupport(Configuration conf) {
182     final String value = conf.get(
183         FS_WITHOUT_SUPPORT_PERMISSION_KEY, FS_WITHOUT_SUPPORT_PERMISSION_DEFAULT);
184     return new HashSet<String>(Arrays.asList(StringUtils.split(value, ',')));
185   }
186 
187   @Override
188   public void stop(CoprocessorEnvironment env) throws IOException {
189   }
190 
191   @Override
192   public void prepareBulkLoad(RpcController controller,
193                                                  PrepareBulkLoadRequest request,
194                                                  RpcCallback<PrepareBulkLoadResponse> done){
195     try {
196       List<BulkLoadObserver> bulkLoadObservers = getBulkLoadObservers();
197 
198       if(bulkLoadObservers != null) {
199         ObserverContext<RegionCoprocessorEnvironment> ctx =
200                                            new ObserverContext<RegionCoprocessorEnvironment>();
201         ctx.prepare(env);
202 
203         for(BulkLoadObserver bulkLoadObserver : bulkLoadObservers) {
204           bulkLoadObserver.prePrepareBulkLoad(ctx, request);
205         }
206       }
207 
208       String bulkToken = createStagingDir(baseStagingDir,
209           getActiveUser(), ProtobufUtil.toTableName(request.getTableName())).toString();
210       done.run(PrepareBulkLoadResponse.newBuilder().setBulkToken(bulkToken).build());
211     } catch (IOException e) {
212       ResponseConverter.setControllerException(controller, e);
213     }
214     done.run(null);
215   }
216 
217   @Override
218   public void cleanupBulkLoad(RpcController controller,
219                               CleanupBulkLoadRequest request,
220                               RpcCallback<CleanupBulkLoadResponse> done) {
221     try {
222       List<BulkLoadObserver> bulkLoadObservers = getBulkLoadObservers();
223 
224       if(bulkLoadObservers != null) {
225         ObserverContext<RegionCoprocessorEnvironment> ctx =
226                                            new ObserverContext<RegionCoprocessorEnvironment>();
227         ctx.prepare(env);
228 
229         for(BulkLoadObserver bulkLoadObserver : bulkLoadObservers) {
230           bulkLoadObserver.preCleanupBulkLoad(ctx, request);
231         }
232       }
233 
234       fs.delete(new Path(request.getBulkToken()), true);
235       done.run(CleanupBulkLoadResponse.newBuilder().build());
236     } catch (IOException e) {
237       ResponseConverter.setControllerException(controller, e);
238     } finally {
239       UserGroupInformation ugi = getActiveUser().getUGI();
240       try {
241         if (!UserGroupInformation.getLoginUser().equals(ugi)) {
242           FileSystem.closeAllForUGI(ugi);
243         }
244       } catch (IOException e) {
245         LOG.error("Failed to close FileSystem for: " + ugi, e);
246       }
247     }
248     done.run(null);
249   }
250 
251   @Override
252   public void secureBulkLoadHFiles(RpcController controller,
253                                    SecureBulkLoadHFilesRequest request,
254                                    RpcCallback<SecureBulkLoadHFilesResponse> done) {
255     final List<Pair<byte[], String>> familyPaths = new ArrayList<Pair<byte[], String>>();
256     for(ClientProtos.BulkLoadHFileRequest.FamilyPath el : request.getFamilyPathList()) {
257       familyPaths.add(new Pair(el.getFamily().toByteArray(),el.getPath()));
258     }
259     
260     Token userToken = null;
261     if (userProvider.isHadoopSecurityEnabled()) {
262       userToken = new Token(request.getFsToken().getIdentifier().toByteArray(), request.getFsToken()
263               .getPassword().toByteArray(), new Text(request.getFsToken().getKind()), new Text(
264               request.getFsToken().getService()));
265     }
266     final String bulkToken = request.getBulkToken();
267     User user = getActiveUser();
268     final UserGroupInformation ugi = user.getUGI();
269     if(userToken != null) {
270       ugi.addToken(userToken);
271     } else if (userProvider.isHadoopSecurityEnabled()) {
272       //we allow this to pass through in "simple" security mode
273       //for mini cluster testing
274       ResponseConverter.setControllerException(controller,
275           new DoNotRetryIOException("User token cannot be null"));
276       done.run(SecureBulkLoadHFilesResponse.newBuilder().setLoaded(false).build());
277       return;
278     }
279 
280     Region region = env.getRegion();
281     boolean bypass = false;
282     if (region.getCoprocessorHost() != null) {
283       try {
284         bypass = region.getCoprocessorHost().preBulkLoadHFile(familyPaths);
285       } catch (IOException e) {
286         ResponseConverter.setControllerException(controller, e);
287         done.run(SecureBulkLoadHFilesResponse.newBuilder().setLoaded(false).build());
288         return;
289       }
290     }
291     boolean loaded = false;
292     if (!bypass) {
293       // Get the target fs (HBase region server fs) delegation token
294       // Since we have checked the permission via 'preBulkLoadHFile', now let's give
295       // the 'request user' necessary token to operate on the target fs.
296       // After this point the 'doAs' user will hold two tokens, one for the source fs
297       // ('request user'), another for the target fs (HBase region server principal).
298       if (userProvider.isHadoopSecurityEnabled()) {
299         FsDelegationToken targetfsDelegationToken = new FsDelegationToken(userProvider, "renewer");
300         try {
301           targetfsDelegationToken.acquireDelegationToken(fs);
302         } catch (IOException e) {
303           ResponseConverter.setControllerException(controller, e);
304           done.run(SecureBulkLoadHFilesResponse.newBuilder().setLoaded(false).build());
305           return;
306         }
307         Token<?> targetFsToken = targetfsDelegationToken.getUserToken();
308         if (targetFsToken != null
309             && (userToken == null || !targetFsToken.getService().equals(userToken.getService()))) {
310           ugi.addToken(targetFsToken);
311         }
312       }
313 
314       loaded = ugi.doAs(new PrivilegedAction<Boolean>() {
315         @Override
316         public Boolean run() {
317           FileSystem fs = null;
318           try {
319             Configuration conf = env.getConfiguration();
320             fs = FileSystem.get(conf);
321             for(Pair<byte[], String> el: familyPaths) {
322               Path stageFamily = new Path(bulkToken, Bytes.toString(el.getFirst()));
323               if(!fs.exists(stageFamily)) {
324                 fs.mkdirs(stageFamily);
325                 fs.setPermission(stageFamily, PERM_ALL_ACCESS);
326               }
327             }
328             //We call bulkLoadHFiles as requesting user
329             //To enable access prior to staging
330             return env.getRegion().bulkLoadHFiles(familyPaths, true,
331                 new SecureBulkLoadListener(fs, bulkToken, conf));
332           } catch (Exception e) {
333             LOG.error("Failed to complete bulk load", e);
334           }
335           return false;
336         }
337       });
338     }
339     if (region.getCoprocessorHost() != null) {
340       try {
341         loaded = region.getCoprocessorHost().postBulkLoadHFile(familyPaths, loaded);
342       } catch (IOException e) {
343         ResponseConverter.setControllerException(controller, e);
344         done.run(SecureBulkLoadHFilesResponse.newBuilder().setLoaded(false).build());
345         return;
346       }
347     }
348     done.run(SecureBulkLoadHFilesResponse.newBuilder().setLoaded(loaded).build());
349   }
350 
351   private List<BulkLoadObserver> getBulkLoadObservers() {
352     List<BulkLoadObserver> coprocessorList =
353               this.env.getRegion().getCoprocessorHost().findCoprocessors(BulkLoadObserver.class);
354 
355     return coprocessorList;
356   }
357 
358   private Path createStagingDir(Path baseDir,
359                                 User user,
360                                 TableName tableName) throws IOException {
361     String tblName = tableName.getNameAsString().replace(":", "_");
362     String randomDir = user.getShortName()+"__"+ tblName +"__"+
363         (new BigInteger(RANDOM_WIDTH, random).toString(RANDOM_RADIX));
364     return createStagingDir(baseDir, user, randomDir);
365   }
366 
367   private Path createStagingDir(Path baseDir,
368                                 User user,
369                                 String randomDir) throws IOException {
370     Path p = new Path(baseDir, randomDir);
371     fs.mkdirs(p, PERM_ALL_ACCESS);
372     fs.setPermission(p, PERM_ALL_ACCESS);
373     return p;
374   }
375 
376   private User getActiveUser() {
377     User user = RpcServer.getRequestUser();
378     if (user == null) {
379       return null;
380     }
381 
382     //this is for testing
383     if (userProvider.isHadoopSecurityEnabled()
384         && "simple".equalsIgnoreCase(conf.get(User.HBASE_SECURITY_CONF_KEY))) {
385       return User.createUserForTesting(conf, user.getShortName(), new String[]{});
386     }
387 
388     return user;
389   }
390 
391   @Override
392   public Service getService() {
393     return this;
394   }
395 
396   private static class SecureBulkLoadListener implements BulkLoadListener {
397     // Target filesystem
398     private FileSystem fs;
399     private String stagingDir;
400     private Configuration conf;
401     // Source filesystem
402     private FileSystem srcFs = null;
403     private Map<String, FsPermission> origPermissions = null;
404 
405     public SecureBulkLoadListener(FileSystem fs, String stagingDir, Configuration conf) {
406       this.fs = fs;
407       this.stagingDir = stagingDir;
408       this.conf = conf;
409       this.origPermissions = new HashMap<String, FsPermission>();
410     }
411 
412     @Override
413     public String prepareBulkLoad(final byte[] family, final String srcPath) throws IOException {
414       Path p = new Path(srcPath);
415       Path stageP = new Path(stagingDir, new Path(Bytes.toString(family), p.getName()));
416       if (srcFs == null) {
417         srcFs = FileSystem.newInstance(p.toUri(), conf);
418       }
419 
420       if(!isFile(p)) {
421         throw new IOException("Path does not reference a file: " + p);
422       }
423 
424       // Check to see if the source and target filesystems are the same
425       if (!FSHDFSUtils.isSameHdfs(conf, srcFs, fs)) {
426         LOG.debug("Bulk-load file " + srcPath + " is on different filesystem than " +
427             "the destination filesystem. Copying file over to destination staging dir.");
428         FileUtil.copy(srcFs, p, fs, stageP, false, conf);
429       } else {
430         LOG.debug("Moving " + p + " to " + stageP);
431         FileStatus origFileStatus = fs.getFileStatus(p);
432         origPermissions.put(srcPath, origFileStatus.getPermission());
433         if(!fs.rename(p, stageP)) {
434           throw new IOException("Failed to move HFile: " + p + " to " + stageP);
435         }
436       }
437       fs.setPermission(stageP, PERM_ALL_ACCESS);
438       return stageP.toString();
439     }
440 
441     @Override
442     public void doneBulkLoad(byte[] family, String srcPath) throws IOException {
443       LOG.debug("Bulk Load done for: " + srcPath);
444       closeSrcFs();
445     }
446 
447     private void closeSrcFs() throws IOException {
448       if (srcFs != null) {
449         srcFs.close();
450         srcFs = null;
451       }
452     }
453 
454     @Override
455     public void failedBulkLoad(final byte[] family, final String srcPath) throws IOException {
456       try {
457         Path p = new Path(srcPath);
458         if (srcFs == null) {
459           srcFs = FileSystem.newInstance(p.toUri(), conf);
460         }
461         if (!FSHDFSUtils.isSameHdfs(conf, srcFs, fs)) {
462           // files are copied so no need to move them back
463           return;
464         }
465         Path stageP = new Path(stagingDir, new Path(Bytes.toString(family), p.getName()));
466         LOG.debug("Moving " + stageP + " back to " + p);
467         if (!fs.rename(stageP, p))
468           throw new IOException("Failed to move HFile: " + stageP + " to " + p);
469 
470         // restore original permission
471         if (origPermissions.containsKey(srcPath)) {
472           fs.setPermission(p, origPermissions.get(srcPath));
473         } else {
474           LOG.warn("Can't find previous permission for path=" + srcPath);
475         }
476       } finally {
477         closeSrcFs();
478       }
479     }
480 
481     /**
482      * Check if the path is referencing a file.
483      * This is mainly needed to avoid symlinks.
484      * @param p
485      * @return true if the p is a file
486      * @throws IOException
487      */
488     private boolean isFile(Path p) throws IOException {
489       FileStatus status = srcFs.getFileStatus(p);
490       boolean isFile = !status.isDirectory();
491       try {
492         isFile = isFile && !(Boolean)Methods.call(FileStatus.class, status, "isSymlink", null, null);
493       } catch (Exception e) {
494       }
495       return isFile;
496     }
497   }
498 }