1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.apache.hadoop.hbase.security.access;
16
17 import java.io.IOException;
18 import java.net.InetAddress;
19 import java.security.PrivilegedExceptionAction;
20 import java.util.Collection;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Set;
27 import java.util.TreeMap;
28 import java.util.TreeSet;
29
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32 import org.apache.hadoop.conf.Configuration;
33 import org.apache.hadoop.hbase.Cell;
34 import org.apache.hadoop.hbase.CellScanner;
35 import org.apache.hadoop.hbase.CellUtil;
36 import org.apache.hadoop.hbase.CompoundConfiguration;
37 import org.apache.hadoop.hbase.CoprocessorEnvironment;
38 import org.apache.hadoop.hbase.DoNotRetryIOException;
39 import org.apache.hadoop.hbase.HBaseInterfaceAudience;
40 import org.apache.hadoop.hbase.HColumnDescriptor;
41 import org.apache.hadoop.hbase.HConstants;
42 import org.apache.hadoop.hbase.HRegionInfo;
43 import org.apache.hadoop.hbase.HTableDescriptor;
44 import org.apache.hadoop.hbase.KeyValue;
45 import org.apache.hadoop.hbase.KeyValue.Type;
46 import org.apache.hadoop.hbase.MetaTableAccessor;
47 import org.apache.hadoop.hbase.NamespaceDescriptor;
48 import org.apache.hadoop.hbase.ServerName;
49 import org.apache.hadoop.hbase.TableName;
50 import org.apache.hadoop.hbase.Tag;
51 import org.apache.hadoop.hbase.TagRewriteCell;
52 import org.apache.hadoop.hbase.classification.InterfaceAudience;
53 import org.apache.hadoop.hbase.client.Append;
54 import org.apache.hadoop.hbase.client.Delete;
55 import org.apache.hadoop.hbase.client.Durability;
56 import org.apache.hadoop.hbase.client.Get;
57 import org.apache.hadoop.hbase.client.Increment;
58 import org.apache.hadoop.hbase.client.Mutation;
59 import org.apache.hadoop.hbase.client.Put;
60 import org.apache.hadoop.hbase.client.Query;
61 import org.apache.hadoop.hbase.client.Result;
62 import org.apache.hadoop.hbase.client.Scan;
63 import org.apache.hadoop.hbase.coprocessor.BaseMasterAndRegionObserver;
64 import org.apache.hadoop.hbase.coprocessor.BulkLoadObserver;
65 import org.apache.hadoop.hbase.coprocessor.CoprocessorException;
66 import org.apache.hadoop.hbase.coprocessor.CoprocessorService;
67 import org.apache.hadoop.hbase.coprocessor.EndpointObserver;
68 import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment;
69 import org.apache.hadoop.hbase.coprocessor.ObserverContext;
70 import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
71 import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessorEnvironment;
72 import org.apache.hadoop.hbase.coprocessor.RegionServerObserver;
73 import org.apache.hadoop.hbase.filter.ByteArrayComparable;
74 import org.apache.hadoop.hbase.filter.CompareFilter;
75 import org.apache.hadoop.hbase.filter.Filter;
76 import org.apache.hadoop.hbase.filter.FilterList;
77 import org.apache.hadoop.hbase.io.hfile.HFile;
78 import org.apache.hadoop.hbase.ipc.RpcServer;
79 import org.apache.hadoop.hbase.master.MasterServices;
80 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
81 import org.apache.hadoop.hbase.protobuf.ResponseConverter;
82 import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos;
83 import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.AccessControlService;
84 import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.WALEntry;
85 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
86 import org.apache.hadoop.hbase.protobuf.generated.QuotaProtos.Quotas;
87 import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.CleanupBulkLoadRequest;
88 import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.PrepareBulkLoadRequest;
89 import org.apache.hadoop.hbase.regionserver.InternalScanner;
90 import org.apache.hadoop.hbase.regionserver.MiniBatchOperationInProgress;
91 import org.apache.hadoop.hbase.regionserver.Region;
92 import org.apache.hadoop.hbase.regionserver.RegionScanner;
93 import org.apache.hadoop.hbase.regionserver.ScanType;
94 import org.apache.hadoop.hbase.regionserver.ScannerContext;
95 import org.apache.hadoop.hbase.regionserver.Store;
96 import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
97 import org.apache.hadoop.hbase.replication.ReplicationEndpoint;
98 import org.apache.hadoop.hbase.security.AccessDeniedException;
99 import org.apache.hadoop.hbase.security.User;
100 import org.apache.hadoop.hbase.security.UserProvider;
101 import org.apache.hadoop.hbase.security.access.Permission.Action;
102 import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
103 import org.apache.hadoop.hbase.util.ByteRange;
104 import org.apache.hadoop.hbase.util.Bytes;
105 import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
106 import org.apache.hadoop.hbase.util.Pair;
107 import org.apache.hadoop.hbase.util.SimpleMutableByteRange;
108 import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
109
110 import com.google.common.collect.ArrayListMultimap;
111 import com.google.common.collect.ImmutableSet;
112 import com.google.common.collect.ListMultimap;
113 import com.google.common.collect.Lists;
114 import com.google.common.collect.MapMaker;
115 import com.google.common.collect.Maps;
116 import com.google.common.collect.Sets;
117 import com.google.protobuf.Message;
118 import com.google.protobuf.RpcCallback;
119 import com.google.protobuf.RpcController;
120 import com.google.protobuf.Service;
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153 @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.CONFIG)
154 public class AccessController extends BaseMasterAndRegionObserver
155 implements RegionServerObserver,
156 AccessControlService.Interface, CoprocessorService, EndpointObserver, BulkLoadObserver {
157
158 public static final Log LOG = LogFactory.getLog(AccessController.class);
159
160 private static final Log AUDITLOG =
161 LogFactory.getLog("SecurityLogger."+AccessController.class.getName());
162 private static final String CHECK_COVERING_PERM = "check_covering_perm";
163 private static final String TAG_CHECK_PASSED = "tag_check_passed";
164 private static final byte[] TRUE = Bytes.toBytes(true);
165
166 TableAuthManager authManager = null;
167
168
169 boolean aclRegion = false;
170
171
172
173 private RegionCoprocessorEnvironment regionEnv;
174
175
176 private Map<InternalScanner,String> scannerOwners =
177 new MapMaker().weakKeys().makeMap();
178
179 private Map<TableName, List<UserPermission>> tableAcls;
180
181
182 private UserProvider userProvider;
183
184
185 private List<String> superusers;
186
187
188
189 boolean authorizationEnabled;
190
191
192 boolean cellFeaturesEnabled;
193
194
195 boolean shouldCheckExecPermission;
196
197
198
199 boolean compatibleEarlyTermination;
200
201
202 private volatile boolean initialized = false;
203
204
205 private volatile boolean aclTabAvailable = false;
206
207 public Region getRegion() {
208 return regionEnv != null ? regionEnv.getRegion() : null;
209 }
210
211 public TableAuthManager getAuthManager() {
212 return authManager;
213 }
214
215 void initialize(RegionCoprocessorEnvironment e) throws IOException {
216 final Region region = e.getRegion();
217 Configuration conf = e.getConfiguration();
218 Map<byte[], ListMultimap<String,TablePermission>> tables =
219 AccessControlLists.loadAll(region);
220
221
222 for (Map.Entry<byte[], ListMultimap<String,TablePermission>> t:
223 tables.entrySet()) {
224 byte[] entry = t.getKey();
225 ListMultimap<String,TablePermission> perms = t.getValue();
226 byte[] serialized = AccessControlLists.writePermissionsAsBytes(perms, conf);
227 this.authManager.getZKPermissionWatcher().writeToZookeeper(entry, serialized);
228 }
229 initialized = true;
230 }
231
232
233
234
235
236
237 void updateACL(RegionCoprocessorEnvironment e,
238 final Map<byte[], List<Cell>> familyMap) {
239 Set<byte[]> entries =
240 new TreeSet<byte[]>(Bytes.BYTES_RAWCOMPARATOR);
241 for (Map.Entry<byte[], List<Cell>> f : familyMap.entrySet()) {
242 List<Cell> cells = f.getValue();
243 for (Cell cell: cells) {
244 if (Bytes.equals(cell.getFamilyArray(), cell.getFamilyOffset(),
245 cell.getFamilyLength(), AccessControlLists.ACL_LIST_FAMILY, 0,
246 AccessControlLists.ACL_LIST_FAMILY.length)) {
247 entries.add(CellUtil.cloneRow(cell));
248 }
249 }
250 }
251 ZKPermissionWatcher zkw = this.authManager.getZKPermissionWatcher();
252 Configuration conf = regionEnv.getConfiguration();
253 for (byte[] entry: entries) {
254 try {
255 ListMultimap<String,TablePermission> perms =
256 AccessControlLists.getPermissions(conf, entry);
257 byte[] serialized = AccessControlLists.writePermissionsAsBytes(perms, conf);
258 zkw.writeToZookeeper(entry, serialized);
259 } catch (IOException ex) {
260 LOG.error("Failed updating permissions mirror for '" + Bytes.toString(entry) + "'",
261 ex);
262 }
263 }
264 }
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280 AuthResult permissionGranted(String request, User user, Action permRequest,
281 RegionCoprocessorEnvironment e,
282 Map<byte [], ? extends Collection<?>> families) {
283 HRegionInfo hri = e.getRegion().getRegionInfo();
284 TableName tableName = hri.getTable();
285
286
287
288 if (hri.isMetaRegion()) {
289 if (permRequest == Action.READ) {
290 return AuthResult.allow(request, "All users allowed", user,
291 permRequest, tableName, families);
292 }
293 }
294
295 if (user == null) {
296 return AuthResult.deny(request, "No user associated with request!", null,
297 permRequest, tableName, families);
298 }
299
300
301 if (authManager.authorize(user, tableName, (byte[])null, permRequest)) {
302 return AuthResult.allow(request, "Table permission granted", user,
303 permRequest, tableName, families);
304 }
305
306
307 if (families != null && families.size() > 0) {
308
309 for (Map.Entry<byte [], ? extends Collection<?>> family : families.entrySet()) {
310
311 if (authManager.authorize(user, tableName, family.getKey(),
312 permRequest)) {
313 continue;
314 }
315
316
317 if ((family.getValue() != null) && (family.getValue().size() > 0)) {
318 if (family.getValue() instanceof Set) {
319
320 Set<byte[]> familySet = (Set<byte[]>)family.getValue();
321 for (byte[] qualifier : familySet) {
322 if (!authManager.authorize(user, tableName, family.getKey(),
323 qualifier, permRequest)) {
324 return AuthResult.deny(request, "Failed qualifier check", user,
325 permRequest, tableName, makeFamilyMap(family.getKey(), qualifier));
326 }
327 }
328 } else if (family.getValue() instanceof List) {
329 List<KeyValue> kvList = (List<KeyValue>)family.getValue();
330 for (KeyValue kv : kvList) {
331 if (!authManager.authorize(user, tableName, family.getKey(),
332 kv.getQualifier(), permRequest)) {
333 return AuthResult.deny(request, "Failed qualifier check", user,
334 permRequest, tableName, makeFamilyMap(family.getKey(), kv.getQualifier()));
335 }
336 }
337 }
338 } else {
339
340 return AuthResult.deny(request, "Failed family check", user, permRequest,
341 tableName, makeFamilyMap(family.getKey(), null));
342 }
343 }
344
345
346 return AuthResult.allow(request, "All family checks passed", user, permRequest,
347 tableName, families);
348 }
349
350
351 return AuthResult.deny(request, "No families to check and table permission failed",
352 user, permRequest, tableName, families);
353 }
354
355
356
357
358
359
360
361
362
363
364
365
366 AuthResult permissionGranted(OpType opType, User user, RegionCoprocessorEnvironment e,
367 Map<byte [], ? extends Collection<?>> families, Action... actions) {
368 AuthResult result = null;
369 for (Action action: actions) {
370 result = permissionGranted(opType.toString(), user, action, e, families);
371 if (!result.isAllowed()) {
372 return result;
373 }
374 }
375 return result;
376 }
377
378 private void logResult(AuthResult result) {
379 if (AUDITLOG.isTraceEnabled()) {
380 InetAddress remoteAddr = RpcServer.getRemoteAddress();
381 AUDITLOG.trace("Access " + (result.isAllowed() ? "allowed" : "denied") +
382 " for user " + (result.getUser() != null ? result.getUser().getShortName() : "UNKNOWN") +
383 "; reason: " + result.getReason() +
384 "; remote address: " + (remoteAddr != null ? remoteAddr : "") +
385 "; request: " + result.getRequest() +
386 "; context: " + result.toContextString());
387 }
388 }
389
390
391
392
393
394
395 private User getActiveUser() throws IOException {
396 User user = RpcServer.getRequestUser();
397 if (user == null) {
398
399 user = userProvider.getCurrent();
400 }
401 return user;
402 }
403
404
405
406
407
408
409
410
411
412
413 private void requirePermission(String request, TableName tableName, byte[] family,
414 byte[] qualifier, Action... permissions) throws IOException {
415 User user = getActiveUser();
416 AuthResult result = null;
417
418 for (Action permission : permissions) {
419 if (authManager.authorize(user, tableName, family, qualifier, permission)) {
420 result = AuthResult.allow(request, "Table permission granted", user,
421 permission, tableName, family, qualifier);
422 break;
423 } else {
424
425 result = AuthResult.deny(request, "Insufficient permissions", user,
426 permission, tableName, family, qualifier);
427 }
428 }
429 logResult(result);
430 if (authorizationEnabled && !result.isAllowed()) {
431 throw new AccessDeniedException("Insufficient permissions " + result.toContextString());
432 }
433 }
434
435
436
437
438
439
440
441
442
443
444 private void requireTablePermission(String request, TableName tableName, byte[] family,
445 byte[] qualifier, Action... permissions) throws IOException {
446 User user = getActiveUser();
447 AuthResult result = null;
448
449 for (Action permission : permissions) {
450 if (authManager.authorize(user, tableName, null, null, permission)) {
451 result = AuthResult.allow(request, "Table permission granted", user,
452 permission, tableName, null, null);
453 result.getParams().setFamily(family).setQualifier(qualifier);
454 break;
455 } else {
456
457 result = AuthResult.deny(request, "Insufficient permissions", user,
458 permission, tableName, family, qualifier);
459 result.getParams().setFamily(family).setQualifier(qualifier);
460 }
461 }
462 logResult(result);
463 if (authorizationEnabled && !result.isAllowed()) {
464 throw new AccessDeniedException("Insufficient permissions " + result.toContextString());
465 }
466 }
467
468
469
470
471
472
473
474
475
476 private void requireAccess(String request, TableName tableName,
477 Action... permissions) throws IOException {
478 User user = getActiveUser();
479 AuthResult result = null;
480
481 for (Action permission : permissions) {
482 if (authManager.hasAccess(user, tableName, permission)) {
483 result = AuthResult.allow(request, "Table permission granted", user,
484 permission, tableName, null, null);
485 break;
486 } else {
487
488 result = AuthResult.deny(request, "Insufficient permissions", user,
489 permission, tableName, null, null);
490 }
491 }
492 logResult(result);
493 if (authorizationEnabled && !result.isAllowed()) {
494 throw new AccessDeniedException("Insufficient permissions " + result.toContextString());
495 }
496 }
497
498
499
500
501
502
503
504 private void requirePermission(String request, Action perm) throws IOException {
505 requireGlobalPermission(request, perm, null, null);
506 }
507
508
509
510
511
512
513
514
515
516 private void requireGlobalPermission(String request, Action perm, TableName tableName,
517 Map<byte[], ? extends Collection<byte[]>> familyMap) throws IOException {
518 User user = getActiveUser();
519 AuthResult result = null;
520 if (authManager.authorize(user, perm)) {
521 result = AuthResult.allow(request, "Global check allowed", user, perm, tableName, familyMap);
522 result.getParams().setTableName(tableName).setFamilies(familyMap);
523 logResult(result);
524 } else {
525 result = AuthResult.deny(request, "Global check failed", user, perm, tableName, familyMap);
526 result.getParams().setTableName(tableName).setFamilies(familyMap);
527 logResult(result);
528 if (authorizationEnabled) {
529 throw new AccessDeniedException("Insufficient permissions for user '" +
530 (user != null ? user.getShortName() : "null") +"' (global, action=" +
531 perm.toString() + ")");
532 }
533 }
534 }
535
536
537
538
539
540
541
542
543 private void requireGlobalPermission(String request, Action perm,
544 String namespace) throws IOException {
545 User user = getActiveUser();
546 AuthResult authResult = null;
547 if (authManager.authorize(user, perm)) {
548 authResult = AuthResult.allow(request, "Global check allowed", user, perm, null);
549 authResult.getParams().setNamespace(namespace);
550 logResult(authResult);
551 } else {
552 authResult = AuthResult.deny(request, "Global check failed", user, perm, null);
553 authResult.getParams().setNamespace(namespace);
554 logResult(authResult);
555 if (authorizationEnabled) {
556 throw new AccessDeniedException("Insufficient permissions for user '" +
557 (user != null ? user.getShortName() : "null") +"' (global, action=" +
558 perm.toString() + ")");
559 }
560 }
561 }
562
563
564
565
566
567
568 public void requireNamespacePermission(String request, String namespace,
569 Action... permissions) throws IOException {
570 User user = getActiveUser();
571 AuthResult result = null;
572
573 for (Action permission : permissions) {
574 if (authManager.authorize(user, namespace, permission)) {
575 result = AuthResult.allow(request, "Namespace permission granted",
576 user, permission, namespace);
577 break;
578 } else {
579
580 result = AuthResult.deny(request, "Insufficient permissions", user,
581 permission, namespace);
582 }
583 }
584 logResult(result);
585 if (authorizationEnabled && !result.isAllowed()) {
586 throw new AccessDeniedException("Insufficient permissions "
587 + result.toContextString());
588 }
589 }
590
591
592
593
594
595
596 public void requireNamespacePermission(String request, String namespace, TableName tableName,
597 Map<byte[], ? extends Collection<byte[]>> familyMap, Action... permissions)
598 throws IOException {
599 User user = getActiveUser();
600 AuthResult result = null;
601
602 for (Action permission : permissions) {
603 if (authManager.authorize(user, namespace, permission)) {
604 result = AuthResult.allow(request, "Namespace permission granted",
605 user, permission, namespace);
606 result.getParams().setTableName(tableName).setFamilies(familyMap);
607 break;
608 } else {
609
610 result = AuthResult.deny(request, "Insufficient permissions", user,
611 permission, namespace);
612 result.getParams().setTableName(tableName).setFamilies(familyMap);
613 }
614 }
615 logResult(result);
616 if (authorizationEnabled && !result.isAllowed()) {
617 throw new AccessDeniedException("Insufficient permissions "
618 + result.toContextString());
619 }
620 }
621
622
623
624
625
626 private boolean hasFamilyQualifierPermission(User user,
627 Action perm,
628 RegionCoprocessorEnvironment env,
629 Map<byte[], ? extends Collection<byte[]>> familyMap)
630 throws IOException {
631 HRegionInfo hri = env.getRegion().getRegionInfo();
632 TableName tableName = hri.getTable();
633
634 if (user == null) {
635 return false;
636 }
637
638 if (familyMap != null && familyMap.size() > 0) {
639
640 for (Map.Entry<byte[], ? extends Collection<byte[]>> family :
641 familyMap.entrySet()) {
642 if (family.getValue() != null && !family.getValue().isEmpty()) {
643 for (byte[] qualifier : family.getValue()) {
644 if (authManager.matchPermission(user, tableName,
645 family.getKey(), qualifier, perm)) {
646 return true;
647 }
648 }
649 } else {
650 if (authManager.matchPermission(user, tableName, family.getKey(),
651 perm)) {
652 return true;
653 }
654 }
655 }
656 } else if (LOG.isDebugEnabled()) {
657 LOG.debug("Empty family map passed for permission check");
658 }
659
660 return false;
661 }
662
663 private enum OpType {
664 GET_CLOSEST_ROW_BEFORE("getClosestRowBefore"),
665 GET("get"),
666 EXISTS("exists"),
667 SCAN("scan"),
668 PUT("put"),
669 DELETE("delete"),
670 CHECK_AND_PUT("checkAndPut"),
671 CHECK_AND_DELETE("checkAndDelete"),
672 INCREMENT_COLUMN_VALUE("incrementColumnValue"),
673 APPEND("append"),
674 INCREMENT("increment");
675
676 private String type;
677
678 private OpType(String type) {
679 this.type = type;
680 }
681
682 @Override
683 public String toString() {
684 return type;
685 }
686 }
687
688
689
690
691
692
693 private boolean checkCoveringPermission(OpType request, RegionCoprocessorEnvironment e,
694 byte[] row, Map<byte[], ? extends Collection<?>> familyMap, long opTs, Action... actions)
695 throws IOException {
696 if (!cellFeaturesEnabled) {
697 return false;
698 }
699 long cellGrants = 0;
700 User user = getActiveUser();
701 long latestCellTs = 0;
702 Get get = new Get(row);
703
704
705
706
707
708
709
710 boolean considerCellTs = (request == OpType.PUT || request == OpType.DELETE);
711 if (considerCellTs) {
712 get.setMaxVersions();
713 } else {
714 get.setMaxVersions(1);
715 }
716 boolean diffCellTsFromOpTs = false;
717 for (Map.Entry<byte[], ? extends Collection<?>> entry: familyMap.entrySet()) {
718 byte[] col = entry.getKey();
719
720
721 if (entry.getValue() instanceof Set) {
722 Set<byte[]> set = (Set<byte[]>)entry.getValue();
723 if (set == null || set.isEmpty()) {
724 get.addFamily(col);
725 } else {
726 for (byte[] qual: set) {
727 get.addColumn(col, qual);
728 }
729 }
730 } else if (entry.getValue() instanceof List) {
731 List<Cell> list = (List<Cell>)entry.getValue();
732 if (list == null || list.isEmpty()) {
733 get.addFamily(col);
734 } else {
735
736 for (Cell cell : list) {
737 if (cell.getQualifierLength() == 0
738 && (cell.getTypeByte() == Type.DeleteFamily.getCode()
739 || cell.getTypeByte() == Type.DeleteFamilyVersion.getCode())) {
740 get.addFamily(col);
741 } else {
742 get.addColumn(col, CellUtil.cloneQualifier(cell));
743 }
744 if (considerCellTs) {
745 long cellTs = cell.getTimestamp();
746 latestCellTs = Math.max(latestCellTs, cellTs);
747 diffCellTsFromOpTs = diffCellTsFromOpTs || (opTs != cellTs);
748 }
749 }
750 }
751 } else if (entry.getValue() == null) {
752 get.addFamily(col);
753 } else {
754 throw new RuntimeException("Unhandled collection type " +
755 entry.getValue().getClass().getName());
756 }
757 }
758
759
760
761
762
763
764 long latestTs = Math.max(opTs, latestCellTs);
765 if (latestTs == 0 || latestTs == HConstants.LATEST_TIMESTAMP) {
766 latestTs = EnvironmentEdgeManager.currentTime();
767 }
768 get.setTimeRange(0, latestTs + 1);
769
770
771
772 if (!diffCellTsFromOpTs && request == OpType.PUT) {
773 get.setMaxVersions(1);
774 }
775 if (LOG.isTraceEnabled()) {
776 LOG.trace("Scanning for cells with " + get);
777 }
778
779
780
781 Map<ByteRange, List<Cell>> familyMap1 = new HashMap<ByteRange, List<Cell>>();
782 for (Entry<byte[], ? extends Collection<?>> entry : familyMap.entrySet()) {
783 if (entry.getValue() instanceof List) {
784 familyMap1.put(new SimpleMutableByteRange(entry.getKey()), (List<Cell>) entry.getValue());
785 }
786 }
787 RegionScanner scanner = getRegion(e).getScanner(new Scan(get));
788 List<Cell> cells = Lists.newArrayList();
789 Cell prevCell = null;
790 ByteRange curFam = new SimpleMutableByteRange();
791 boolean curColAllVersions = (request == OpType.DELETE);
792 long curColCheckTs = opTs;
793 boolean foundColumn = false;
794 try {
795 boolean more = false;
796 ScannerContext scannerContext = ScannerContext.newBuilder().setBatchLimit(1).build();
797
798 do {
799 cells.clear();
800
801 more = scanner.next(cells, scannerContext);
802 for (Cell cell: cells) {
803 if (LOG.isTraceEnabled()) {
804 LOG.trace("Found cell " + cell);
805 }
806 boolean colChange = prevCell == null || !CellUtil.matchingColumn(prevCell, cell);
807 if (colChange) foundColumn = false;
808 prevCell = cell;
809 if (!curColAllVersions && foundColumn) {
810 continue;
811 }
812 if (colChange && considerCellTs) {
813 curFam.set(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength());
814 List<Cell> cols = familyMap1.get(curFam);
815 for (Cell col : cols) {
816
817
818
819 if ((col.getQualifierLength() == 0 && request == OpType.DELETE)
820 || CellUtil.matchingQualifier(cell, col)) {
821 byte type = col.getTypeByte();
822 if (considerCellTs) {
823 curColCheckTs = col.getTimestamp();
824 }
825
826
827
828
829 curColAllVersions = (KeyValue.Type.DeleteColumn.getCode() == type)
830 || (KeyValue.Type.DeleteFamily.getCode() == type);
831 break;
832 }
833 }
834 }
835 if (cell.getTimestamp() > curColCheckTs) {
836
837 continue;
838 }
839 foundColumn = true;
840 for (Action action: actions) {
841
842 if (!authManager.authorize(user, getTableName(e), cell, action)) {
843
844 return false;
845 }
846 }
847 cellGrants++;
848 }
849 } while (more);
850 } catch (AccessDeniedException ex) {
851 throw ex;
852 } catch (IOException ex) {
853 LOG.error("Exception while getting cells to calculate covering permission", ex);
854 } finally {
855 scanner.close();
856 }
857
858
859
860 return cellGrants > 0;
861 }
862
863 private static void addCellPermissions(final byte[] perms, Map<byte[], List<Cell>> familyMap) {
864
865
866 for (Map.Entry<byte[], List<Cell>> e: familyMap.entrySet()) {
867 List<Cell> newCells = Lists.newArrayList();
868 for (Cell cell: e.getValue()) {
869
870 List<Tag> tags = Lists.newArrayList(new Tag(AccessControlLists.ACL_TAG_TYPE, perms));
871 if (cell.getTagsLength() > 0) {
872 Iterator<Tag> tagIterator = CellUtil.tagsIterator(cell.getTagsArray(),
873 cell.getTagsOffset(), cell.getTagsLength());
874 while (tagIterator.hasNext()) {
875 tags.add(tagIterator.next());
876 }
877 }
878 newCells.add(new TagRewriteCell(cell, Tag.fromList(tags)));
879 }
880
881 e.setValue(newCells);
882 }
883 }
884
885
886
887 private void checkForReservedTagPresence(User user, Mutation m) throws IOException {
888
889 if (!authorizationEnabled) {
890 m.setAttribute(TAG_CHECK_PASSED, TRUE);
891 return;
892 }
893
894 if (superusers.contains(user.getShortName())) {
895 m.setAttribute(TAG_CHECK_PASSED, TRUE);
896 return;
897 }
898
899 if (m.getAttribute(TAG_CHECK_PASSED) != null) {
900 return;
901 }
902 for (CellScanner cellScanner = m.cellScanner(); cellScanner.advance();) {
903 Cell cell = cellScanner.current();
904 if (cell.getTagsLength() > 0) {
905 Iterator<Tag> tagsItr = CellUtil.tagsIterator(cell.getTagsArray(), cell.getTagsOffset(),
906 cell.getTagsLength());
907 while (tagsItr.hasNext()) {
908 if (tagsItr.next().getType() == AccessControlLists.ACL_TAG_TYPE) {
909 throw new AccessDeniedException("Mutation contains cell with reserved type tag");
910 }
911 }
912 }
913 }
914 m.setAttribute(TAG_CHECK_PASSED, TRUE);
915 }
916
917
918 @Override
919 public void start(CoprocessorEnvironment env) throws IOException {
920 CompoundConfiguration conf = new CompoundConfiguration();
921 conf.add(env.getConfiguration());
922
923 authorizationEnabled = conf.getBoolean(User.HBASE_SECURITY_AUTHORIZATION_CONF_KEY, true);
924 if (!authorizationEnabled) {
925 LOG.warn("The AccessController has been loaded with authorization checks disabled.");
926 }
927
928 shouldCheckExecPermission = conf.getBoolean(AccessControlConstants.EXEC_PERMISSION_CHECKS_KEY,
929 AccessControlConstants.DEFAULT_EXEC_PERMISSION_CHECKS);
930
931 cellFeaturesEnabled = HFile.getFormatVersion(conf) >= HFile.MIN_FORMAT_VERSION_WITH_TAGS;
932 if (!cellFeaturesEnabled) {
933 LOG.info("A minimum HFile version of " + HFile.MIN_FORMAT_VERSION_WITH_TAGS
934 + " is required to persist cell ACLs. Consider setting " + HFile.FORMAT_VERSION_KEY
935 + " accordingly.");
936 }
937
938 ZooKeeperWatcher zk = null;
939 if (env instanceof MasterCoprocessorEnvironment) {
940
941 MasterCoprocessorEnvironment mEnv = (MasterCoprocessorEnvironment) env;
942 zk = mEnv.getMasterServices().getZooKeeper();
943 } else if (env instanceof RegionServerCoprocessorEnvironment) {
944 RegionServerCoprocessorEnvironment rsEnv = (RegionServerCoprocessorEnvironment) env;
945 zk = rsEnv.getRegionServerServices().getZooKeeper();
946 } else if (env instanceof RegionCoprocessorEnvironment) {
947
948 regionEnv = (RegionCoprocessorEnvironment) env;
949 conf.addStringMap(regionEnv.getRegion().getTableDesc().getConfiguration());
950 zk = regionEnv.getRegionServerServices().getZooKeeper();
951 compatibleEarlyTermination = conf.getBoolean(AccessControlConstants.CF_ATTRIBUTE_EARLY_OUT,
952 AccessControlConstants.DEFAULT_ATTRIBUTE_EARLY_OUT);
953 }
954
955
956 this.userProvider = UserProvider.instantiate(env.getConfiguration());
957
958
959 User user = userProvider.getCurrent();
960 superusers = Lists.asList(user.getShortName(),
961 conf.getStrings(AccessControlLists.SUPERUSER_CONF_KEY, new String[0]));
962
963
964
965 if (zk != null) {
966 try {
967 this.authManager = TableAuthManager.get(zk, env.getConfiguration());
968 } catch (IOException ioe) {
969 throw new RuntimeException("Error obtaining TableAuthManager", ioe);
970 }
971 } else {
972 throw new RuntimeException("Error obtaining TableAuthManager, zk found null.");
973 }
974
975 tableAcls = new MapMaker().weakValues().makeMap();
976 }
977
978 @Override
979 public void stop(CoprocessorEnvironment env) {
980
981 }
982
983 @Override
984 public void preCreateTable(ObserverContext<MasterCoprocessorEnvironment> c,
985 HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
986 Set<byte[]> families = desc.getFamiliesKeys();
987 Map<byte[], Set<byte[]>> familyMap = new TreeMap<byte[], Set<byte[]>>(Bytes.BYTES_COMPARATOR);
988 for (byte[] family: families) {
989 familyMap.put(family, null);
990 }
991 requireNamespacePermission("createTable", desc.getTableName().getNamespaceAsString(),
992 desc.getTableName(), familyMap, Action.CREATE);
993 }
994
995 @Override
996 public void postCreateTableHandler(final ObserverContext<MasterCoprocessorEnvironment> c,
997 HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013 if (AccessControlLists.isAclTable(desc)) {
1014 this.aclTabAvailable = true;
1015 } else if (!(TableName.NAMESPACE_TABLE_NAME.equals(desc.getTableName()))) {
1016 if (!aclTabAvailable) {
1017 LOG.warn("Not adding owner permission for table " + desc.getTableName() + ". "
1018 + AccessControlLists.ACL_TABLE_NAME + " is not yet created. "
1019 + getClass().getSimpleName() + " should be configured as the first Coprocessor");
1020 } else {
1021 String owner = desc.getOwnerString();
1022
1023 if (owner == null)
1024 owner = getActiveUser().getShortName();
1025 final UserPermission userperm = new UserPermission(Bytes.toBytes(owner),
1026 desc.getTableName(), null, Action.values());
1027
1028 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() {
1029 @Override
1030 public Void run() throws Exception {
1031 AccessControlLists.addUserPermission(c.getEnvironment().getConfiguration(),
1032 userperm);
1033 return null;
1034 }
1035 });
1036 }
1037 }
1038 }
1039
1040 @Override
1041 public void preDeleteTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName)
1042 throws IOException {
1043 requirePermission("deleteTable", tableName, null, null, Action.ADMIN, Action.CREATE);
1044 }
1045
1046 @Override
1047 public void postDeleteTable(ObserverContext<MasterCoprocessorEnvironment> c,
1048 final TableName tableName) throws IOException {
1049 final Configuration conf = c.getEnvironment().getConfiguration();
1050 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() {
1051 @Override
1052 public Void run() throws Exception {
1053 AccessControlLists.removeTablePermissions(conf, tableName);
1054 return null;
1055 }
1056 });
1057 this.authManager.getZKPermissionWatcher().deleteTableACLNode(tableName);
1058 }
1059
1060 @Override
1061 public void preTruncateTable(ObserverContext<MasterCoprocessorEnvironment> c,
1062 final TableName tableName) throws IOException {
1063 requirePermission("truncateTable", tableName, null, null, Action.ADMIN, Action.CREATE);
1064
1065 final Configuration conf = c.getEnvironment().getConfiguration();
1066 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() {
1067 @Override
1068 public Void run() throws Exception {
1069 List<UserPermission> acls = AccessControlLists.getUserTablePermissions(conf, tableName);
1070 if (acls != null) {
1071 tableAcls.put(tableName, acls);
1072 }
1073 return null;
1074 }
1075 });
1076 }
1077
1078 @Override
1079 public void postTruncateTable(ObserverContext<MasterCoprocessorEnvironment> ctx,
1080 final TableName tableName) throws IOException {
1081 final Configuration conf = ctx.getEnvironment().getConfiguration();
1082 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() {
1083 @Override
1084 public Void run() throws Exception {
1085 List<UserPermission> perms = tableAcls.get(tableName);
1086 if (perms != null) {
1087 for (UserPermission perm : perms) {
1088 AccessControlLists.addUserPermission(conf, perm);
1089 }
1090 }
1091 tableAcls.remove(tableName);
1092 return null;
1093 }
1094 });
1095 }
1096
1097 @Override
1098 public void preModifyTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName,
1099 HTableDescriptor htd) throws IOException {
1100 requirePermission("modifyTable", tableName, null, null, Action.ADMIN, Action.CREATE);
1101 }
1102
1103 @Override
1104 public void postModifyTable(ObserverContext<MasterCoprocessorEnvironment> c,
1105 TableName tableName, final HTableDescriptor htd) throws IOException {
1106 final Configuration conf = c.getEnvironment().getConfiguration();
1107
1108 final String owner = (htd.getOwnerString() != null) ? htd.getOwnerString() :
1109 getActiveUser().getShortName();
1110 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() {
1111 @Override
1112 public Void run() throws Exception {
1113 UserPermission userperm = new UserPermission(Bytes.toBytes(owner),
1114 htd.getTableName(), null, Action.values());
1115 AccessControlLists.addUserPermission(conf, userperm);
1116 return null;
1117 }
1118 });
1119 }
1120
1121 @Override
1122 public void preAddColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName,
1123 HColumnDescriptor column) throws IOException {
1124 requireTablePermission("addColumn", tableName, column.getName(), null, Action.ADMIN,
1125 Action.CREATE);
1126 }
1127
1128 @Override
1129 public void preModifyColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName,
1130 HColumnDescriptor descriptor) throws IOException {
1131 requirePermission("modifyColumn", tableName, descriptor.getName(), null, Action.ADMIN,
1132 Action.CREATE);
1133 }
1134
1135 @Override
1136 public void preDeleteColumn(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName,
1137 byte[] col) throws IOException {
1138 requirePermission("deleteColumn", tableName, col, null, Action.ADMIN, Action.CREATE);
1139 }
1140
1141 @Override
1142 public void postDeleteColumn(ObserverContext<MasterCoprocessorEnvironment> c,
1143 final TableName tableName, final byte[] col) throws IOException {
1144 final Configuration conf = c.getEnvironment().getConfiguration();
1145 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() {
1146 @Override
1147 public Void run() throws Exception {
1148 AccessControlLists.removeTablePermissions(conf, tableName, col);
1149 return null;
1150 }
1151 });
1152 }
1153
1154 @Override
1155 public void preEnableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName)
1156 throws IOException {
1157 requirePermission("enableTable", tableName, null, null, Action.ADMIN, Action.CREATE);
1158 }
1159
1160 @Override
1161 public void preDisableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName)
1162 throws IOException {
1163 if (Bytes.equals(tableName.getName(), AccessControlLists.ACL_GLOBAL_NAME)) {
1164
1165
1166
1167
1168 throw new AccessDeniedException("Not allowed to disable "
1169 + AccessControlLists.ACL_TABLE_NAME + " table with AccessController installed");
1170 }
1171 requirePermission("disableTable", tableName, null, null, Action.ADMIN, Action.CREATE);
1172 }
1173
1174 @Override
1175 public void preMove(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo region,
1176 ServerName srcServer, ServerName destServer) throws IOException {
1177 requirePermission("move", region.getTable(), null, null, Action.ADMIN);
1178 }
1179
1180 @Override
1181 public void preAssign(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo)
1182 throws IOException {
1183 requirePermission("assign", regionInfo.getTable(), null, null, Action.ADMIN);
1184 }
1185
1186 @Override
1187 public void preUnassign(ObserverContext<MasterCoprocessorEnvironment> c, HRegionInfo regionInfo,
1188 boolean force) throws IOException {
1189 requirePermission("unassign", regionInfo.getTable(), null, null, Action.ADMIN);
1190 }
1191
1192 @Override
1193 public void preRegionOffline(ObserverContext<MasterCoprocessorEnvironment> c,
1194 HRegionInfo regionInfo) throws IOException {
1195 requirePermission("regionOffline", regionInfo.getTable(), null, null, Action.ADMIN);
1196 }
1197
1198 @Override
1199 public void preBalance(ObserverContext<MasterCoprocessorEnvironment> c)
1200 throws IOException {
1201 requirePermission("balance", Action.ADMIN);
1202 }
1203
1204 @Override
1205 public boolean preBalanceSwitch(ObserverContext<MasterCoprocessorEnvironment> c,
1206 boolean newValue) throws IOException {
1207 requirePermission("balanceSwitch", Action.ADMIN);
1208 return newValue;
1209 }
1210
1211 @Override
1212 public void preShutdown(ObserverContext<MasterCoprocessorEnvironment> c)
1213 throws IOException {
1214 requirePermission("shutdown", Action.ADMIN);
1215 }
1216
1217 @Override
1218 public void preStopMaster(ObserverContext<MasterCoprocessorEnvironment> c)
1219 throws IOException {
1220 requirePermission("stopMaster", Action.ADMIN);
1221 }
1222
1223 @Override
1224 public void postStartMaster(ObserverContext<MasterCoprocessorEnvironment> ctx)
1225 throws IOException {
1226 if (!MetaTableAccessor.tableExists(ctx.getEnvironment().getMasterServices()
1227 .getConnection(), AccessControlLists.ACL_TABLE_NAME)) {
1228
1229 AccessControlLists.createACLTable(ctx.getEnvironment().getMasterServices());
1230 } else {
1231 aclTabAvailable = true;
1232 }
1233 }
1234
1235 @Override
1236 public void preSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx,
1237 final SnapshotDescription snapshot, final HTableDescriptor hTableDescriptor)
1238 throws IOException {
1239 requirePermission("snapshot", hTableDescriptor.getTableName(), null, null,
1240 Permission.Action.ADMIN);
1241 }
1242
1243 @Override
1244 public void preListSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx,
1245 final SnapshotDescription snapshot) throws IOException {
1246 if (SnapshotDescriptionUtils.isSnapshotOwner(snapshot, getActiveUser())) {
1247
1248 } else {
1249 requirePermission("listSnapshot", Action.ADMIN);
1250 }
1251 }
1252
1253 @Override
1254 public void preCloneSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx,
1255 final SnapshotDescription snapshot, final HTableDescriptor hTableDescriptor)
1256 throws IOException {
1257 requirePermission("clone", Action.ADMIN);
1258 }
1259
1260 @Override
1261 public void preRestoreSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx,
1262 final SnapshotDescription snapshot, final HTableDescriptor hTableDescriptor)
1263 throws IOException {
1264 if (SnapshotDescriptionUtils.isSnapshotOwner(snapshot, getActiveUser())) {
1265 requirePermission("restoreSnapshot", hTableDescriptor.getTableName(), null, null,
1266 Permission.Action.ADMIN);
1267 } else {
1268 requirePermission("restore", Action.ADMIN);
1269 }
1270 }
1271
1272 @Override
1273 public void preDeleteSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx,
1274 final SnapshotDescription snapshot) throws IOException {
1275 if (SnapshotDescriptionUtils.isSnapshotOwner(snapshot, getActiveUser())) {
1276
1277
1278 } else {
1279 requirePermission("deleteSnapshot", Action.ADMIN);
1280 }
1281 }
1282
1283 @Override
1284 public void preCreateNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx,
1285 NamespaceDescriptor ns) throws IOException {
1286 requireGlobalPermission("createNamespace", Action.ADMIN, ns.getName());
1287 }
1288
1289 @Override
1290 public void preDeleteNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, String namespace)
1291 throws IOException {
1292 requireGlobalPermission("deleteNamespace", Action.ADMIN, namespace);
1293 }
1294
1295 @Override
1296 public void postDeleteNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx,
1297 final String namespace) throws IOException {
1298 final Configuration conf = ctx.getEnvironment().getConfiguration();
1299 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() {
1300 @Override
1301 public Void run() throws Exception {
1302 AccessControlLists.removeNamespacePermissions(conf, namespace);
1303 return null;
1304 }
1305 });
1306 this.authManager.getZKPermissionWatcher().deleteNamespaceACLNode(namespace);
1307 LOG.info(namespace + " entry deleted in "+AccessControlLists.ACL_TABLE_NAME+" table.");
1308 }
1309
1310 @Override
1311 public void preModifyNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx,
1312 NamespaceDescriptor ns) throws IOException {
1313
1314
1315 requireGlobalPermission("modifyNamespace", Action.ADMIN, ns.getName());
1316 }
1317
1318 @Override
1319 public void preGetNamespaceDescriptor(ObserverContext<MasterCoprocessorEnvironment> ctx, String namespace)
1320 throws IOException {
1321 requireNamespacePermission("getNamespaceDescriptor", namespace, Action.ADMIN);
1322 }
1323
1324 @Override
1325 public void postListNamespaceDescriptors(ObserverContext<MasterCoprocessorEnvironment> ctx,
1326 List<NamespaceDescriptor> descriptors) throws IOException {
1327
1328
1329 Iterator<NamespaceDescriptor> itr = descriptors.iterator();
1330 while (itr.hasNext()) {
1331 NamespaceDescriptor desc = itr.next();
1332 try {
1333 requireNamespacePermission("listNamespaces", desc.getName(), Action.ADMIN);
1334 } catch (AccessDeniedException e) {
1335 itr.remove();
1336 }
1337 }
1338 }
1339
1340 @Override
1341 public void preTableFlush(final ObserverContext<MasterCoprocessorEnvironment> ctx,
1342 final TableName tableName) throws IOException {
1343 requirePermission("flushTable", tableName, null, null, Action.ADMIN, Action.CREATE);
1344 }
1345
1346
1347
1348 @Override
1349 public void preOpen(ObserverContext<RegionCoprocessorEnvironment> e)
1350 throws IOException {
1351 RegionCoprocessorEnvironment env = e.getEnvironment();
1352 final Region region = env.getRegion();
1353 if (region == null) {
1354 LOG.error("NULL region from RegionCoprocessorEnvironment in preOpen()");
1355 } else {
1356 HRegionInfo regionInfo = region.getRegionInfo();
1357 if (regionInfo.getTable().isSystemTable()) {
1358 isSystemOrSuperUser(regionEnv.getConfiguration());
1359 } else {
1360 requirePermission("preOpen", Action.ADMIN);
1361 }
1362 }
1363 }
1364
1365 @Override
1366 public void postOpen(ObserverContext<RegionCoprocessorEnvironment> c) {
1367 RegionCoprocessorEnvironment env = c.getEnvironment();
1368 final Region region = env.getRegion();
1369 if (region == null) {
1370 LOG.error("NULL region from RegionCoprocessorEnvironment in postOpen()");
1371 return;
1372 }
1373 if (AccessControlLists.isAclRegion(region)) {
1374 aclRegion = true;
1375
1376 if (!region.isRecovering()) {
1377 try {
1378 initialize(env);
1379 } catch (IOException ex) {
1380
1381
1382 throw new RuntimeException("Failed to initialize permissions cache", ex);
1383 }
1384 }
1385 } else {
1386 initialized = true;
1387 }
1388 }
1389
1390 @Override
1391 public void postLogReplay(ObserverContext<RegionCoprocessorEnvironment> c) {
1392 if (aclRegion) {
1393 try {
1394 initialize(c.getEnvironment());
1395 } catch (IOException ex) {
1396
1397
1398 throw new RuntimeException("Failed to initialize permissions cache", ex);
1399 }
1400 }
1401 }
1402
1403 @Override
1404 public void preFlush(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException {
1405 requirePermission("flush", getTableName(e.getEnvironment()), null, null, Action.ADMIN,
1406 Action.CREATE);
1407 }
1408
1409 @Override
1410 public void preSplit(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException {
1411 requirePermission("split", getTableName(e.getEnvironment()), null, null, Action.ADMIN);
1412 }
1413
1414 @Override
1415 public void preSplit(ObserverContext<RegionCoprocessorEnvironment> e,
1416 byte[] splitRow) throws IOException {
1417 requirePermission("split", getTableName(e.getEnvironment()), null, null, Action.ADMIN);
1418 }
1419
1420 @Override
1421 public InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment> e,
1422 final Store store, final InternalScanner scanner, final ScanType scanType)
1423 throws IOException {
1424 requirePermission("compact", getTableName(e.getEnvironment()), null, null, Action.ADMIN,
1425 Action.CREATE);
1426 return scanner;
1427 }
1428
1429 @Override
1430 public void preGetClosestRowBefore(final ObserverContext<RegionCoprocessorEnvironment> c,
1431 final byte [] row, final byte [] family, final Result result)
1432 throws IOException {
1433 assert family != null;
1434 RegionCoprocessorEnvironment env = c.getEnvironment();
1435 Map<byte[],? extends Collection<byte[]>> families = makeFamilyMap(family, null);
1436 User user = getActiveUser();
1437 AuthResult authResult = permissionGranted(OpType.GET_CLOSEST_ROW_BEFORE, user, env, families,
1438 Action.READ);
1439 if (!authResult.isAllowed() && cellFeaturesEnabled && !compatibleEarlyTermination) {
1440 authResult.setAllowed(checkCoveringPermission(OpType.GET_CLOSEST_ROW_BEFORE, env, row,
1441 families, HConstants.LATEST_TIMESTAMP, Action.READ));
1442 authResult.setReason("Covering cell set");
1443 }
1444 logResult(authResult);
1445 if (authorizationEnabled && !authResult.isAllowed()) {
1446 throw new AccessDeniedException("Insufficient permissions " +
1447 authResult.toContextString());
1448 }
1449 }
1450
1451 private void internalPreRead(final ObserverContext<RegionCoprocessorEnvironment> c,
1452 final Query query, OpType opType) throws IOException {
1453 Filter filter = query.getFilter();
1454
1455 if (filter != null && filter instanceof AccessControlFilter) {
1456 return;
1457 }
1458 User user = getActiveUser();
1459 RegionCoprocessorEnvironment env = c.getEnvironment();
1460 Map<byte[],? extends Collection<byte[]>> families = null;
1461 switch (opType) {
1462 case GET:
1463 case EXISTS:
1464 families = ((Get)query).getFamilyMap();
1465 break;
1466 case SCAN:
1467 families = ((Scan)query).getFamilyMap();
1468 break;
1469 default:
1470 throw new RuntimeException("Unhandled operation " + opType);
1471 }
1472 AuthResult authResult = permissionGranted(opType, user, env, families, Action.READ);
1473 Region region = getRegion(env);
1474 TableName table = getTableName(region);
1475 Map<ByteRange, Integer> cfVsMaxVersions = Maps.newHashMap();
1476 for (HColumnDescriptor hcd : region.getTableDesc().getFamilies()) {
1477 cfVsMaxVersions.put(new SimpleMutableByteRange(hcd.getName()), hcd.getMaxVersions());
1478 }
1479 if (!authResult.isAllowed()) {
1480 if (!cellFeaturesEnabled || compatibleEarlyTermination) {
1481
1482
1483
1484
1485
1486
1487
1488
1489 if (hasFamilyQualifierPermission(user, Action.READ, env, families)) {
1490 authResult.setAllowed(true);
1491 authResult.setReason("Access allowed with filter");
1492
1493 if (authorizationEnabled) {
1494 Filter ourFilter = new AccessControlFilter(authManager, user, table,
1495 AccessControlFilter.Strategy.CHECK_TABLE_AND_CF_ONLY,
1496 cfVsMaxVersions);
1497
1498 if (filter != null) {
1499 ourFilter = new FilterList(FilterList.Operator.MUST_PASS_ALL,
1500 Lists.newArrayList(ourFilter, filter));
1501 }
1502 switch (opType) {
1503 case GET:
1504 case EXISTS:
1505 ((Get)query).setFilter(ourFilter);
1506 break;
1507 case SCAN:
1508 ((Scan)query).setFilter(ourFilter);
1509 break;
1510 default:
1511 throw new RuntimeException("Unhandled operation " + opType);
1512 }
1513 }
1514 }
1515 } else {
1516
1517
1518
1519
1520 authResult.setAllowed(true);
1521 authResult.setReason("Access allowed with filter");
1522
1523 if (authorizationEnabled) {
1524 Filter ourFilter = new AccessControlFilter(authManager, user, table,
1525 AccessControlFilter.Strategy.CHECK_CELL_DEFAULT, cfVsMaxVersions);
1526
1527 if (filter != null) {
1528 ourFilter = new FilterList(FilterList.Operator.MUST_PASS_ALL,
1529 Lists.newArrayList(ourFilter, filter));
1530 }
1531 switch (opType) {
1532 case GET:
1533 case EXISTS:
1534 ((Get)query).setFilter(ourFilter);
1535 break;
1536 case SCAN:
1537 ((Scan)query).setFilter(ourFilter);
1538 break;
1539 default:
1540 throw new RuntimeException("Unhandled operation " + opType);
1541 }
1542 }
1543 }
1544 }
1545
1546 logResult(authResult);
1547 if (authorizationEnabled && !authResult.isAllowed()) {
1548 throw new AccessDeniedException("Insufficient permissions for user '"
1549 + (user != null ? user.getShortName() : "null")
1550 + "' (table=" + table + ", action=READ)");
1551 }
1552 }
1553
1554 @Override
1555 public void preGetOp(final ObserverContext<RegionCoprocessorEnvironment> c,
1556 final Get get, final List<Cell> result) throws IOException {
1557 internalPreRead(c, get, OpType.GET);
1558 }
1559
1560 @Override
1561 public boolean preExists(final ObserverContext<RegionCoprocessorEnvironment> c,
1562 final Get get, final boolean exists) throws IOException {
1563 internalPreRead(c, get, OpType.EXISTS);
1564 return exists;
1565 }
1566
1567 @Override
1568 public void prePut(final ObserverContext<RegionCoprocessorEnvironment> c,
1569 final Put put, final WALEdit edit, final Durability durability)
1570 throws IOException {
1571 User user = getActiveUser();
1572 checkForReservedTagPresence(user, put);
1573
1574
1575
1576
1577
1578
1579
1580 RegionCoprocessorEnvironment env = c.getEnvironment();
1581 Map<byte[],? extends Collection<Cell>> families = put.getFamilyCellMap();
1582 AuthResult authResult = permissionGranted(OpType.PUT, user, env, families, Action.WRITE);
1583 logResult(authResult);
1584 if (!authResult.isAllowed()) {
1585 if (cellFeaturesEnabled && !compatibleEarlyTermination) {
1586 put.setAttribute(CHECK_COVERING_PERM, TRUE);
1587 } else if (authorizationEnabled) {
1588 throw new AccessDeniedException("Insufficient permissions " + authResult.toContextString());
1589 }
1590 }
1591
1592
1593 byte[] bytes = put.getAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL);
1594 if (bytes != null) {
1595 if (cellFeaturesEnabled) {
1596 addCellPermissions(bytes, put.getFamilyCellMap());
1597 } else {
1598 throw new DoNotRetryIOException("Cell ACLs cannot be persisted");
1599 }
1600 }
1601 }
1602
1603 @Override
1604 public void postPut(final ObserverContext<RegionCoprocessorEnvironment> c,
1605 final Put put, final WALEdit edit, final Durability durability) {
1606 if (aclRegion) {
1607 updateACL(c.getEnvironment(), put.getFamilyCellMap());
1608 }
1609 }
1610
1611 @Override
1612 public void preDelete(final ObserverContext<RegionCoprocessorEnvironment> c,
1613 final Delete delete, final WALEdit edit, final Durability durability)
1614 throws IOException {
1615
1616 if (delete.getAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL) != null) {
1617 throw new DoNotRetryIOException("ACL on delete has no effect: " + delete.toString());
1618 }
1619
1620
1621
1622
1623
1624 RegionCoprocessorEnvironment env = c.getEnvironment();
1625 Map<byte[],? extends Collection<Cell>> families = delete.getFamilyCellMap();
1626 User user = getActiveUser();
1627 AuthResult authResult = permissionGranted(OpType.DELETE, user, env, families, Action.WRITE);
1628 logResult(authResult);
1629 if (!authResult.isAllowed()) {
1630 if (cellFeaturesEnabled && !compatibleEarlyTermination) {
1631 delete.setAttribute(CHECK_COVERING_PERM, TRUE);
1632 } else if (authorizationEnabled) {
1633 throw new AccessDeniedException("Insufficient permissions " +
1634 authResult.toContextString());
1635 }
1636 }
1637 }
1638
1639 @Override
1640 public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c,
1641 MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
1642 if (cellFeaturesEnabled && !compatibleEarlyTermination) {
1643 TableName table = c.getEnvironment().getRegion().getRegionInfo().getTable();
1644 for (int i = 0; i < miniBatchOp.size(); i++) {
1645 Mutation m = miniBatchOp.getOperation(i);
1646 if (m.getAttribute(CHECK_COVERING_PERM) != null) {
1647
1648
1649 OpType opType;
1650 if (m instanceof Put) {
1651 checkForReservedTagPresence(getActiveUser(), m);
1652 opType = OpType.PUT;
1653 } else {
1654 opType = OpType.DELETE;
1655 }
1656 AuthResult authResult = null;
1657 if (checkCoveringPermission(opType, c.getEnvironment(), m.getRow(),
1658 m.getFamilyCellMap(), m.getTimeStamp(), Action.WRITE)) {
1659 authResult = AuthResult.allow(opType.toString(), "Covering cell set",
1660 getActiveUser(), Action.WRITE, table, m.getFamilyCellMap());
1661 } else {
1662 authResult = AuthResult.deny(opType.toString(), "Covering cell set",
1663 getActiveUser(), Action.WRITE, table, m.getFamilyCellMap());
1664 }
1665 logResult(authResult);
1666 if (authorizationEnabled && !authResult.isAllowed()) {
1667 throw new AccessDeniedException("Insufficient permissions "
1668 + authResult.toContextString());
1669 }
1670 }
1671 }
1672 }
1673 }
1674
1675 @Override
1676 public void postDelete(final ObserverContext<RegionCoprocessorEnvironment> c,
1677 final Delete delete, final WALEdit edit, final Durability durability)
1678 throws IOException {
1679 if (aclRegion) {
1680 updateACL(c.getEnvironment(), delete.getFamilyCellMap());
1681 }
1682 }
1683
1684 @Override
1685 public boolean preCheckAndPut(final ObserverContext<RegionCoprocessorEnvironment> c,
1686 final byte [] row, final byte [] family, final byte [] qualifier,
1687 final CompareFilter.CompareOp compareOp,
1688 final ByteArrayComparable comparator, final Put put,
1689 final boolean result) throws IOException {
1690 User user = getActiveUser();
1691 checkForReservedTagPresence(user, put);
1692
1693
1694 RegionCoprocessorEnvironment env = c.getEnvironment();
1695 Map<byte[],? extends Collection<byte[]>> families = makeFamilyMap(family, qualifier);
1696 AuthResult authResult = permissionGranted(OpType.CHECK_AND_PUT, user, env, families,
1697 Action.READ, Action.WRITE);
1698 logResult(authResult);
1699 if (!authResult.isAllowed()) {
1700 if (cellFeaturesEnabled && !compatibleEarlyTermination) {
1701 put.setAttribute(CHECK_COVERING_PERM, TRUE);
1702 } else if (authorizationEnabled) {
1703 throw new AccessDeniedException("Insufficient permissions " +
1704 authResult.toContextString());
1705 }
1706 }
1707
1708 byte[] bytes = put.getAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL);
1709 if (bytes != null) {
1710 if (cellFeaturesEnabled) {
1711 addCellPermissions(bytes, put.getFamilyCellMap());
1712 } else {
1713 throw new DoNotRetryIOException("Cell ACLs cannot be persisted");
1714 }
1715 }
1716 return result;
1717 }
1718
1719 @Override
1720 public boolean preCheckAndPutAfterRowLock(final ObserverContext<RegionCoprocessorEnvironment> c,
1721 final byte[] row, final byte[] family, final byte[] qualifier,
1722 final CompareFilter.CompareOp compareOp, final ByteArrayComparable comparator, final Put put,
1723 final boolean result) throws IOException {
1724 if (put.getAttribute(CHECK_COVERING_PERM) != null) {
1725
1726
1727 TableName table = c.getEnvironment().getRegion().getRegionInfo().getTable();
1728 Map<byte[], ? extends Collection<byte[]>> families = makeFamilyMap(family, qualifier);
1729 AuthResult authResult = null;
1730 if (checkCoveringPermission(OpType.CHECK_AND_PUT, c.getEnvironment(), row, families,
1731 HConstants.LATEST_TIMESTAMP, Action.READ)) {
1732 authResult = AuthResult.allow(OpType.CHECK_AND_PUT.toString(), "Covering cell set",
1733 getActiveUser(), Action.READ, table, families);
1734 } else {
1735 authResult = AuthResult.deny(OpType.CHECK_AND_PUT.toString(), "Covering cell set",
1736 getActiveUser(), Action.READ, table, families);
1737 }
1738 logResult(authResult);
1739 if (authorizationEnabled && !authResult.isAllowed()) {
1740 throw new AccessDeniedException("Insufficient permissions " + authResult.toContextString());
1741 }
1742 }
1743 return result;
1744 }
1745
1746 @Override
1747 public boolean preCheckAndDelete(final ObserverContext<RegionCoprocessorEnvironment> c,
1748 final byte [] row, final byte [] family, final byte [] qualifier,
1749 final CompareFilter.CompareOp compareOp,
1750 final ByteArrayComparable comparator, final Delete delete,
1751 final boolean result) throws IOException {
1752
1753 if (delete.getAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL) != null) {
1754 throw new DoNotRetryIOException("ACL on checkAndDelete has no effect: " +
1755 delete.toString());
1756 }
1757
1758
1759 RegionCoprocessorEnvironment env = c.getEnvironment();
1760 Map<byte[],? extends Collection<byte[]>> families = makeFamilyMap(family, qualifier);
1761 User user = getActiveUser();
1762 AuthResult authResult = permissionGranted(OpType.CHECK_AND_DELETE, user, env, families,
1763 Action.READ, Action.WRITE);
1764 logResult(authResult);
1765 if (!authResult.isAllowed()) {
1766 if (cellFeaturesEnabled && !compatibleEarlyTermination) {
1767 delete.setAttribute(CHECK_COVERING_PERM, TRUE);
1768 } else if (authorizationEnabled) {
1769 throw new AccessDeniedException("Insufficient permissions " +
1770 authResult.toContextString());
1771 }
1772 }
1773 return result;
1774 }
1775
1776 @Override
1777 public boolean preCheckAndDeleteAfterRowLock(
1778 final ObserverContext<RegionCoprocessorEnvironment> c, final byte[] row, final byte[] family,
1779 final byte[] qualifier, final CompareFilter.CompareOp compareOp,
1780 final ByteArrayComparable comparator, final Delete delete, final boolean result)
1781 throws IOException {
1782 if (delete.getAttribute(CHECK_COVERING_PERM) != null) {
1783
1784
1785 TableName table = c.getEnvironment().getRegion().getRegionInfo().getTable();
1786 Map<byte[], ? extends Collection<byte[]>> families = makeFamilyMap(family, qualifier);
1787 AuthResult authResult = null;
1788 if (checkCoveringPermission(OpType.CHECK_AND_DELETE, c.getEnvironment(), row, families,
1789 HConstants.LATEST_TIMESTAMP, Action.READ)) {
1790 authResult = AuthResult.allow(OpType.CHECK_AND_DELETE.toString(), "Covering cell set",
1791 getActiveUser(), Action.READ, table, families);
1792 } else {
1793 authResult = AuthResult.deny(OpType.CHECK_AND_DELETE.toString(), "Covering cell set",
1794 getActiveUser(), Action.READ, table, families);
1795 }
1796 logResult(authResult);
1797 if (authorizationEnabled && !authResult.isAllowed()) {
1798 throw new AccessDeniedException("Insufficient permissions " + authResult.toContextString());
1799 }
1800 }
1801 return result;
1802 }
1803
1804 @Override
1805 public long preIncrementColumnValue(final ObserverContext<RegionCoprocessorEnvironment> c,
1806 final byte [] row, final byte [] family, final byte [] qualifier,
1807 final long amount, final boolean writeToWAL)
1808 throws IOException {
1809
1810
1811 RegionCoprocessorEnvironment env = c.getEnvironment();
1812 Map<byte[],? extends Collection<byte[]>> families = makeFamilyMap(family, qualifier);
1813 User user = getActiveUser();
1814 AuthResult authResult = permissionGranted(OpType.INCREMENT_COLUMN_VALUE, user, env, families,
1815 Action.WRITE);
1816 if (!authResult.isAllowed() && cellFeaturesEnabled && !compatibleEarlyTermination) {
1817 authResult.setAllowed(checkCoveringPermission(OpType.INCREMENT_COLUMN_VALUE, env, row,
1818 families, HConstants.LATEST_TIMESTAMP, Action.WRITE));
1819 authResult.setReason("Covering cell set");
1820 }
1821 logResult(authResult);
1822 if (authorizationEnabled && !authResult.isAllowed()) {
1823 throw new AccessDeniedException("Insufficient permissions " + authResult.toContextString());
1824 }
1825 return -1;
1826 }
1827
1828 @Override
1829 public Result preAppend(ObserverContext<RegionCoprocessorEnvironment> c, Append append)
1830 throws IOException {
1831 User user = getActiveUser();
1832 checkForReservedTagPresence(user, append);
1833
1834
1835 RegionCoprocessorEnvironment env = c.getEnvironment();
1836 Map<byte[],? extends Collection<Cell>> families = append.getFamilyCellMap();
1837 AuthResult authResult = permissionGranted(OpType.APPEND, user, env, families, Action.WRITE);
1838 logResult(authResult);
1839 if (!authResult.isAllowed()) {
1840 if (cellFeaturesEnabled && !compatibleEarlyTermination) {
1841 append.setAttribute(CHECK_COVERING_PERM, TRUE);
1842 } else if (authorizationEnabled) {
1843 throw new AccessDeniedException("Insufficient permissions " +
1844 authResult.toContextString());
1845 }
1846 }
1847
1848 byte[] bytes = append.getAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL);
1849 if (bytes != null) {
1850 if (cellFeaturesEnabled) {
1851 addCellPermissions(bytes, append.getFamilyCellMap());
1852 } else {
1853 throw new DoNotRetryIOException("Cell ACLs cannot be persisted");
1854 }
1855 }
1856
1857 return null;
1858 }
1859
1860 @Override
1861 public Result preAppendAfterRowLock(final ObserverContext<RegionCoprocessorEnvironment> c,
1862 final Append append) throws IOException {
1863 if (append.getAttribute(CHECK_COVERING_PERM) != null) {
1864
1865
1866 TableName table = c.getEnvironment().getRegion().getRegionInfo().getTable();
1867 AuthResult authResult = null;
1868 if (checkCoveringPermission(OpType.APPEND, c.getEnvironment(), append.getRow(),
1869 append.getFamilyCellMap(), HConstants.LATEST_TIMESTAMP, Action.WRITE)) {
1870 authResult = AuthResult.allow(OpType.APPEND.toString(), "Covering cell set",
1871 getActiveUser(), Action.WRITE, table, append.getFamilyCellMap());
1872 } else {
1873 authResult = AuthResult.deny(OpType.APPEND.toString(), "Covering cell set",
1874 getActiveUser(), Action.WRITE, table, append.getFamilyCellMap());
1875 }
1876 logResult(authResult);
1877 if (authorizationEnabled && !authResult.isAllowed()) {
1878 throw new AccessDeniedException("Insufficient permissions " +
1879 authResult.toContextString());
1880 }
1881 }
1882 return null;
1883 }
1884
1885 @Override
1886 public Result preIncrement(final ObserverContext<RegionCoprocessorEnvironment> c,
1887 final Increment increment)
1888 throws IOException {
1889 User user = getActiveUser();
1890 checkForReservedTagPresence(user, increment);
1891
1892
1893
1894 RegionCoprocessorEnvironment env = c.getEnvironment();
1895 Map<byte[],? extends Collection<Cell>> families = increment.getFamilyCellMap();
1896 AuthResult authResult = permissionGranted(OpType.INCREMENT, user, env, families,
1897 Action.WRITE);
1898 logResult(authResult);
1899 if (!authResult.isAllowed()) {
1900 if (cellFeaturesEnabled && !compatibleEarlyTermination) {
1901 increment.setAttribute(CHECK_COVERING_PERM, TRUE);
1902 } else if (authorizationEnabled) {
1903 throw new AccessDeniedException("Insufficient permissions " +
1904 authResult.toContextString());
1905 }
1906 }
1907
1908 byte[] bytes = increment.getAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL);
1909 if (bytes != null) {
1910 if (cellFeaturesEnabled) {
1911 addCellPermissions(bytes, increment.getFamilyCellMap());
1912 } else {
1913 throw new DoNotRetryIOException("Cell ACLs cannot be persisted");
1914 }
1915 }
1916
1917 return null;
1918 }
1919
1920 @Override
1921 public Result preIncrementAfterRowLock(final ObserverContext<RegionCoprocessorEnvironment> c,
1922 final Increment increment) throws IOException {
1923 if (increment.getAttribute(CHECK_COVERING_PERM) != null) {
1924
1925
1926 TableName table = c.getEnvironment().getRegion().getRegionInfo().getTable();
1927 AuthResult authResult = null;
1928 if (checkCoveringPermission(OpType.INCREMENT, c.getEnvironment(), increment.getRow(),
1929 increment.getFamilyCellMap(), increment.getTimeRange().getMax(), Action.WRITE)) {
1930 authResult = AuthResult.allow(OpType.INCREMENT.toString(), "Covering cell set",
1931 getActiveUser(), Action.WRITE, table, increment.getFamilyCellMap());
1932 } else {
1933 authResult = AuthResult.deny(OpType.INCREMENT.toString(), "Covering cell set",
1934 getActiveUser(), Action.WRITE, table, increment.getFamilyCellMap());
1935 }
1936 logResult(authResult);
1937 if (authorizationEnabled && !authResult.isAllowed()) {
1938 throw new AccessDeniedException("Insufficient permissions " +
1939 authResult.toContextString());
1940 }
1941 }
1942 return null;
1943 }
1944
1945 @Override
1946 public Cell postMutationBeforeWAL(ObserverContext<RegionCoprocessorEnvironment> ctx,
1947 MutationType opType, Mutation mutation, Cell oldCell, Cell newCell) throws IOException {
1948
1949
1950 if (!cellFeaturesEnabled) {
1951 return newCell;
1952 }
1953
1954
1955 List<Tag> tags = Lists.newArrayList();
1956 ListMultimap<String,Permission> perms = ArrayListMultimap.create();
1957 if (oldCell != null) {
1958
1959 if (oldCell.getTagsLength() > 0) {
1960 Iterator<Tag> tagIterator = CellUtil.tagsIterator(oldCell.getTagsArray(),
1961 oldCell.getTagsOffset(), oldCell.getTagsLength());
1962 while (tagIterator.hasNext()) {
1963 Tag tag = tagIterator.next();
1964 if (tag.getType() != AccessControlLists.ACL_TAG_TYPE) {
1965
1966 if (LOG.isTraceEnabled()) {
1967 LOG.trace("Carrying forward tag from " + oldCell + ": type " + tag.getType() +
1968 " length " + tag.getTagLength());
1969 }
1970 tags.add(tag);
1971 } else {
1972
1973 ListMultimap<String,Permission> kvPerms = ProtobufUtil.toUsersAndPermissions(
1974 AccessControlProtos.UsersAndPermissions.newBuilder().mergeFrom(
1975 tag.getBuffer(), tag.getTagOffset(), tag.getTagLength()).build());
1976 perms.putAll(kvPerms);
1977 }
1978 }
1979 }
1980 }
1981
1982
1983 byte[] aclBytes = mutation.getACL();
1984 if (aclBytes != null) {
1985
1986 tags.add(new Tag(AccessControlLists.ACL_TAG_TYPE, aclBytes));
1987 } else {
1988
1989 if (perms != null) {
1990
1991
1992
1993 if (LOG.isTraceEnabled()) {
1994 LOG.trace("Carrying forward ACLs from " + oldCell + ": " + perms);
1995 }
1996 tags.add(new Tag(AccessControlLists.ACL_TAG_TYPE,
1997 ProtobufUtil.toUsersAndPermissions(perms).toByteArray()));
1998 }
1999 }
2000
2001
2002 if (tags.isEmpty()) {
2003 return newCell;
2004 }
2005
2006 Cell rewriteCell = new TagRewriteCell(newCell, Tag.fromList(tags));
2007 return rewriteCell;
2008 }
2009
2010 @Override
2011 public RegionScanner preScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
2012 final Scan scan, final RegionScanner s) throws IOException {
2013 internalPreRead(c, scan, OpType.SCAN);
2014 return s;
2015 }
2016
2017 @Override
2018 public RegionScanner postScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
2019 final Scan scan, final RegionScanner s) throws IOException {
2020 User user = getActiveUser();
2021 if (user != null && user.getShortName() != null) {
2022
2023 scannerOwners.put(s, user.getShortName());
2024 }
2025 return s;
2026 }
2027
2028 @Override
2029 public boolean preScannerNext(final ObserverContext<RegionCoprocessorEnvironment> c,
2030 final InternalScanner s, final List<Result> result,
2031 final int limit, final boolean hasNext) throws IOException {
2032 requireScannerOwner(s);
2033 return hasNext;
2034 }
2035
2036 @Override
2037 public void preScannerClose(final ObserverContext<RegionCoprocessorEnvironment> c,
2038 final InternalScanner s) throws IOException {
2039 requireScannerOwner(s);
2040 }
2041
2042 @Override
2043 public void postScannerClose(final ObserverContext<RegionCoprocessorEnvironment> c,
2044 final InternalScanner s) throws IOException {
2045
2046 scannerOwners.remove(s);
2047 }
2048
2049
2050
2051
2052
2053
2054 private void requireScannerOwner(InternalScanner s) throws AccessDeniedException {
2055 if (!RpcServer.isInRpcCallContext())
2056 return;
2057 String requestUserName = RpcServer.getRequestUserName();
2058 String owner = scannerOwners.get(s);
2059 if (authorizationEnabled && owner != null && !owner.equals(requestUserName)) {
2060 throw new AccessDeniedException("User '"+ requestUserName +"' is not the scanner owner!");
2061 }
2062 }
2063
2064
2065
2066
2067
2068
2069
2070 @Override
2071 public void preBulkLoadHFile(ObserverContext<RegionCoprocessorEnvironment> ctx,
2072 List<Pair<byte[], String>> familyPaths) throws IOException {
2073 for(Pair<byte[],String> el : familyPaths) {
2074 requirePermission("preBulkLoadHFile",
2075 ctx.getEnvironment().getRegion().getTableDesc().getTableName(),
2076 el.getFirst(),
2077 null,
2078 Action.CREATE);
2079 }
2080 }
2081
2082
2083
2084
2085
2086
2087
2088
2089 @Override
2090 public void prePrepareBulkLoad(ObserverContext<RegionCoprocessorEnvironment> ctx,
2091 PrepareBulkLoadRequest request) throws IOException {
2092 requireAccess("prePareBulkLoad",
2093 ctx.getEnvironment().getRegion().getTableDesc().getTableName(), Action.CREATE);
2094 }
2095
2096
2097
2098
2099
2100
2101
2102
2103 @Override
2104 public void preCleanupBulkLoad(ObserverContext<RegionCoprocessorEnvironment> ctx,
2105 CleanupBulkLoadRequest request) throws IOException {
2106 requireAccess("preCleanupBulkLoad",
2107 ctx.getEnvironment().getRegion().getTableDesc().getTableName(), Action.CREATE);
2108 }
2109
2110
2111
2112 @Override
2113 public Message preEndpointInvocation(ObserverContext<RegionCoprocessorEnvironment> ctx,
2114 Service service, String methodName, Message request) throws IOException {
2115
2116
2117 if (shouldCheckExecPermission && !(service instanceof AccessControlService)) {
2118 requirePermission("invoke(" + service.getDescriptorForType().getName() + "." +
2119 methodName + ")",
2120 getTableName(ctx.getEnvironment()), null, null,
2121 Action.EXEC);
2122 }
2123 return request;
2124 }
2125
2126 @Override
2127 public void postEndpointInvocation(ObserverContext<RegionCoprocessorEnvironment> ctx,
2128 Service service, String methodName, Message request, Message.Builder responseBuilder)
2129 throws IOException { }
2130
2131
2132
2133 @Override
2134 public void grant(RpcController controller,
2135 AccessControlProtos.GrantRequest request,
2136 RpcCallback<AccessControlProtos.GrantResponse> done) {
2137 final UserPermission perm = ProtobufUtil.toUserPermission(request.getUserPermission());
2138 AccessControlProtos.GrantResponse response = null;
2139 try {
2140
2141 if (aclRegion) {
2142 if (!initialized) {
2143 throw new CoprocessorException("AccessController not yet initialized");
2144 }
2145 if (LOG.isDebugEnabled()) {
2146 LOG.debug("Received request to grant access permission " + perm.toString());
2147 }
2148
2149 switch(request.getUserPermission().getPermission().getType()) {
2150 case Global :
2151 case Table :
2152 requirePermission("grant", perm.getTableName(), perm.getFamily(),
2153 perm.getQualifier(), Action.ADMIN);
2154 break;
2155 case Namespace :
2156 requireGlobalPermission("grant", Action.ADMIN, perm.getNamespace());
2157 break;
2158 }
2159
2160 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() {
2161 @Override
2162 public Void run() throws Exception {
2163 AccessControlLists.addUserPermission(regionEnv.getConfiguration(), perm);
2164 return null;
2165 }
2166 });
2167
2168 if (AUDITLOG.isTraceEnabled()) {
2169
2170 AUDITLOG.trace("Granted permission " + perm.toString());
2171 }
2172 } else {
2173 throw new CoprocessorException(AccessController.class, "This method "
2174 + "can only execute at " + AccessControlLists.ACL_TABLE_NAME + " table.");
2175 }
2176 response = AccessControlProtos.GrantResponse.getDefaultInstance();
2177 } catch (IOException ioe) {
2178
2179 ResponseConverter.setControllerException(controller, ioe);
2180 }
2181 done.run(response);
2182 }
2183
2184 @Override
2185 public void revoke(RpcController controller,
2186 AccessControlProtos.RevokeRequest request,
2187 RpcCallback<AccessControlProtos.RevokeResponse> done) {
2188 final UserPermission perm = ProtobufUtil.toUserPermission(request.getUserPermission());
2189 AccessControlProtos.RevokeResponse response = null;
2190 try {
2191
2192 if (aclRegion) {
2193 if (!initialized) {
2194 throw new CoprocessorException("AccessController not yet initialized");
2195 }
2196 if (LOG.isDebugEnabled()) {
2197 LOG.debug("Received request to revoke access permission " + perm.toString());
2198 }
2199
2200 switch(request.getUserPermission().getPermission().getType()) {
2201 case Global :
2202 case Table :
2203 requirePermission("revoke", perm.getTableName(), perm.getFamily(),
2204 perm.getQualifier(), Action.ADMIN);
2205 break;
2206 case Namespace :
2207 requireGlobalPermission("revoke", Action.ADMIN, perm.getNamespace());
2208 break;
2209 }
2210
2211 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() {
2212 @Override
2213 public Void run() throws Exception {
2214 AccessControlLists.removeUserPermission(regionEnv.getConfiguration(), perm);
2215 return null;
2216 }
2217 });
2218
2219 if (AUDITLOG.isTraceEnabled()) {
2220
2221 AUDITLOG.trace("Revoked permission " + perm.toString());
2222 }
2223 } else {
2224 throw new CoprocessorException(AccessController.class, "This method "
2225 + "can only execute at " + AccessControlLists.ACL_TABLE_NAME + " table.");
2226 }
2227 response = AccessControlProtos.RevokeResponse.getDefaultInstance();
2228 } catch (IOException ioe) {
2229
2230 ResponseConverter.setControllerException(controller, ioe);
2231 }
2232 done.run(response);
2233 }
2234
2235 @Override
2236 public void getUserPermissions(RpcController controller,
2237 AccessControlProtos.GetUserPermissionsRequest request,
2238 RpcCallback<AccessControlProtos.GetUserPermissionsResponse> done) {
2239 AccessControlProtos.GetUserPermissionsResponse response = null;
2240 try {
2241
2242 if (aclRegion) {
2243 if (!initialized) {
2244 throw new CoprocessorException("AccessController not yet initialized");
2245 }
2246 List<UserPermission> perms = null;
2247 if (request.getType() == AccessControlProtos.Permission.Type.Table) {
2248 final TableName table = request.hasTableName() ?
2249 ProtobufUtil.toTableName(request.getTableName()) : null;
2250 requirePermission("userPermissions", table, null, null, Action.ADMIN);
2251 perms = User.runAsLoginUser(new PrivilegedExceptionAction<List<UserPermission>>() {
2252 @Override
2253 public List<UserPermission> run() throws Exception {
2254 return AccessControlLists.getUserTablePermissions(regionEnv.getConfiguration(), table);
2255 }
2256 });
2257 } else if (request.getType() == AccessControlProtos.Permission.Type.Namespace) {
2258 final String namespace = request.getNamespaceName().toStringUtf8();
2259 requireNamespacePermission("userPermissions", namespace, Action.ADMIN);
2260 perms = User.runAsLoginUser(new PrivilegedExceptionAction<List<UserPermission>>() {
2261 @Override
2262 public List<UserPermission> run() throws Exception {
2263 return AccessControlLists.getUserNamespacePermissions(regionEnv.getConfiguration(),
2264 namespace);
2265 }
2266 });
2267 } else {
2268 requirePermission("userPermissions", Action.ADMIN);
2269 perms = User.runAsLoginUser(new PrivilegedExceptionAction<List<UserPermission>>() {
2270 @Override
2271 public List<UserPermission> run() throws Exception {
2272 return AccessControlLists.getUserPermissions(regionEnv.getConfiguration(), null);
2273 }
2274 });
2275 }
2276 response = ResponseConverter.buildGetUserPermissionsResponse(perms);
2277 } else {
2278 throw new CoprocessorException(AccessController.class, "This method "
2279 + "can only execute at " + AccessControlLists.ACL_TABLE_NAME + " table.");
2280 }
2281 } catch (IOException ioe) {
2282
2283 ResponseConverter.setControllerException(controller, ioe);
2284 }
2285 done.run(response);
2286 }
2287
2288 @Override
2289 public void checkPermissions(RpcController controller,
2290 AccessControlProtos.CheckPermissionsRequest request,
2291 RpcCallback<AccessControlProtos.CheckPermissionsResponse> done) {
2292 Permission[] permissions = new Permission[request.getPermissionCount()];
2293 for (int i=0; i < request.getPermissionCount(); i++) {
2294 permissions[i] = ProtobufUtil.toPermission(request.getPermission(i));
2295 }
2296 AccessControlProtos.CheckPermissionsResponse response = null;
2297 try {
2298 User user = getActiveUser();
2299 TableName tableName = regionEnv.getRegion().getTableDesc().getTableName();
2300 for (Permission permission : permissions) {
2301 if (permission instanceof TablePermission) {
2302
2303
2304 TablePermission tperm = (TablePermission) permission;
2305 for (Action action : permission.getActions()) {
2306 if (!tperm.getTableName().equals(tableName)) {
2307 throw new CoprocessorException(AccessController.class, String.format("This method "
2308 + "can only execute at the table specified in TablePermission. " +
2309 "Table of the region:%s , requested table:%s", tableName,
2310 tperm.getTableName()));
2311 }
2312
2313 Map<byte[], Set<byte[]>> familyMap =
2314 new TreeMap<byte[], Set<byte[]>>(Bytes.BYTES_COMPARATOR);
2315 if (tperm.getFamily() != null) {
2316 if (tperm.getQualifier() != null) {
2317 Set<byte[]> qualifiers = Sets.newTreeSet(Bytes.BYTES_COMPARATOR);
2318 qualifiers.add(tperm.getQualifier());
2319 familyMap.put(tperm.getFamily(), qualifiers);
2320 } else {
2321 familyMap.put(tperm.getFamily(), null);
2322 }
2323 }
2324
2325 AuthResult result = permissionGranted("checkPermissions", user, action, regionEnv,
2326 familyMap);
2327 logResult(result);
2328 if (!result.isAllowed()) {
2329
2330
2331 throw new AccessDeniedException("Insufficient permissions (table=" + tableName +
2332 (familyMap.size() > 0 ? ", family: " + result.toFamilyString() : "") +
2333 ", action=" + action.toString() + ")");
2334 }
2335 }
2336
2337 } else {
2338
2339
2340 for (Action action : permission.getActions()) {
2341 AuthResult result;
2342 if (authManager.authorize(user, action)) {
2343 result = AuthResult.allow("checkPermissions", "Global action allowed", user,
2344 action, null, null);
2345 } else {
2346 result = AuthResult.deny("checkPermissions", "Global action denied", user, action,
2347 null, null);
2348 }
2349 logResult(result);
2350 if (!result.isAllowed()) {
2351
2352
2353 throw new AccessDeniedException("Insufficient permissions (action=" +
2354 action.toString() + ")");
2355 }
2356 }
2357 }
2358 }
2359 response = AccessControlProtos.CheckPermissionsResponse.getDefaultInstance();
2360 } catch (IOException ioe) {
2361 ResponseConverter.setControllerException(controller, ioe);
2362 }
2363 done.run(response);
2364 }
2365
2366 @Override
2367 public Service getService() {
2368 return AccessControlProtos.AccessControlService.newReflectiveService(this);
2369 }
2370
2371 private Region getRegion(RegionCoprocessorEnvironment e) {
2372 return e.getRegion();
2373 }
2374
2375 private TableName getTableName(RegionCoprocessorEnvironment e) {
2376 Region region = e.getRegion();
2377 if (region != null) {
2378 return getTableName(region);
2379 }
2380 return null;
2381 }
2382
2383 private TableName getTableName(Region region) {
2384 HRegionInfo regionInfo = region.getRegionInfo();
2385 if (regionInfo != null) {
2386 return regionInfo.getTable();
2387 }
2388 return null;
2389 }
2390
2391 @Override
2392 public void preClose(ObserverContext<RegionCoprocessorEnvironment> e, boolean abortRequested)
2393 throws IOException {
2394 requirePermission("preClose", Action.ADMIN);
2395 }
2396
2397 private void isSystemOrSuperUser(Configuration conf) throws IOException {
2398
2399 if (!authorizationEnabled) {
2400 return;
2401 }
2402 User user = userProvider.getCurrent();
2403 if (user == null) {
2404 throw new IOException("Unable to obtain the current user, " +
2405 "authorization checks for internal operations will not work correctly!");
2406 }
2407 User activeUser = getActiveUser();
2408 if (!(superusers.contains(activeUser.getShortName()))) {
2409 throw new AccessDeniedException("User '" + (user != null ? user.getShortName() : "null") +
2410 "is not system or super user.");
2411 }
2412 }
2413
2414 @Override
2415 public void preStopRegionServer(
2416 ObserverContext<RegionServerCoprocessorEnvironment> env)
2417 throws IOException {
2418 requirePermission("preStopRegionServer", Action.ADMIN);
2419 }
2420
2421 private Map<byte[], ? extends Collection<byte[]>> makeFamilyMap(byte[] family,
2422 byte[] qualifier) {
2423 if (family == null) {
2424 return null;
2425 }
2426
2427 Map<byte[], Collection<byte[]>> familyMap = new TreeMap<byte[], Collection<byte[]>>(Bytes.BYTES_COMPARATOR);
2428 familyMap.put(family, qualifier != null ? ImmutableSet.of(qualifier) : null);
2429 return familyMap;
2430 }
2431
2432 @Override
2433 public void preGetTableDescriptors(ObserverContext<MasterCoprocessorEnvironment> ctx,
2434 List<TableName> tableNamesList, List<HTableDescriptor> descriptors,
2435 String regex) throws IOException {
2436
2437
2438 if (regex == null && tableNamesList != null && !tableNamesList.isEmpty()) {
2439
2440
2441 MasterServices masterServices = ctx.getEnvironment().getMasterServices();
2442 for (TableName tableName: tableNamesList) {
2443
2444 if (masterServices.getTableDescriptors().get(tableName) == null) {
2445 continue;
2446 }
2447 requirePermission("getTableDescriptors", tableName, null, null,
2448 Action.ADMIN, Action.CREATE);
2449 }
2450 }
2451 }
2452
2453 @Override
2454 public void postGetTableDescriptors(ObserverContext<MasterCoprocessorEnvironment> ctx,
2455 List<TableName> tableNamesList, List<HTableDescriptor> descriptors,
2456 String regex) throws IOException {
2457
2458 if (regex == null && tableNamesList != null && !tableNamesList.isEmpty()) {
2459 return;
2460 }
2461
2462
2463
2464 Iterator<HTableDescriptor> itr = descriptors.iterator();
2465 while (itr.hasNext()) {
2466 HTableDescriptor htd = itr.next();
2467 try {
2468 requirePermission("getTableDescriptors", htd.getTableName(), null, null,
2469 Action.ADMIN, Action.CREATE);
2470 } catch (AccessDeniedException e) {
2471 itr.remove();
2472 }
2473 }
2474 }
2475
2476 @Override
2477 public void postGetTableNames(ObserverContext<MasterCoprocessorEnvironment> ctx,
2478 List<HTableDescriptor> descriptors, String regex) throws IOException {
2479
2480 Iterator<HTableDescriptor> itr = descriptors.iterator();
2481 while (itr.hasNext()) {
2482 HTableDescriptor htd = itr.next();
2483 try {
2484 requireAccess("getTableNames", htd.getTableName(), Action.values());
2485 } catch (AccessDeniedException e) {
2486 itr.remove();
2487 }
2488 }
2489 }
2490
2491 @Override
2492 public void preMerge(ObserverContext<RegionServerCoprocessorEnvironment> ctx, Region regionA,
2493 Region regionB) throws IOException {
2494 requirePermission("mergeRegions", regionA.getTableDesc().getTableName(), null, null,
2495 Action.ADMIN);
2496 }
2497
2498 @Override
2499 public void postMerge(ObserverContext<RegionServerCoprocessorEnvironment> c, Region regionA,
2500 Region regionB, Region mergedRegion) throws IOException { }
2501
2502 @Override
2503 public void preMergeCommit(ObserverContext<RegionServerCoprocessorEnvironment> ctx,
2504 Region regionA, Region regionB, List<Mutation> metaEntries) throws IOException { }
2505
2506 @Override
2507 public void postMergeCommit(ObserverContext<RegionServerCoprocessorEnvironment> ctx,
2508 Region regionA, Region regionB, Region mergedRegion) throws IOException { }
2509
2510 @Override
2511 public void preRollBackMerge(ObserverContext<RegionServerCoprocessorEnvironment> ctx,
2512 Region regionA, Region regionB) throws IOException { }
2513
2514 @Override
2515 public void postRollBackMerge(ObserverContext<RegionServerCoprocessorEnvironment> ctx,
2516 Region regionA, Region regionB) throws IOException { }
2517
2518 @Override
2519 public void preRollWALWriterRequest(ObserverContext<RegionServerCoprocessorEnvironment> ctx)
2520 throws IOException {
2521 requirePermission("preRollLogWriterRequest", Permission.Action.ADMIN);
2522 }
2523
2524 @Override
2525 public void postRollWALWriterRequest(ObserverContext<RegionServerCoprocessorEnvironment> ctx)
2526 throws IOException { }
2527
2528 @Override
2529 public ReplicationEndpoint postCreateReplicationEndPoint(
2530 ObserverContext<RegionServerCoprocessorEnvironment> ctx, ReplicationEndpoint endpoint) {
2531 return endpoint;
2532 }
2533
2534 @Override
2535 public void preReplicateLogEntries(ObserverContext<RegionServerCoprocessorEnvironment> ctx,
2536 List<WALEntry> entries, CellScanner cells) throws IOException {
2537 requirePermission("replicateLogEntries", Action.WRITE);
2538 }
2539
2540 @Override
2541 public void postReplicateLogEntries(ObserverContext<RegionServerCoprocessorEnvironment> ctx,
2542 List<WALEntry> entries, CellScanner cells) throws IOException {
2543 }
2544
2545 @Override
2546 public void preSetUserQuota(final ObserverContext<MasterCoprocessorEnvironment> ctx,
2547 final String userName, final Quotas quotas) throws IOException {
2548 requirePermission("setUserQuota", Action.ADMIN);
2549 }
2550
2551 @Override
2552 public void preSetUserQuota(final ObserverContext<MasterCoprocessorEnvironment> ctx,
2553 final String userName, final TableName tableName, final Quotas quotas) throws IOException {
2554 requirePermission("setUserTableQuota", tableName, null, null, Action.ADMIN);
2555 }
2556
2557 @Override
2558 public void preSetUserQuota(final ObserverContext<MasterCoprocessorEnvironment> ctx,
2559 final String userName, final String namespace, final Quotas quotas) throws IOException {
2560 requirePermission("setUserNamespaceQuota", Action.ADMIN);
2561 }
2562
2563 @Override
2564 public void preSetTableQuota(final ObserverContext<MasterCoprocessorEnvironment> ctx,
2565 final TableName tableName, final Quotas quotas) throws IOException {
2566 requirePermission("setTableQuota", tableName, null, null, Action.ADMIN);
2567 }
2568
2569 @Override
2570 public void preSetNamespaceQuota(final ObserverContext<MasterCoprocessorEnvironment> ctx,
2571 final String namespace, final Quotas quotas) throws IOException {
2572 requirePermission("setNamespaceQuota", Action.ADMIN);
2573 }
2574 }