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 java.io.ByteArrayInputStream;
22 import java.io.DataInput;
23 import java.io.DataInputStream;
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Set;
31 import java.util.TreeMap;
32 import java.util.TreeSet;
33
34 import org.apache.commons.logging.Log;
35 import org.apache.commons.logging.LogFactory;
36 import org.apache.hadoop.conf.Configuration;
37 import org.apache.hadoop.hbase.Cell;
38 import org.apache.hadoop.hbase.CellUtil;
39 import org.apache.hadoop.hbase.HColumnDescriptor;
40 import org.apache.hadoop.hbase.HConstants;
41 import org.apache.hadoop.hbase.HTableDescriptor;
42 import org.apache.hadoop.hbase.NamespaceDescriptor;
43 import org.apache.hadoop.hbase.TableName;
44 import org.apache.hadoop.hbase.Tag;
45 import org.apache.hadoop.hbase.TagType;
46 import org.apache.hadoop.hbase.classification.InterfaceAudience;
47 import org.apache.hadoop.hbase.client.Connection;
48 import org.apache.hadoop.hbase.client.ConnectionFactory;
49 import org.apache.hadoop.hbase.client.Delete;
50 import org.apache.hadoop.hbase.client.Get;
51 import org.apache.hadoop.hbase.client.Put;
52 import org.apache.hadoop.hbase.client.Result;
53 import org.apache.hadoop.hbase.client.ResultScanner;
54 import org.apache.hadoop.hbase.client.Scan;
55 import org.apache.hadoop.hbase.client.Table;
56 import org.apache.hadoop.hbase.exceptions.DeserializationException;
57 import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
58 import org.apache.hadoop.hbase.filter.QualifierFilter;
59 import org.apache.hadoop.hbase.filter.RegexStringComparator;
60 import org.apache.hadoop.hbase.master.MasterServices;
61 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
62 import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos;
63 import org.apache.hadoop.hbase.regionserver.BloomType;
64 import org.apache.hadoop.hbase.regionserver.InternalScanner;
65 import org.apache.hadoop.hbase.regionserver.Region;
66 import org.apache.hadoop.hbase.security.User;
67 import org.apache.hadoop.hbase.util.Bytes;
68 import org.apache.hadoop.hbase.util.Pair;
69 import org.apache.hadoop.io.Text;
70
71 import com.google.common.collect.ArrayListMultimap;
72 import com.google.common.collect.ListMultimap;
73 import com.google.common.collect.Lists;
74 import com.google.protobuf.InvalidProtocolBufferException;
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99 @InterfaceAudience.Private
100 public class AccessControlLists {
101
102 public static final TableName ACL_TABLE_NAME =
103 TableName.valueOf(NamespaceDescriptor.SYSTEM_NAMESPACE_NAME_STR, "acl");
104 public static final byte[] ACL_GLOBAL_NAME = ACL_TABLE_NAME.getName();
105
106 public static final String ACL_LIST_FAMILY_STR = "l";
107 public static final byte[] ACL_LIST_FAMILY = Bytes.toBytes(ACL_LIST_FAMILY_STR);
108
109 public static final byte ACL_TAG_TYPE = TagType.ACL_TAG_TYPE;
110
111 public static final char NAMESPACE_PREFIX = '@';
112
113
114
115
116 public static final char ACL_KEY_DELIMITER = ',';
117
118 public static final String GROUP_PREFIX = "@";
119
120 public static final String SUPERUSER_CONF_KEY = "hbase.superuser";
121
122 private static Log LOG = LogFactory.getLog(AccessControlLists.class);
123
124
125
126
127
128
129 static void createACLTable(MasterServices master) throws IOException {
130 master.createTable(new HTableDescriptor(ACL_TABLE_NAME)
131 .addFamily(new HColumnDescriptor(ACL_LIST_FAMILY)
132 .setMaxVersions(1)
133 .setInMemory(true)
134 .setBlockCacheEnabled(true)
135 .setBlocksize(8 * 1024)
136 .setBloomFilterType(BloomType.NONE)
137 .setScope(HConstants.REPLICATION_SCOPE_LOCAL)
138
139
140 .setCacheDataInL1(true)),
141 null);
142 }
143
144
145
146
147
148
149
150 static void addUserPermission(Configuration conf, UserPermission userPerm)
151 throws IOException {
152 Permission.Action[] actions = userPerm.getActions();
153 byte[] rowKey = userPermissionRowKey(userPerm);
154 Put p = new Put(rowKey);
155 byte[] key = userPermissionKey(userPerm);
156
157 if ((actions == null) || (actions.length == 0)) {
158 String msg = "No actions associated with user '" + Bytes.toString(userPerm.getUser()) + "'";
159 LOG.warn(msg);
160 throw new IOException(msg);
161 }
162
163 byte[] value = new byte[actions.length];
164 for (int i = 0; i < actions.length; i++) {
165 value[i] = actions[i].code();
166 }
167 p.addImmutable(ACL_LIST_FAMILY, key, value);
168 if (LOG.isDebugEnabled()) {
169 LOG.debug("Writing permission with rowKey "+
170 Bytes.toString(rowKey)+" "+
171 Bytes.toString(key)+": "+Bytes.toStringBinary(value)
172 );
173 }
174
175 try (Connection connection = ConnectionFactory.createConnection(conf)) {
176 try (Table table = connection.getTable(ACL_TABLE_NAME)) {
177 table.put(p);
178 }
179 }
180 }
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195 static void removeUserPermission(Configuration conf, UserPermission userPerm)
196 throws IOException {
197 Delete d = new Delete(userPermissionRowKey(userPerm));
198 byte[] key = userPermissionKey(userPerm);
199
200 if (LOG.isDebugEnabled()) {
201 LOG.debug("Removing permission "+ userPerm.toString());
202 }
203 d.addColumns(ACL_LIST_FAMILY, key);
204
205 try (Connection connection = ConnectionFactory.createConnection(conf)) {
206 try (Table table = connection.getTable(ACL_TABLE_NAME)) {
207 table.delete(d);
208 }
209 }
210 }
211
212
213
214
215 static void removeTablePermissions(Configuration conf, TableName tableName)
216 throws IOException{
217 Delete d = new Delete(tableName.getName());
218
219 if (LOG.isDebugEnabled()) {
220 LOG.debug("Removing permissions of removed table "+ tableName);
221 }
222
223 try (Connection connection = ConnectionFactory.createConnection(conf)) {
224 try (Table table = connection.getTable(ACL_TABLE_NAME)) {
225 table.delete(d);
226 }
227 }
228 }
229
230
231
232
233 static void removeNamespacePermissions(Configuration conf, String namespace)
234 throws IOException{
235 Delete d = new Delete(Bytes.toBytes(toNamespaceEntry(namespace)));
236
237 if (LOG.isDebugEnabled()) {
238 LOG.debug("Removing permissions of removed namespace "+ namespace);
239 }
240
241 try (Connection connection = ConnectionFactory.createConnection(conf)) {
242 try (Table table = connection.getTable(ACL_TABLE_NAME)) {
243 table.delete(d);
244 }
245 }
246 }
247
248
249
250
251 static void removeTablePermissions(Configuration conf, TableName tableName, byte[] column)
252 throws IOException{
253
254 if (LOG.isDebugEnabled()) {
255 LOG.debug("Removing permissions of removed column " + Bytes.toString(column) +
256 " from table "+ tableName);
257 }
258
259 try (Connection connection = ConnectionFactory.createConnection(conf)) {
260 try (Table table = connection.getTable(ACL_TABLE_NAME)) {
261 Scan scan = new Scan();
262 scan.addFamily(ACL_LIST_FAMILY);
263
264 String columnName = Bytes.toString(column);
265 scan.setFilter(new QualifierFilter(CompareOp.EQUAL, new RegexStringComparator(
266 String.format("(%s%s%s)|(%s%s)$",
267 ACL_KEY_DELIMITER, columnName, ACL_KEY_DELIMITER,
268 ACL_KEY_DELIMITER, columnName))));
269
270 Set<byte[]> qualifierSet = new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR);
271 ResultScanner scanner = table.getScanner(scan);
272 try {
273 for (Result res : scanner) {
274 for (byte[] q : res.getFamilyMap(ACL_LIST_FAMILY).navigableKeySet()) {
275 qualifierSet.add(q);
276 }
277 }
278 } finally {
279 scanner.close();
280 }
281
282 if (qualifierSet.size() > 0) {
283 Delete d = new Delete(tableName.getName());
284 for (byte[] qualifier : qualifierSet) {
285 d.addColumns(ACL_LIST_FAMILY, qualifier);
286 }
287 table.delete(d);
288 }
289 }
290 }
291 }
292
293 static byte[] userPermissionRowKey(UserPermission userPerm) {
294 byte[] row;
295 if(userPerm.hasNamespace()) {
296 row = Bytes.toBytes(toNamespaceEntry(userPerm.getNamespace()));
297 } else if(userPerm.isGlobal()) {
298 row = ACL_GLOBAL_NAME;
299 } else {
300 row = userPerm.getTableName().getName();
301 }
302 return row;
303 }
304
305
306
307
308
309
310
311 static byte[] userPermissionKey(UserPermission userPerm) {
312 byte[] qualifier = userPerm.getQualifier();
313 byte[] family = userPerm.getFamily();
314 byte[] key = userPerm.getUser();
315
316 if (family != null && family.length > 0) {
317 key = Bytes.add(key, Bytes.add(new byte[]{ACL_KEY_DELIMITER}, family));
318 if (qualifier != null && qualifier.length > 0) {
319 key = Bytes.add(key, Bytes.add(new byte[]{ACL_KEY_DELIMITER}, qualifier));
320 }
321 }
322
323 return key;
324 }
325
326
327
328
329
330 static boolean isAclRegion(Region region) {
331 return ACL_TABLE_NAME.equals(region.getTableDesc().getTableName());
332 }
333
334
335
336
337 static boolean isAclTable(HTableDescriptor desc) {
338 return ACL_TABLE_NAME.equals(desc.getTableName());
339 }
340
341
342
343
344
345
346
347
348
349 static Map<byte[], ListMultimap<String,TablePermission>> loadAll(Region aclRegion)
350 throws IOException {
351
352 if (!isAclRegion(aclRegion)) {
353 throw new IOException("Can only load permissions from "+ACL_TABLE_NAME);
354 }
355
356 Map<byte[], ListMultimap<String, TablePermission>> allPerms =
357 new TreeMap<byte[], ListMultimap<String, TablePermission>>(Bytes.BYTES_RAWCOMPARATOR);
358
359
360
361 Scan scan = new Scan();
362 scan.addFamily(ACL_LIST_FAMILY);
363
364 InternalScanner iScanner = null;
365 try {
366 iScanner = aclRegion.getScanner(scan);
367
368 while (true) {
369 List<Cell> row = new ArrayList<Cell>();
370
371 boolean hasNext = iScanner.next(row);
372 ListMultimap<String,TablePermission> perms = ArrayListMultimap.create();
373 byte[] entry = null;
374 for (Cell kv : row) {
375 if (entry == null) {
376 entry = CellUtil.cloneRow(kv);
377 }
378 Pair<String,TablePermission> permissionsOfUserOnTable =
379 parsePermissionRecord(entry, kv);
380 if (permissionsOfUserOnTable != null) {
381 String username = permissionsOfUserOnTable.getFirst();
382 TablePermission permissions = permissionsOfUserOnTable.getSecond();
383 perms.put(username, permissions);
384 }
385 }
386 if (entry != null) {
387 allPerms.put(entry, perms);
388 }
389 if (!hasNext) {
390 break;
391 }
392 }
393 } finally {
394 if (iScanner != null) {
395 iScanner.close();
396 }
397 }
398
399 return allPerms;
400 }
401
402
403
404
405
406 static Map<byte[], ListMultimap<String,TablePermission>> loadAll(
407 Configuration conf) throws IOException {
408 Map<byte[], ListMultimap<String,TablePermission>> allPerms =
409 new TreeMap<byte[], ListMultimap<String,TablePermission>>(Bytes.BYTES_RAWCOMPARATOR);
410
411
412
413 Scan scan = new Scan();
414 scan.addFamily(ACL_LIST_FAMILY);
415
416 ResultScanner scanner = null;
417
418 try (Connection connection = ConnectionFactory.createConnection(conf)) {
419 try (Table table = connection.getTable(ACL_TABLE_NAME)) {
420 scanner = table.getScanner(scan);
421 try {
422 for (Result row : scanner) {
423 ListMultimap<String,TablePermission> resultPerms = parsePermissions(row.getRow(), row);
424 allPerms.put(row.getRow(), resultPerms);
425 }
426 } finally {
427 if (scanner != null) scanner.close();
428 }
429 }
430 }
431
432 return allPerms;
433 }
434
435 static ListMultimap<String, TablePermission> getTablePermissions(Configuration conf,
436 TableName tableName) throws IOException {
437 return getPermissions(conf, tableName != null ? tableName.getName() : null);
438 }
439
440 static ListMultimap<String, TablePermission> getNamespacePermissions(Configuration conf,
441 String namespace) throws IOException {
442 return getPermissions(conf, Bytes.toBytes(toNamespaceEntry(namespace)));
443 }
444
445
446
447
448
449
450
451
452
453
454 static ListMultimap<String, TablePermission> getPermissions(Configuration conf,
455 byte[] entryName) throws IOException {
456 if (entryName == null) entryName = ACL_GLOBAL_NAME;
457
458
459 ListMultimap<String, TablePermission> perms = ArrayListMultimap.create();
460
461 try (Connection connection = ConnectionFactory.createConnection(conf)) {
462 try (Table table = connection.getTable(ACL_TABLE_NAME)) {
463 Get get = new Get(entryName);
464 get.addFamily(ACL_LIST_FAMILY);
465 Result row = table.get(get);
466 if (!row.isEmpty()) {
467 perms = parsePermissions(entryName, row);
468 } else {
469 LOG.info("No permissions found in " + ACL_TABLE_NAME + " for acl entry "
470 + Bytes.toString(entryName));
471 }
472 }
473 }
474
475 return perms;
476 }
477
478
479
480
481
482 static List<UserPermission> getUserTablePermissions(
483 Configuration conf, TableName tableName) throws IOException {
484 return getUserPermissions(conf, tableName == null ? null : tableName.getName());
485 }
486
487 static List<UserPermission> getUserNamespacePermissions(
488 Configuration conf, String namespace) throws IOException {
489 return getUserPermissions(conf, Bytes.toBytes(toNamespaceEntry(namespace)));
490 }
491
492 static List<UserPermission> getUserPermissions(
493 Configuration conf, byte[] entryName)
494 throws IOException {
495 ListMultimap<String,TablePermission> allPerms = getPermissions(
496 conf, entryName);
497
498 List<UserPermission> perms = new ArrayList<UserPermission>();
499
500 for (Map.Entry<String, TablePermission> entry : allPerms.entries()) {
501 UserPermission up = new UserPermission(Bytes.toBytes(entry.getKey()),
502 entry.getValue().getTableName(), entry.getValue().getFamily(),
503 entry.getValue().getQualifier(), entry.getValue().getActions());
504 perms.add(up);
505 }
506 return perms;
507 }
508
509 private static ListMultimap<String, TablePermission> parsePermissions(
510 byte[] entryName, Result result) {
511 ListMultimap<String, TablePermission> perms = ArrayListMultimap.create();
512 if (result != null && result.size() > 0) {
513 for (Cell kv : result.rawCells()) {
514
515 Pair<String,TablePermission> permissionsOfUserOnTable =
516 parsePermissionRecord(entryName, kv);
517
518 if (permissionsOfUserOnTable != null) {
519 String username = permissionsOfUserOnTable.getFirst();
520 TablePermission permissions = permissionsOfUserOnTable.getSecond();
521 perms.put(username, permissions);
522 }
523 }
524 }
525 return perms;
526 }
527
528 private static Pair<String, TablePermission> parsePermissionRecord(
529 byte[] entryName, Cell kv) {
530
531 byte[] family = CellUtil.cloneFamily(kv);
532
533 if (!Bytes.equals(family, ACL_LIST_FAMILY)) {
534 return null;
535 }
536
537 byte[] key = CellUtil.cloneQualifier(kv);
538 byte[] value = CellUtil.cloneValue(kv);
539 if (LOG.isDebugEnabled()) {
540 LOG.debug("Read acl: kv ["+
541 Bytes.toStringBinary(key)+": "+
542 Bytes.toStringBinary(value)+"]");
543 }
544
545
546
547 String username = Bytes.toString(key);
548
549
550 if(isNamespaceEntry(entryName)) {
551 return new Pair<String, TablePermission>(username,
552 new TablePermission(Bytes.toString(fromNamespaceEntry(entryName)), value));
553 }
554
555
556
557 int idx = username.indexOf(ACL_KEY_DELIMITER);
558 byte[] permFamily = null;
559 byte[] permQualifier = null;
560 if (idx > 0 && idx < username.length()-1) {
561 String remainder = username.substring(idx+1);
562 username = username.substring(0, idx);
563 idx = remainder.indexOf(ACL_KEY_DELIMITER);
564 if (idx > 0 && idx < remainder.length()-1) {
565 permFamily = Bytes.toBytes(remainder.substring(0, idx));
566 permQualifier = Bytes.toBytes(remainder.substring(idx+1));
567 } else {
568 permFamily = Bytes.toBytes(remainder);
569 }
570 }
571
572 return new Pair<String,TablePermission>(username,
573 new TablePermission(TableName.valueOf(entryName), permFamily, permQualifier, value));
574 }
575
576
577
578
579
580
581
582 public static byte[] writePermissionsAsBytes(ListMultimap<String, TablePermission> perms,
583 Configuration conf) {
584 return ProtobufUtil.prependPBMagic(ProtobufUtil.toUserTablePermissions(perms).toByteArray());
585 }
586
587
588
589
590
591 public static ListMultimap<String, TablePermission> readPermissions(byte[] data,
592 Configuration conf)
593 throws DeserializationException {
594 if (ProtobufUtil.isPBMagicPrefix(data)) {
595 int pblen = ProtobufUtil.lengthOfPBMagic();
596 try {
597 AccessControlProtos.UsersAndPermissions perms =
598 AccessControlProtos.UsersAndPermissions.newBuilder().mergeFrom(
599 data, pblen, data.length - pblen).build();
600 return ProtobufUtil.toUserTablePermissions(perms);
601 } catch (InvalidProtocolBufferException e) {
602 throw new DeserializationException(e);
603 }
604 } else {
605 ListMultimap<String,TablePermission> perms = ArrayListMultimap.create();
606 try {
607 DataInput in = new DataInputStream(new ByteArrayInputStream(data));
608 int length = in.readInt();
609 for (int i=0; i<length; i++) {
610 String user = Text.readString(in);
611 List<TablePermission> userPerms =
612 (List)HbaseObjectWritableFor96Migration.readObject(in, conf);
613 perms.putAll(user, userPerms);
614 }
615 } catch (IOException e) {
616 throw new DeserializationException(e);
617 }
618 return perms;
619 }
620 }
621
622
623
624
625
626
627 public static boolean isGroupPrincipal(String name) {
628 return name != null && name.startsWith(GROUP_PREFIX);
629 }
630
631
632
633
634
635 public static String getGroupName(String aclKey) {
636 if (!isGroupPrincipal(aclKey)) {
637 return aclKey;
638 }
639
640 return aclKey.substring(GROUP_PREFIX.length());
641 }
642
643
644
645
646 public static String toGroupEntry(String name) {
647 return GROUP_PREFIX + name;
648 }
649
650 public static boolean isNamespaceEntry(String entryName) {
651 return entryName.charAt(0) == NAMESPACE_PREFIX;
652 }
653
654 public static boolean isNamespaceEntry(byte[] entryName) {
655 return entryName[0] == NAMESPACE_PREFIX;
656 }
657
658 public static String toNamespaceEntry(String namespace) {
659 return NAMESPACE_PREFIX + namespace;
660 }
661
662 public static String fromNamespaceEntry(String namespace) {
663 if(namespace.charAt(0) != NAMESPACE_PREFIX)
664 throw new IllegalArgumentException("Argument is not a valid namespace entry");
665 return namespace.substring(1);
666 }
667
668 public static byte[] toNamespaceEntry(byte[] namespace) {
669 byte[] ret = new byte[namespace.length+1];
670 ret[0] = NAMESPACE_PREFIX;
671 System.arraycopy(namespace, 0, ret, 1, namespace.length);
672 return ret;
673 }
674
675 public static byte[] fromNamespaceEntry(byte[] namespace) {
676 if(namespace[0] != NAMESPACE_PREFIX) {
677 throw new IllegalArgumentException("Argument is not a valid namespace entry: " +
678 Bytes.toString(namespace));
679 }
680 return Arrays.copyOfRange(namespace, 1, namespace.length);
681 }
682
683 public static List<Permission> getCellPermissionsForUser(User user, Cell cell)
684 throws IOException {
685
686 if (cell.getTagsLength() == 0) {
687 return null;
688 }
689 List<Permission> results = Lists.newArrayList();
690 Iterator<Tag> tagsIterator = CellUtil.tagsIterator(cell.getTagsArray(), cell.getTagsOffset(),
691 cell.getTagsLength());
692 while (tagsIterator.hasNext()) {
693 Tag tag = tagsIterator.next();
694 if (tag.getType() == ACL_TAG_TYPE) {
695
696 ListMultimap<String,Permission> kvPerms = ProtobufUtil.toUsersAndPermissions(
697 AccessControlProtos.UsersAndPermissions.newBuilder().mergeFrom(
698 tag.getBuffer(), tag.getTagOffset(), tag.getTagLength()).build());
699
700 List<Permission> userPerms = kvPerms.get(user.getShortName());
701 if (userPerms != null) {
702 results.addAll(userPerms);
703 }
704
705 String groupNames[] = user.getGroupNames();
706 if (groupNames != null) {
707 for (String group : groupNames) {
708 List<Permission> groupPerms = kvPerms.get(GROUP_PREFIX + group);
709 if (results != null) {
710 results.addAll(groupPerms);
711 }
712 }
713 }
714 }
715 }
716 return results;
717 }
718 }