001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.security.access; 019 020import com.google.errorprone.annotations.RestrictedApi; 021import java.io.ByteArrayInputStream; 022import java.io.DataInput; 023import java.io.DataInputStream; 024import java.io.IOException; 025import java.util.ArrayList; 026import java.util.Arrays; 027import java.util.Collection; 028import java.util.Iterator; 029import java.util.List; 030import java.util.Map; 031import java.util.Set; 032import java.util.TreeMap; 033import java.util.TreeSet; 034import java.util.function.Function; 035import java.util.stream.Collectors; 036import org.apache.commons.lang3.ArrayUtils; 037import org.apache.commons.lang3.StringUtils; 038import org.apache.hadoop.conf.Configuration; 039import org.apache.hadoop.hbase.AuthUtil; 040import org.apache.hadoop.hbase.Cell; 041import org.apache.hadoop.hbase.CellUtil; 042import org.apache.hadoop.hbase.ExtendedCell; 043import org.apache.hadoop.hbase.NamespaceDescriptor; 044import org.apache.hadoop.hbase.PrivateCellUtil; 045import org.apache.hadoop.hbase.TableName; 046import org.apache.hadoop.hbase.Tag; 047import org.apache.hadoop.hbase.TagType; 048import org.apache.hadoop.hbase.client.Connection; 049import org.apache.hadoop.hbase.client.Delete; 050import org.apache.hadoop.hbase.client.Get; 051import org.apache.hadoop.hbase.client.Put; 052import org.apache.hadoop.hbase.client.Result; 053import org.apache.hadoop.hbase.client.ResultScanner; 054import org.apache.hadoop.hbase.client.Scan; 055import org.apache.hadoop.hbase.client.Table; 056import org.apache.hadoop.hbase.client.TableDescriptor; 057import org.apache.hadoop.hbase.exceptions.DeserializationException; 058import org.apache.hadoop.hbase.regionserver.InternalScanner; 059import org.apache.hadoop.hbase.regionserver.Region; 060import org.apache.hadoop.hbase.security.User; 061import org.apache.hadoop.hbase.util.Bytes; 062import org.apache.hadoop.io.Text; 063import org.apache.hadoop.io.Writable; 064import org.apache.hadoop.io.WritableFactories; 065import org.apache.hadoop.io.WritableUtils; 066import org.apache.yetus.audience.InterfaceAudience; 067import org.slf4j.Logger; 068import org.slf4j.LoggerFactory; 069 070import org.apache.hbase.thirdparty.com.google.common.collect.ArrayListMultimap; 071import org.apache.hbase.thirdparty.com.google.common.collect.ListMultimap; 072import org.apache.hbase.thirdparty.com.google.common.collect.Lists; 073 074import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; 075import org.apache.hadoop.hbase.shaded.protobuf.generated.AccessControlProtos; 076 077/** 078 * Maintains lists of permission grants to users and groups to allow for authorization checks by 079 * {@link AccessController}. 080 * <p> 081 * Access control lists are stored in an "internal" metadata table named {@code _acl_}. Each table's 082 * permission grants are stored as a separate row, keyed by the table name. KeyValues for 083 * permissions assignments are stored in one of the formats: 084 * 085 * <pre> 086 * Key Desc 087 * -------- -------- 088 * user table level permissions for a user [R=read, W=write] 089 * group table level permissions for a group 090 * user,family column family level permissions for a user 091 * group,family column family level permissions for a group 092 * user,family,qualifier column qualifier level permissions for a user 093 * group,family,qualifier column qualifier level permissions for a group 094 * </pre> 095 * <p> 096 * All values are encoded as byte arrays containing the codes from the 097 * org.apache.hadoop.hbase.security.access.TablePermission.Action enum. 098 * </p> 099 */ 100@InterfaceAudience.Private 101public final class PermissionStorage { 102 /** Internal storage table for access control lists */ 103 public static final TableName ACL_TABLE_NAME = 104 TableName.valueOf(NamespaceDescriptor.SYSTEM_NAMESPACE_NAME_STR, "acl"); 105 public static final byte[] ACL_GLOBAL_NAME = ACL_TABLE_NAME.getName(); 106 /** Column family used to store ACL grants */ 107 public static final String ACL_LIST_FAMILY_STR = "l"; 108 public static final byte[] ACL_LIST_FAMILY = Bytes.toBytes(ACL_LIST_FAMILY_STR); 109 /** KV tag to store per cell access control lists */ 110 public static final byte ACL_TAG_TYPE = TagType.ACL_TAG_TYPE; 111 112 public static final char NAMESPACE_PREFIX = '@'; 113 114 /** 115 * Delimiter to separate user, column family, and qualifier in _acl_ table info: column keys 116 */ 117 public static final char ACL_KEY_DELIMITER = ','; 118 119 private static final Logger LOG = LoggerFactory.getLogger(PermissionStorage.class); 120 121 private PermissionStorage() { 122 } 123 124 private static byte[] toTableEntryName(TableName tableName) { 125 return tableName.getName(); 126 } 127 128 private static String getNamespaceFromEntryName(byte[] entryName) { 129 return Bytes.toString(entryName, 1); 130 } 131 132 /** 133 * Return the username for this table entry, and add family/qualifier to the given {@code builder} 134 * if available. 135 */ 136 private static String parseTableEntry(Permission.Builder builder, byte[] qual) { 137 byte delimiter = (byte) ACL_KEY_DELIMITER; 138 int idx = ArrayUtils.indexOf(qual, delimiter); 139 // no family/qualifier 140 if (idx < 0) { 141 return Bytes.toString(qual); 142 } 143 int idx2 = ArrayUtils.indexOf(qual, delimiter, idx + 1); 144 if (idx2 < 0) { 145 // no qualifer 146 builder.withFamily(Arrays.copyOfRange(qual, idx + 1, qual.length)); 147 } else { 148 builder.withFamily(Arrays.copyOfRange(qual, idx + 1, idx2)) 149 .withQualifier(Arrays.copyOfRange(qual, idx2 + 1, qual.length)); 150 } 151 return Bytes.toString(qual, 0, idx); 152 } 153 154 private static UserPermission parseUserPermission(byte[] entryName, byte[] qual, 155 byte[] actionCodes) { 156 if (ArrayUtils.isEmpty(actionCodes)) { 157 return null; 158 } 159 String user; 160 Permission.Builder builder; 161 if (isGlobalEntry(entryName)) { 162 builder = Permission.newBuilder(); 163 user = Bytes.toString(qual); 164 } else if (isNamespaceEntry(entryName)) { 165 builder = Permission.newBuilder(getNamespaceFromEntryName(entryName)); 166 user = Bytes.toString(qual); 167 } else { 168 // table entry 169 builder = Permission.newBuilder(TableName.valueOf(entryName)); 170 user = parseTableEntry(builder, qual); 171 } 172 return new UserPermission(user, builder.withActionCodes(actionCodes).build()); 173 } 174 175 // mainly used in grant/revoke, where we need to get the exact permission record for a given user 176 private static UserPermission getUserPermission(Table aclTable, UserPermission userPerm) 177 throws IOException { 178 byte[] entryName = userPermissionRowKey(userPerm.getPermission()); 179 Get get = new Get(entryName); 180 byte[] qual = userPermissionKey(userPerm); 181 get.addColumn(ACL_LIST_FAMILY, qual); 182 Result result = aclTable.get(get); 183 if (result.isEmpty()) { 184 return null; 185 } 186 byte[] actionCodes = result.getValue(ACL_LIST_FAMILY, qual); 187 return parseUserPermission(entryName, qual, actionCodes); 188 } 189 190 private static byte[] getActionCodes(Permission perm) { 191 Permission.Action[] actions = perm.getActions(); 192 byte[] actionCodes = new byte[actions.length]; 193 for (int i = 0; i < actionCodes.length; i++) { 194 actionCodes[i] = actions[i].code(); 195 } 196 return actionCodes; 197 } 198 199 private static void put(Table aclTable, UserPermission userPerm) throws IOException { 200 Permission perm = userPerm.getPermission(); 201 Put put = new Put(userPermissionRowKey(perm)); 202 byte[] qual = userPermissionKey(userPerm); 203 byte[] value = getActionCodes(perm); 204 put.addColumn(ACL_LIST_FAMILY, qual, value); 205 if (LOG.isDebugEnabled()) { 206 LOG.debug("Writing permission with rowKey " + Bytes.toString(put.getRow()) + " " 207 + Bytes.toString(qual) + ": " + Bytes.toStringBinary(value)); 208 } 209 aclTable.put(put); 210 } 211 212 private static void delete(UserPermission userPerm, Table aclTable) throws IOException { 213 Delete d = new Delete(userPermissionRowKey(userPerm.getPermission())); 214 byte[] qual = userPermissionKey(userPerm); 215 d.addColumns(ACL_LIST_FAMILY, qual); 216 if (LOG.isDebugEnabled()) { 217 LOG.debug("Removing permission with rowKey " + Bytes.toString(d.getRow()) + " " 218 + Bytes.toString(qual)); 219 } 220 aclTable.delete(d); 221 } 222 223 private static IOException warnAndThrow(String msg) throws IOException { 224 LOG.warn(msg); 225 throw new IOException(msg); 226 } 227 228 private static void validateUserOrGroupName(String name, Function<String, String> formatter) 229 throws IOException { 230 // empty name is not allowed 231 if (StringUtils.isBlank(name)) { 232 throw warnAndThrow(formatter.apply("Blank %s name '%s' is not allowed")); 233 } 234 // leading/trailing whitespace is not allowed since a real name never has it 235 if (!name.equals(name.trim())) { 236 throw warnAndThrow( 237 formatter.apply("Leading or trailing whitespace in %s name '%s' is not allowed")); 238 } 239 // ',' is used as separator so you can not use it in name 240 if (name.contains(",")) { 241 throw warnAndThrow(formatter.apply("',' in %s name '%s' is not allowed")); 242 } 243 } 244 245 private static void validateUser(String user) throws IOException { 246 if (user == null) { 247 throw warnAndThrow("null user name is not allowed"); 248 } 249 if (user.startsWith("@")) { 250 validateUserOrGroupName(user.substring(1), msg -> String.format(msg, "group", user)); 251 } else { 252 validateUserOrGroupName(user, msg -> String.format(msg, "user", user)); 253 } 254 } 255 256 /** 257 * Stores a new user permission grant in the access control lists table. 258 * @param conn connection to hbase cluster 259 * @param userPerm the details of the permission to be granted 260 * @param aclTable acl table instance. It is closed upon method return. 261 * @throws IOException in the case of an error accessing the metadata table, or the 262 * {@code userPerm} is invalid, i.e, has an invalid user/group name or an 263 * empty actions. 264 */ 265 public static void addUserPermission(Connection conn, UserPermission userPerm, 266 boolean mergeExistingPermissions) throws IOException { 267 validateUser(userPerm.getUser()); 268 if (ArrayUtils.isEmpty(userPerm.getPermission().getActions())) { 269 throw warnAndThrow("No actions associated with user '" + userPerm.getUser() + "'"); 270 } 271 try (Table aclTable = conn.getTable(ACL_TABLE_NAME)) { 272 UserPermission toAdd; 273 if (mergeExistingPermissions) { 274 UserPermission oldUserPerm = getUserPermission(aclTable, userPerm); 275 if (oldUserPerm == null || ArrayUtils.isEmpty(oldUserPerm.getPermission().getActions())) { 276 toAdd = userPerm; 277 } else { 278 Set<Permission.Action> actionSet = new TreeSet<>(); 279 actionSet.addAll(Arrays.asList(oldUserPerm.getPermission().getActions())); 280 actionSet.addAll(Arrays.asList(userPerm.getPermission().getActions())); 281 oldUserPerm.getPermission().setActions(actionSet.toArray(Permission.Action[]::new)); 282 toAdd = oldUserPerm; 283 } 284 } else { 285 toAdd = userPerm; 286 } 287 put(aclTable, toAdd); 288 } 289 } 290 291 /** 292 * Removes a previously granted permission from the stored access control lists. 293 * <p> 294 * The {@link TablePermission} being removed must exactly match what is stored -- no wildcard 295 * matching is attempted. Ie, if user "bob" has been granted "READ" access to the "data" table, 296 * but only to column family plus qualifier "info:colA", then trying to call this method with only 297 * user "bob" and the table name "data" (but without specifying the column qualifier "info:colA") 298 * will have no effect. 299 * <p> 300 * Passing an {@code userPerm} with empty actions means revoke all the permissions. 301 * @param conn connection to hbase cluster 302 * @param userPerm the details of the permission to be revoked 303 * @throws IOException in the case of an error accessing the metadata table, or the 304 * {@code userPerm} is invalid, i.e, has an invalid user/group name. 305 */ 306 public static void removeUserPermission(Connection conn, UserPermission userPerm) 307 throws IOException { 308 validateUser(userPerm.getUser()); 309 try (Table aclTable = conn.getTable(ACL_TABLE_NAME)) { 310 Permission perm = userPerm.getPermission(); 311 if (ArrayUtils.isEmpty(perm.getActions())) { 312 delete(userPerm, aclTable); 313 return; 314 } 315 UserPermission oldUserPerm = getUserPermission(aclTable, userPerm); 316 if (oldUserPerm == null) { 317 // nothing to revoke 318 return; 319 } 320 Permission oldPerm = oldUserPerm.getPermission(); 321 Set<Permission.Action> remainingActions = new TreeSet<>(); 322 if (!ArrayUtils.isEmpty(oldPerm.getActions())) { 323 remainingActions.addAll(Arrays.asList(oldPerm.getActions())); 324 } 325 for (Permission.Action action : perm.getActions()) { 326 remainingActions.remove(action); 327 } 328 if (remainingActions.isEmpty()) { 329 delete(userPerm, aclTable); 330 } else { 331 oldPerm.setActions(remainingActions.toArray(Permission.Action[]::new)); 332 put(aclTable, oldUserPerm); 333 } 334 if (LOG.isDebugEnabled()) { 335 LOG.debug("Removed permission " + userPerm.toString()); 336 } 337 } 338 } 339 340 /** 341 * Remove specified table from the _acl_ table. 342 */ 343 static void removeTablePermissions(Connection conn, TableName tableName) throws IOException { 344 if (LOG.isDebugEnabled()) { 345 LOG.debug("Removing permissions of removed table " + tableName); 346 } 347 Delete d = new Delete(toTableEntryName(tableName)).addFamily(ACL_LIST_FAMILY); 348 try (Table aclTable = conn.getTable(ACL_TABLE_NAME)) { 349 aclTable.delete(d); 350 } 351 } 352 353 /** 354 * Remove specified namespace from the acl table. 355 */ 356 static void removeNamespacePermissions(Connection conn, String namespace) throws IOException { 357 if (LOG.isDebugEnabled()) { 358 LOG.debug("Removing permissions of removed namespace " + namespace); 359 } 360 Delete d = new Delete(toNamespaceEntry(namespace)).addFamily(ACL_LIST_FAMILY); 361 362 try (Table aclTable = conn.getTable(ACL_TABLE_NAME)) { 363 aclTable.delete(d); 364 } 365 } 366 367 /** 368 * Remove permissions of the specified column families of the given table from the acl table. 369 */ 370 static void removeTableColumnFamiliesPermissions(Connection conn, TableName tableName, 371 Collection<byte[]> columns) throws IOException { 372 if (LOG.isDebugEnabled()) { 373 LOG.debug("Removing permissions of removed columns {} from table {}", 374 columns.stream().map(Bytes::toStringBinary).collect(Collectors.joining(", ")), tableName); 375 } 376 Set<byte[]> families = new TreeSet<>(Bytes.BYTES_COMPARATOR); 377 families.addAll(columns); 378 List<UserPermission> userPerms = getTablePermissions(conn, tableName); 379 Delete d = new Delete(toTableEntryName(tableName)); 380 boolean found = false; 381 for (UserPermission userPerm : userPerms) { 382 TablePermission perm = (TablePermission) userPerm.getPermission(); 383 byte[] family = perm.getFamily(); 384 if (family != null && families.contains(family)) { 385 d.addColumns(ACL_LIST_FAMILY, userPermissionKey(userPerm)); 386 found = true; 387 } 388 } 389 if (found) { 390 try (Table aclTable = conn.getTable(ACL_TABLE_NAME)) { 391 aclTable.delete(d); 392 } 393 } 394 } 395 396 private static byte[] userPermissionRowKey(Permission permission) { 397 byte[] row; 398 if (permission instanceof TablePermission) { 399 TablePermission tablePerm = (TablePermission) permission; 400 row = toTableEntryName(tablePerm.getTableName()); 401 } else if (permission instanceof NamespacePermission) { 402 NamespacePermission nsPerm = (NamespacePermission) permission; 403 row = toNamespaceEntry(nsPerm.getNamespace()); 404 } else { 405 // permission instanceof TablePermission 406 row = ACL_GLOBAL_NAME; 407 } 408 return row; 409 } 410 411 /** 412 * Build qualifier key from user permission: username username,family username,family,qualifier 413 */ 414 private static byte[] userPermissionKey(UserPermission permission) { 415 byte[] key = Bytes.toBytes(permission.getUser()); 416 byte[] qualifier = null; 417 byte[] family = null; 418 if (permission.getPermission().getAccessScope() == Permission.Scope.TABLE) { 419 TablePermission tablePermission = (TablePermission) permission.getPermission(); 420 family = tablePermission.getFamily(); 421 qualifier = tablePermission.getQualifier(); 422 } 423 424 if (family != null && family.length > 0) { 425 key = Bytes.add(key, Bytes.add(new byte[] { ACL_KEY_DELIMITER }, family)); 426 if (qualifier != null && qualifier.length > 0) { 427 key = Bytes.add(key, Bytes.add(new byte[] { ACL_KEY_DELIMITER }, qualifier)); 428 } 429 } 430 431 return key; 432 } 433 434 /** 435 * Returns {@code true} if the given region is part of the {@code _acl_} metadata table. 436 */ 437 static boolean isAclRegion(Region region) { 438 return ACL_TABLE_NAME.equals(region.getTableDescriptor().getTableName()); 439 } 440 441 /** 442 * Returns {@code true} if the given table is {@code _acl_} metadata table. 443 */ 444 static boolean isAclTable(TableDescriptor desc) { 445 return ACL_TABLE_NAME.equals(desc.getTableName()); 446 } 447 448 /** 449 * Loads all of the permission grants stored in a region of the {@code _acl_} table. 450 * @param aclRegion the acl region 451 * @return a map of the permissions for this table. 452 * @throws IOException if an error occurs 453 */ 454 static Map<byte[], ListMultimap<String, UserPermission>> loadAll(Region aclRegion) 455 throws IOException { 456 if (!isAclRegion(aclRegion)) { 457 throw new IOException("Can only load permissions from " + ACL_TABLE_NAME); 458 } 459 460 Map<byte[], ListMultimap<String, UserPermission>> allPerms = 461 new TreeMap<>(Bytes.BYTES_RAWCOMPARATOR); 462 // do a full scan of _acl_ table 463 Scan scan = new Scan().addFamily(ACL_LIST_FAMILY); 464 try (InternalScanner scanner = aclRegion.getScanner(scan);) { 465 while (true) { 466 List<Cell> row = new ArrayList<>(); 467 boolean hasNext = scanner.next(row); 468 ListMultimap<String, UserPermission> perms = ArrayListMultimap.create(); 469 byte[] entry = null; 470 for (Cell kv : row) { 471 if (entry == null) { 472 entry = CellUtil.cloneRow(kv); 473 } 474 UserPermission userPerm = 475 parseUserPermission(entry, CellUtil.cloneQualifier(kv), CellUtil.cloneValue(kv)); 476 if (userPerm != null) { 477 perms.put(userPerm.getUser(), userPerm); 478 } 479 } 480 if (entry != null) { 481 allPerms.put(entry, perms); 482 } 483 if (!hasNext) { 484 break; 485 } 486 } 487 } 488 489 return allPerms; 490 } 491 492 /** 493 * Load all permissions from the region server holding {@code _acl_}, primarily intended for 494 * testing purposes. 495 */ 496 @RestrictedApi(explanation = "Should only be called in tests", link = "", 497 allowedOnPath = ".*/src/test/.*") 498 static Map<byte[], ListMultimap<String, UserPermission>> loadAll(Connection conn) 499 throws IOException { 500 Map<byte[], ListMultimap<String, UserPermission>> allPerms = 501 new TreeMap<>(Bytes.BYTES_RAWCOMPARATOR); 502 503 // do a full scan of _acl_, filtering on only first table region rows 504 Scan scan = new Scan(); 505 scan.addFamily(ACL_LIST_FAMILY); 506 try (Table table = conn.getTable(ACL_TABLE_NAME); 507 ResultScanner scanner = table.getScanner(scan)) { 508 while (true) { 509 Result result = scanner.next(); 510 if (result == null) { 511 break; 512 } 513 byte[] entryName = result.getRow(); 514 ListMultimap<String, UserPermission> perms = ArrayListMultimap.create(); 515 result.getFamilyMap(ACL_LIST_FAMILY).forEach((qual, actionCodes) -> { 516 UserPermission userPerm = parseUserPermission(entryName, qual, actionCodes); 517 if (userPerm != null) { 518 perms.put(userPerm.getUser(), userPerm); 519 } else { 520 // Malformed/empty ACL cell; skip to avoid NPE and continue scanning. 521 LOG.warn("Skipping malformed ACL entry for row={} qualifier={}", 522 Bytes.toStringBinary(entryName), Bytes.toStringBinary(qual)); 523 } 524 }); 525 allPerms.put(entryName, perms); 526 } 527 } 528 529 return allPerms; 530 } 531 532 /** 533 * Get all the permission entries for this table. 534 */ 535 public static List<UserPermission> getTablePermissions(Connection conn, TableName tableName) 536 throws IOException { 537 if (ACL_TABLE_NAME.equals(tableName)) { 538 // hbase:acl does not have any permission record, the entry for hbase:acl is for storing the 539 // global permissions 540 // TODO: typically caller should not do this, better throwing an exception? 541 return getGlobalPermissions(conn); 542 } 543 byte[] entryName = toTableEntryName(tableName); 544 Get get = new Get(entryName).addFamily(ACL_LIST_FAMILY); 545 List<UserPermission> userPerms = new ArrayList<>(); 546 try (Table aclTable = conn.getTable(ACL_TABLE_NAME)) { 547 Result result = aclTable.get(get); 548 if (!result.isEmpty()) { 549 result.getFamilyMap(ACL_LIST_FAMILY).forEach((qual, actionCodes) -> { 550 if (ArrayUtils.isEmpty(actionCodes)) { 551 // Malformed/empty ACL cell; skip to avoid NPE 552 LOG.warn("Skipping malformed ACL entry for row={} qualifier={}", 553 Bytes.toStringBinary(entryName), Bytes.toStringBinary(qual)); 554 return; 555 } 556 Permission.Builder builder = 557 Permission.newBuilder(tableName).withActionCodes(actionCodes); 558 String user = parseTableEntry(builder, qual); 559 userPerms.add(new UserPermission(user, builder.build())); 560 }); 561 } 562 } 563 return userPerms; 564 } 565 566 public static List<UserPermission> getNamespacePermissions(Connection conn, String namespace) 567 throws IOException { 568 byte[] entryName = toNamespaceEntry(namespace); 569 Get get = new Get(entryName).addFamily(ACL_LIST_FAMILY); 570 List<UserPermission> userPerms = new ArrayList<>(); 571 try (Table aclTable = conn.getTable(ACL_TABLE_NAME)) { 572 Result result = aclTable.get(get); 573 if (!result.isEmpty()) { 574 575 result.getFamilyMap(ACL_LIST_FAMILY).forEach((qual, actionCodes) -> { 576 if (ArrayUtils.isEmpty(actionCodes)) { 577 // Malformed/empty ACL cell; skip to avoid NPE 578 LOG.warn("Skipping malformed ACL entry for row={} qualifier={}", 579 Bytes.toStringBinary(entryName), Bytes.toStringBinary(qual)); 580 return; 581 } 582 Permission perm = Permission.newBuilder(namespace).withActionCodes(actionCodes).build(); 583 String user = Bytes.toString(qual); 584 userPerms.add(new UserPermission(user, perm)); 585 }); 586 } 587 } 588 return userPerms; 589 } 590 591 public static List<UserPermission> getGlobalPermissions(Connection conn) throws IOException { 592 Get get = new Get(ACL_GLOBAL_NAME).addFamily(ACL_LIST_FAMILY); 593 List<UserPermission> userPerms = new ArrayList<>(); 594 try (Table aclTable = conn.getTable(ACL_TABLE_NAME)) { 595 Result result = aclTable.get(get); 596 if (!result.isEmpty()) { 597 result.getFamilyMap(ACL_LIST_FAMILY).forEach((qual, actionCodes) -> { 598 if (ArrayUtils.isEmpty(actionCodes)) { 599 // Malformed/empty ACL cell; skip to avoid NPE 600 LOG.warn("Skipping malformed ACL entry for row={} qualifier={}", 601 Bytes.toStringBinary(ACL_GLOBAL_NAME), Bytes.toStringBinary(qual)); 602 return; 603 } 604 Permission perm = Permission.newBuilder().withActionCodes(actionCodes).build(); 605 String user = Bytes.toString(qual); 606 userPerms.add(new UserPermission(user, perm)); 607 }); 608 } 609 } 610 return userPerms; 611 } 612 613 public static boolean isGlobalEntry(byte[] entryName) { 614 return Bytes.equals(entryName, ACL_GLOBAL_NAME); 615 } 616 617 public static boolean isNamespaceEntry(String entryName) { 618 return isNamespaceEntry(Bytes.toBytes(entryName)); 619 } 620 621 public static boolean isNamespaceEntry(byte[] entryName) { 622 return entryName != null && entryName.length != 0 && entryName[0] == NAMESPACE_PREFIX; 623 } 624 625 public static boolean isTableEntry(byte[] entryName) { 626 return !isNamespaceEntry(entryName) && !isGlobalEntry(entryName) && entryName != null; 627 } 628 629 public static byte[] toNamespaceEntry(String namespace) { 630 return Bytes.toBytes(NAMESPACE_PREFIX + namespace); 631 } 632 633 public static String fromNamespaceEntry(String namespace) { 634 if (namespace.charAt(0) != NAMESPACE_PREFIX) { 635 throw new IllegalArgumentException("Argument is not a valid namespace entry"); 636 } 637 return namespace.substring(1); 638 } 639 640 public static byte[] toNamespaceEntry(byte[] namespace) { 641 byte[] ret = new byte[namespace.length + 1]; 642 ret[0] = NAMESPACE_PREFIX; 643 System.arraycopy(namespace, 0, ret, 1, namespace.length); 644 return ret; 645 } 646 647 public static byte[] fromNamespaceEntry(byte[] namespace) { 648 if (namespace[0] != NAMESPACE_PREFIX) { 649 throw new IllegalArgumentException( 650 "Argument is not a valid namespace entry: " + Bytes.toString(namespace)); 651 } 652 return Arrays.copyOfRange(namespace, 1, namespace.length); 653 } 654 655 public static List<Permission> getCellPermissionsForUser(User user, ExtendedCell cell) 656 throws IOException { 657 // Save an object allocation where we can 658 if (cell.getTagsLength() == 0) { 659 return null; 660 } 661 List<Permission> results = Lists.newArrayList(); 662 Iterator<Tag> tagsIterator = PrivateCellUtil.tagsIterator(cell); 663 while (tagsIterator.hasNext()) { 664 Tag tag = tagsIterator.next(); 665 if (tag.getType() == ACL_TAG_TYPE) { 666 // Deserialize the table permissions from the KV 667 // TODO: This can be improved. Don't build UsersAndPermissions just to unpack it again, 668 // use the builder 669 AccessControlProtos.UsersAndPermissions.Builder builder = 670 AccessControlProtos.UsersAndPermissions.newBuilder(); 671 if (tag.hasArray()) { 672 ProtobufUtil.mergeFrom(builder, tag.getValueArray(), tag.getValueOffset(), 673 tag.getValueLength()); 674 } else { 675 ProtobufUtil.mergeFrom(builder, Tag.cloneValue(tag)); 676 } 677 ListMultimap<String, Permission> kvPerms = 678 AccessControlUtil.toUsersAndPermissions(builder.build()); 679 // Are there permissions for this user? 680 List<Permission> userPerms = kvPerms.get(user.getShortName()); 681 if (userPerms != null) { 682 results.addAll(userPerms); 683 } 684 // Are there permissions for any of the groups this user belongs to? 685 String[] groupNames = user.getGroupNames(); 686 if (groupNames != null) { 687 for (String group : groupNames) { 688 List<Permission> groupPerms = kvPerms.get(AuthUtil.toGroupEntry(group)); 689 if (results != null) { 690 results.addAll(groupPerms); 691 } 692 } 693 } 694 } 695 } 696 return results; 697 } 698 699 // ==================== 700 // Below are methods for sync permission between acl table and zk 701 // ==================== 702 703 /** 704 * Reads user permission assignments stored in the <code>l:</code> column family of the first 705 * table row in <code>_acl_</code>. 706 * <p> 707 * See {@link PermissionStorage class documentation} for the key structure used for storage. 708 * </p> 709 */ 710 static ListMultimap<String, UserPermission> getPermissions(Connection conn, byte[] entryName) 711 throws IOException { 712 // for normal user tables, we just read the table row from _acl_ 713 ListMultimap<String, UserPermission> perms = ArrayListMultimap.create(); 714 Get get = new Get(entryName); 715 get.addFamily(ACL_LIST_FAMILY); 716 Result result; 717 try (Table aclTable = conn.getTable(ACL_TABLE_NAME)) { 718 result = aclTable.get(get); 719 } 720 if (!result.isEmpty()) { 721 result.getFamilyMap(ACL_LIST_FAMILY).forEach((qual, actionCodes) -> { 722 UserPermission userPerm = parseUserPermission(entryName, qual, actionCodes); 723 if (userPerm != null) { 724 perms.put(userPerm.getUser(), userPerm); 725 } else { 726 // Malformed/empty ACL cell; skip to avoid NPE 727 LOG.warn("Skipping malformed ACL entry for row={} qualifier={}", 728 Bytes.toStringBinary(entryName), Bytes.toStringBinary(qual)); 729 } 730 }); 731 } else { 732 LOG.info("No permissions found in " + ACL_TABLE_NAME + " for acl entry " 733 + Bytes.toString(entryName)); 734 } 735 736 return perms; 737 } 738 739 /** 740 * Writes a set of permissions as {@link org.apache.hadoop.io.Writable} instances and returns the 741 * resulting byte array. Writes a set of permission [user: table permission] 742 */ 743 public static byte[] writePermissionsAsBytes(ListMultimap<String, UserPermission> perms, 744 Configuration conf) { 745 return ProtobufUtil 746 .prependPBMagic(AccessControlUtil.toUserTablePermissions(perms).toByteArray()); 747 } 748 749 // This is part of the old HbaseObjectWritableFor96Migration. 750 private static final int LIST_CODE = 61; 751 752 private static final int WRITABLE_CODE = 14; 753 754 private static final int WRITABLE_NOT_ENCODED = 0; 755 756 private static List<Permission> readWritableUserPermission(DataInput in, Configuration conf) 757 throws IOException, ClassNotFoundException { 758 assert WritableUtils.readVInt(in) == LIST_CODE; 759 int length = in.readInt(); 760 List<Permission> list = new ArrayList<>(length); 761 for (int i = 0; i < length; i++) { 762 assert WritableUtils.readVInt(in) == WRITABLE_CODE; 763 assert WritableUtils.readVInt(in) == WRITABLE_NOT_ENCODED; 764 String className = Text.readString(in); 765 Class<? extends Writable> clazz = conf.getClassByName(className).asSubclass(Writable.class); 766 Writable instance = WritableFactories.newInstance(clazz, conf); 767 instance.readFields(in); 768 list.add((Permission) instance); 769 } 770 return list; 771 } 772 773 public static ListMultimap<String, UserPermission> readUserPermission(byte[] data, 774 Configuration conf) throws DeserializationException { 775 if (ProtobufUtil.isPBMagicPrefix(data)) { 776 int pblen = ProtobufUtil.lengthOfPBMagic(); 777 try { 778 AccessControlProtos.UsersAndPermissions.Builder builder = 779 AccessControlProtos.UsersAndPermissions.newBuilder(); 780 ProtobufUtil.mergeFrom(builder, data, pblen, data.length - pblen); 781 return AccessControlUtil.toUserPermission(builder.build()); 782 } catch (IOException e) { 783 throw new DeserializationException(e); 784 } 785 } else { 786 // TODO: We have to re-write non-PB data as PB encoded. Otherwise we will carry old Writables 787 // forever (here and a couple of other places). 788 ListMultimap<String, UserPermission> userPermission = ArrayListMultimap.create(); 789 try { 790 DataInput in = new DataInputStream(new ByteArrayInputStream(data)); 791 int length = in.readInt(); 792 for (int i = 0; i < length; i++) { 793 String user = Text.readString(in); 794 List<Permission> perms = readWritableUserPermission(in, conf); 795 for (Permission p : perms) { 796 userPermission.put(user, new UserPermission(user, p)); 797 } 798 } 799 } catch (IOException | ClassNotFoundException e) { 800 throw new DeserializationException(e); 801 } 802 return userPermission; 803 } 804 } 805 806 public static ListMultimap<String, Permission> readPermissions(byte[] data, Configuration conf) 807 throws DeserializationException { 808 if (ProtobufUtil.isPBMagicPrefix(data)) { 809 int pblen = ProtobufUtil.lengthOfPBMagic(); 810 try { 811 AccessControlProtos.UsersAndPermissions.Builder builder = 812 AccessControlProtos.UsersAndPermissions.newBuilder(); 813 ProtobufUtil.mergeFrom(builder, data, pblen, data.length - pblen); 814 return AccessControlUtil.toPermission(builder.build()); 815 } catch (IOException e) { 816 throw new DeserializationException(e); 817 } 818 } else { 819 // TODO: We have to re-write non-PB data as PB encoded. Otherwise we will carry old Writables 820 // forever (here and a couple of other places). 821 ListMultimap<String, Permission> perms = ArrayListMultimap.create(); 822 try { 823 DataInput in = new DataInputStream(new ByteArrayInputStream(data)); 824 int length = in.readInt(); 825 for (int i = 0; i < length; i++) { 826 String user = Text.readString(in); 827 perms.putAll(user, readWritableUserPermission(in, conf)); 828 } 829 } catch (IOException | ClassNotFoundException e) { 830 throw new DeserializationException(e); 831 } 832 return perms; 833 } 834 } 835}