1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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
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
131
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
158
159 if (!status.getPermission().equals(PERM_HIDDEN)) {
160 fs.setPermission(baseStagingDir, PERM_HIDDEN);
161 status = fs.getFileStatus(baseStagingDir);
162 }
163
164
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
273
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
294
295
296
297
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
329
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
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
398 private FileSystem fs;
399 private String stagingDir;
400 private Configuration conf;
401
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
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
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
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
483
484
485
486
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 }