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 java.io.IOException; 021import java.security.PrivilegedExceptionAction; 022import java.util.ArrayList; 023import java.util.Collection; 024import java.util.Collections; 025import java.util.HashMap; 026import java.util.Iterator; 027import java.util.List; 028import java.util.Map; 029import java.util.Map.Entry; 030import java.util.Optional; 031import java.util.Set; 032import java.util.TreeMap; 033import java.util.TreeSet; 034import java.util.stream.Collectors; 035import org.apache.hadoop.conf.Configuration; 036import org.apache.hadoop.hbase.ArrayBackedTag; 037import org.apache.hadoop.hbase.Cell; 038import org.apache.hadoop.hbase.CellUtil; 039import org.apache.hadoop.hbase.CompareOperator; 040import org.apache.hadoop.hbase.CompoundConfiguration; 041import org.apache.hadoop.hbase.CoprocessorEnvironment; 042import org.apache.hadoop.hbase.DoNotRetryIOException; 043import org.apache.hadoop.hbase.ExtendedCell; 044import org.apache.hadoop.hbase.ExtendedCellScanner; 045import org.apache.hadoop.hbase.HBaseInterfaceAudience; 046import org.apache.hadoop.hbase.HConstants; 047import org.apache.hadoop.hbase.KeyValue; 048import org.apache.hadoop.hbase.KeyValue.Type; 049import org.apache.hadoop.hbase.NamespaceDescriptor; 050import org.apache.hadoop.hbase.PrivateCellUtil; 051import org.apache.hadoop.hbase.ServerName; 052import org.apache.hadoop.hbase.TableName; 053import org.apache.hadoop.hbase.Tag; 054import org.apache.hadoop.hbase.client.Admin; 055import org.apache.hadoop.hbase.client.Append; 056import org.apache.hadoop.hbase.client.BalanceRequest; 057import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor; 058import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; 059import org.apache.hadoop.hbase.client.Delete; 060import org.apache.hadoop.hbase.client.Durability; 061import org.apache.hadoop.hbase.client.Get; 062import org.apache.hadoop.hbase.client.Increment; 063import org.apache.hadoop.hbase.client.MasterSwitchType; 064import org.apache.hadoop.hbase.client.Mutation; 065import org.apache.hadoop.hbase.client.Put; 066import org.apache.hadoop.hbase.client.Query; 067import org.apache.hadoop.hbase.client.RegionInfo; 068import org.apache.hadoop.hbase.client.Result; 069import org.apache.hadoop.hbase.client.Scan; 070import org.apache.hadoop.hbase.client.SnapshotDescription; 071import org.apache.hadoop.hbase.client.Table; 072import org.apache.hadoop.hbase.client.TableDescriptor; 073import org.apache.hadoop.hbase.client.TableDescriptorBuilder; 074import org.apache.hadoop.hbase.coprocessor.BulkLoadObserver; 075import org.apache.hadoop.hbase.coprocessor.CoprocessorException; 076import org.apache.hadoop.hbase.coprocessor.CoreCoprocessor; 077import org.apache.hadoop.hbase.coprocessor.EndpointObserver; 078import org.apache.hadoop.hbase.coprocessor.HasMasterServices; 079import org.apache.hadoop.hbase.coprocessor.HasRegionServerServices; 080import org.apache.hadoop.hbase.coprocessor.MasterCoprocessor; 081import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment; 082import org.apache.hadoop.hbase.coprocessor.MasterObserver; 083import org.apache.hadoop.hbase.coprocessor.ObserverContext; 084import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor; 085import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; 086import org.apache.hadoop.hbase.coprocessor.RegionObserver; 087import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessor; 088import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessorEnvironment; 089import org.apache.hadoop.hbase.coprocessor.RegionServerObserver; 090import org.apache.hadoop.hbase.filter.ByteArrayComparable; 091import org.apache.hadoop.hbase.filter.Filter; 092import org.apache.hadoop.hbase.filter.FilterList; 093import org.apache.hadoop.hbase.io.hfile.HFile; 094import org.apache.hadoop.hbase.ipc.CoprocessorRpcUtils; 095import org.apache.hadoop.hbase.ipc.RpcServer; 096import org.apache.hadoop.hbase.master.MasterServices; 097import org.apache.hadoop.hbase.net.Address; 098import org.apache.hadoop.hbase.quotas.GlobalQuotaSettings; 099import org.apache.hadoop.hbase.regionserver.BloomType; 100import org.apache.hadoop.hbase.regionserver.FlushLifeCycleTracker; 101import org.apache.hadoop.hbase.regionserver.InternalScanner; 102import org.apache.hadoop.hbase.regionserver.MiniBatchOperationInProgress; 103import org.apache.hadoop.hbase.regionserver.Region; 104import org.apache.hadoop.hbase.regionserver.RegionScanner; 105import org.apache.hadoop.hbase.regionserver.RegionServerServices; 106import org.apache.hadoop.hbase.regionserver.ScanType; 107import org.apache.hadoop.hbase.regionserver.ScannerContext; 108import org.apache.hadoop.hbase.regionserver.Store; 109import org.apache.hadoop.hbase.regionserver.compactions.CompactionLifeCycleTracker; 110import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest; 111import org.apache.hadoop.hbase.replication.ReplicationEndpoint; 112import org.apache.hadoop.hbase.replication.ReplicationPeerConfig; 113import org.apache.hadoop.hbase.replication.SyncReplicationState; 114import org.apache.hadoop.hbase.security.AccessDeniedException; 115import org.apache.hadoop.hbase.security.Superusers; 116import org.apache.hadoop.hbase.security.User; 117import org.apache.hadoop.hbase.security.UserProvider; 118import org.apache.hadoop.hbase.security.access.Permission.Action; 119import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils; 120import org.apache.hadoop.hbase.util.ByteRange; 121import org.apache.hadoop.hbase.util.Bytes; 122import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; 123import org.apache.hadoop.hbase.util.Pair; 124import org.apache.hadoop.hbase.util.SimpleMutableByteRange; 125import org.apache.hadoop.hbase.wal.WALEdit; 126import org.apache.yetus.audience.InterfaceAudience; 127import org.slf4j.Logger; 128import org.slf4j.LoggerFactory; 129 130import org.apache.hbase.thirdparty.com.google.common.base.Preconditions; 131import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableSet; 132import org.apache.hbase.thirdparty.com.google.common.collect.ListMultimap; 133import org.apache.hbase.thirdparty.com.google.common.collect.Lists; 134import org.apache.hbase.thirdparty.com.google.common.collect.MapMaker; 135import org.apache.hbase.thirdparty.com.google.common.collect.Maps; 136import org.apache.hbase.thirdparty.com.google.protobuf.Message; 137import org.apache.hbase.thirdparty.com.google.protobuf.RpcCallback; 138import org.apache.hbase.thirdparty.com.google.protobuf.RpcController; 139import org.apache.hbase.thirdparty.com.google.protobuf.Service; 140 141import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; 142import org.apache.hadoop.hbase.shaded.protobuf.ResponseConverter; 143import org.apache.hadoop.hbase.shaded.protobuf.generated.AccessControlProtos; 144import org.apache.hadoop.hbase.shaded.protobuf.generated.AccessControlProtos.AccessControlService; 145import org.apache.hadoop.hbase.shaded.protobuf.generated.AccessControlProtos.HasPermissionRequest; 146import org.apache.hadoop.hbase.shaded.protobuf.generated.AccessControlProtos.HasPermissionResponse; 147 148/** 149 * Provides basic authorization checks for data access and administrative operations. 150 * <p> 151 * {@code AccessController} performs authorization checks for HBase operations based on: 152 * </p> 153 * <ul> 154 * <li>the identity of the user performing the operation</li> 155 * <li>the scope over which the operation is performed, in increasing specificity: global, table, 156 * column family, or qualifier</li> 157 * <li>the type of action being performed (as mapped to {@link Permission.Action} values)</li> 158 * </ul> 159 * <p> 160 * If the authorization check fails, an {@link AccessDeniedException} will be thrown for the 161 * operation. 162 * </p> 163 * <p> 164 * To perform authorization checks, {@code AccessController} relies on the RpcServerEngine being 165 * loaded to provide the user identities for remote requests. 166 * </p> 167 * <p> 168 * The access control lists used for authorization can be manipulated via the exposed 169 * {@link AccessControlService} Interface implementation, and the associated {@code grant}, 170 * {@code revoke}, and {@code user_permission} HBase shell commands. 171 * </p> 172 */ 173@CoreCoprocessor 174@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.CONFIG) 175public class AccessController implements MasterCoprocessor, RegionCoprocessor, 176 RegionServerCoprocessor, AccessControlService.Interface, MasterObserver, RegionObserver, 177 RegionServerObserver, EndpointObserver, BulkLoadObserver { 178 // TODO: encapsulate observer functions into separate class/sub-class. 179 180 private static final Logger LOG = LoggerFactory.getLogger(AccessController.class); 181 182 private static final Logger AUDITLOG = 183 LoggerFactory.getLogger("SecurityLogger." + AccessController.class.getName()); 184 private static final String CHECK_COVERING_PERM = "check_covering_perm"; 185 private static final String TAG_CHECK_PASSED = "tag_check_passed"; 186 private static final byte[] TRUE = Bytes.toBytes(true); 187 188 private AccessChecker accessChecker; 189 private ZKPermissionWatcher zkPermissionWatcher; 190 191 /** flags if we are running on a region of the _acl_ table */ 192 private boolean aclRegion = false; 193 194 /** 195 * defined only for Endpoint implementation, so it can have way to access region services 196 */ 197 private RegionCoprocessorEnvironment regionEnv; 198 199 /** Mapping of scanner instances to the user who created them */ 200 private Map<InternalScanner, String> scannerOwners = new MapMaker().weakKeys().makeMap(); 201 202 private Map<TableName, List<UserPermission>> tableAcls; 203 204 /** Provider for mapping principal names to Users */ 205 private UserProvider userProvider; 206 207 /** 208 * if we are active, usually false, only true if "hbase.security.authorization" has been set to 209 * true in site configuration 210 */ 211 private boolean authorizationEnabled; 212 213 /** if we are able to support cell ACLs */ 214 private boolean cellFeaturesEnabled; 215 216 /** if we should check EXEC permissions */ 217 private boolean shouldCheckExecPermission; 218 219 /** 220 * if we should terminate access checks early as soon as table or CF grants allow access; pre-0.98 221 * compatible behavior 222 */ 223 private boolean compatibleEarlyTermination; 224 225 /** if we have been successfully initialized */ 226 private volatile boolean initialized = false; 227 228 /** if the ACL table is available, only relevant in the master */ 229 private volatile boolean aclTabAvailable = false; 230 231 public static boolean isCellAuthorizationSupported(Configuration conf) { 232 return AccessChecker.isAuthorizationSupported(conf) 233 && (HFile.getFormatVersion(conf) >= HFile.MIN_FORMAT_VERSION_WITH_TAGS); 234 } 235 236 public Region getRegion() { 237 return regionEnv != null ? regionEnv.getRegion() : null; 238 } 239 240 public AuthManager getAuthManager() { 241 return accessChecker.getAuthManager(); 242 } 243 244 private void initialize(RegionCoprocessorEnvironment e) throws IOException { 245 final Region region = e.getRegion(); 246 Configuration conf = e.getConfiguration(); 247 Map<byte[], ListMultimap<String, UserPermission>> tables = PermissionStorage.loadAll(region); 248 // For each table, write out the table's permissions to the respective 249 // znode for that table. 250 for (Map.Entry<byte[], ListMultimap<String, UserPermission>> t : tables.entrySet()) { 251 byte[] entry = t.getKey(); 252 ListMultimap<String, UserPermission> perms = t.getValue(); 253 byte[] serialized = PermissionStorage.writePermissionsAsBytes(perms, conf); 254 zkPermissionWatcher.writeToZookeeper(entry, serialized); 255 } 256 initialized = true; 257 } 258 259 /** 260 * Writes all table ACLs for the tables in the given Map up into ZooKeeper znodes. This is called 261 * to synchronize ACL changes following {@code _acl_} table updates. 262 */ 263 private void updateACL(RegionCoprocessorEnvironment e, final Map<byte[], List<Cell>> familyMap) { 264 Set<byte[]> entries = new TreeSet<>(Bytes.BYTES_RAWCOMPARATOR); 265 for (Map.Entry<byte[], List<Cell>> f : familyMap.entrySet()) { 266 List<Cell> cells = f.getValue(); 267 for (Cell cell : cells) { 268 if (CellUtil.matchingFamily(cell, PermissionStorage.ACL_LIST_FAMILY)) { 269 entries.add(CellUtil.cloneRow(cell)); 270 } 271 } 272 } 273 Configuration conf = regionEnv.getConfiguration(); 274 byte[] currentEntry = null; 275 // TODO: Here we are already on the ACL region. (And it is single 276 // region) We can even just get the region from the env and do get 277 // directly. The short circuit connection would avoid the RPC overhead 278 // so no socket communication, req write/read .. But we have the PB 279 // to and fro conversion overhead. get req is converted to PB req 280 // and results are converted to PB results 1st and then to POJOs 281 // again. We could have avoided such at least in ACL table context.. 282 try (Table t = e.getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) { 283 for (byte[] entry : entries) { 284 currentEntry = entry; 285 ListMultimap<String, UserPermission> perms = 286 PermissionStorage.getPermissions(conf, entry, t, null, null, null, false); 287 byte[] serialized = PermissionStorage.writePermissionsAsBytes(perms, conf); 288 zkPermissionWatcher.writeToZookeeper(entry, serialized); 289 } 290 } catch (IOException ex) { 291 LOG.error("Failed updating permissions mirror for '" 292 + (currentEntry == null ? "null" : Bytes.toString(currentEntry)) + "'", ex); 293 } 294 } 295 296 /** 297 * Check the current user for authorization to perform a specific action against the given set of 298 * row data. 299 * @param opType the operation type 300 * @param user the user 301 * @param e the coprocessor environment 302 * @param families the map of column families to qualifiers present in the request 303 * @param actions the desired actions 304 * @return an authorization result 305 */ 306 private AuthResult permissionGranted(OpType opType, User user, RegionCoprocessorEnvironment e, 307 Map<byte[], ? extends Collection<?>> families, Action... actions) { 308 AuthResult result = null; 309 for (Action action : actions) { 310 result = accessChecker.permissionGranted(opType.toString(), user, action, 311 e.getRegion().getRegionInfo().getTable(), families); 312 if (!result.isAllowed()) { 313 return result; 314 } 315 } 316 return result; 317 } 318 319 public void requireAccess(ObserverContext<?> ctx, String request, TableName tableName, 320 Action... permissions) throws IOException { 321 accessChecker.requireAccess(getActiveUser(ctx), request, tableName, permissions); 322 } 323 324 public void requirePermission(ObserverContext<?> ctx, String request, Action perm) 325 throws IOException { 326 accessChecker.requirePermission(getActiveUser(ctx), request, null, perm); 327 } 328 329 public void requireGlobalPermission(ObserverContext<?> ctx, String request, Action perm, 330 TableName tableName, Map<byte[], ? extends Collection<byte[]>> familyMap) throws IOException { 331 accessChecker.requireGlobalPermission(getActiveUser(ctx), request, perm, tableName, familyMap, 332 null); 333 } 334 335 public void requireGlobalPermission(ObserverContext<?> ctx, String request, Action perm, 336 String namespace) throws IOException { 337 accessChecker.requireGlobalPermission(getActiveUser(ctx), request, perm, namespace); 338 } 339 340 public void requireNamespacePermission(ObserverContext<?> ctx, String request, String namespace, 341 Action... permissions) throws IOException { 342 accessChecker.requireNamespacePermission(getActiveUser(ctx), request, namespace, null, 343 permissions); 344 } 345 346 public void requireNamespacePermission(ObserverContext<?> ctx, String request, String namespace, 347 TableName tableName, Map<byte[], ? extends Collection<byte[]>> familyMap, Action... permissions) 348 throws IOException { 349 accessChecker.requireNamespacePermission(getActiveUser(ctx), request, namespace, tableName, 350 familyMap, permissions); 351 } 352 353 public void requirePermission(ObserverContext<?> ctx, String request, TableName tableName, 354 byte[] family, byte[] qualifier, Action... permissions) throws IOException { 355 accessChecker.requirePermission(getActiveUser(ctx), request, tableName, family, qualifier, null, 356 permissions); 357 } 358 359 public void requireTablePermission(ObserverContext<?> ctx, String request, TableName tableName, 360 byte[] family, byte[] qualifier, Action... permissions) throws IOException { 361 accessChecker.requireTablePermission(getActiveUser(ctx), request, tableName, family, qualifier, 362 permissions); 363 } 364 365 public void checkLockPermissions(ObserverContext<?> ctx, String namespace, TableName tableName, 366 RegionInfo[] regionInfos, String reason) throws IOException { 367 accessChecker.checkLockPermissions(getActiveUser(ctx), namespace, tableName, regionInfos, 368 reason); 369 } 370 371 /** 372 * Returns <code>true</code> if the current user is allowed the given action over at least one of 373 * the column qualifiers in the given column families. 374 */ 375 private boolean hasFamilyQualifierPermission(User user, Action perm, 376 RegionCoprocessorEnvironment env, Map<byte[], ? extends Collection<byte[]>> familyMap) 377 throws IOException { 378 RegionInfo hri = env.getRegion().getRegionInfo(); 379 TableName tableName = hri.getTable(); 380 381 if (user == null) { 382 return false; 383 } 384 385 if (familyMap != null && familyMap.size() > 0) { 386 // at least one family must be allowed 387 for (Map.Entry<byte[], ? extends Collection<byte[]>> family : familyMap.entrySet()) { 388 if (family.getValue() != null && !family.getValue().isEmpty()) { 389 for (byte[] qualifier : family.getValue()) { 390 if ( 391 getAuthManager().authorizeUserTable(user, tableName, family.getKey(), qualifier, perm) 392 ) { 393 return true; 394 } 395 } 396 } else { 397 if (getAuthManager().authorizeUserFamily(user, tableName, family.getKey(), perm)) { 398 return true; 399 } 400 } 401 } 402 } else if (LOG.isDebugEnabled()) { 403 LOG.debug("Empty family map passed for permission check"); 404 } 405 406 return false; 407 } 408 409 private enum OpType { 410 GET("get"), 411 EXISTS("exists"), 412 SCAN("scan"), 413 PUT("put"), 414 DELETE("delete"), 415 CHECK_AND_PUT("checkAndPut"), 416 CHECK_AND_DELETE("checkAndDelete"), 417 APPEND("append"), 418 INCREMENT("increment"); 419 420 private String type; 421 422 private OpType(String type) { 423 this.type = type; 424 } 425 426 @Override 427 public String toString() { 428 return type; 429 } 430 } 431 432 /** 433 * Determine if cell ACLs covered by the operation grant access. This is expensive. 434 * @return false if cell ACLs failed to grant access, true otherwise 435 */ 436 private boolean checkCoveringPermission(User user, OpType request, RegionCoprocessorEnvironment e, 437 byte[] row, Map<byte[], ? extends Collection<?>> familyMap, long opTs, Action... actions) 438 throws IOException { 439 if (!cellFeaturesEnabled) { 440 return false; 441 } 442 long cellGrants = 0; 443 long latestCellTs = 0; 444 Get get = new Get(row); 445 // Only in case of Put/Delete op, consider TS within cell (if set for individual cells). 446 // When every cell, within a Mutation, can be linked with diff TS we can not rely on only one 447 // version. We have to get every cell version and check its TS against the TS asked for in 448 // Mutation and skip those Cells which is outside this Mutation TS.In case of Put, we have to 449 // consider only one such passing cell. In case of Delete we have to consider all the cell 450 // versions under this passing version. When Delete Mutation contains columns which are a 451 // version delete just consider only one version for those column cells. 452 boolean considerCellTs = (request == OpType.PUT || request == OpType.DELETE); 453 if (considerCellTs) { 454 get.readAllVersions(); 455 } else { 456 get.readVersions(1); 457 } 458 boolean diffCellTsFromOpTs = false; 459 for (Map.Entry<byte[], ? extends Collection<?>> entry : familyMap.entrySet()) { 460 byte[] col = entry.getKey(); 461 // TODO: HBASE-7114 could possibly unify the collection type in family 462 // maps so we would not need to do this 463 if (entry.getValue() instanceof Set) { 464 Set<byte[]> set = (Set<byte[]>) entry.getValue(); 465 if (set == null || set.isEmpty()) { 466 get.addFamily(col); 467 } else { 468 for (byte[] qual : set) { 469 get.addColumn(col, qual); 470 } 471 } 472 } else if (entry.getValue() instanceof List) { 473 List<ExtendedCell> list = (List<ExtendedCell>) entry.getValue(); 474 if (list == null || list.isEmpty()) { 475 get.addFamily(col); 476 } else { 477 // In case of family delete, a Cell will be added into the list with Qualifier as null. 478 for (ExtendedCell cell : list) { 479 if ( 480 cell.getQualifierLength() == 0 && (cell.getTypeByte() == Type.DeleteFamily.getCode() 481 || cell.getTypeByte() == Type.DeleteFamilyVersion.getCode()) 482 ) { 483 get.addFamily(col); 484 } else { 485 get.addColumn(col, CellUtil.cloneQualifier(cell)); 486 } 487 if (considerCellTs) { 488 long cellTs = cell.getTimestamp(); 489 latestCellTs = Math.max(latestCellTs, cellTs); 490 diffCellTsFromOpTs = diffCellTsFromOpTs || (opTs != cellTs); 491 } 492 } 493 } 494 } else if (entry.getValue() == null) { 495 get.addFamily(col); 496 } else { 497 throw new RuntimeException( 498 "Unhandled collection type " + entry.getValue().getClass().getName()); 499 } 500 } 501 // We want to avoid looking into the future. So, if the cells of the 502 // operation specify a timestamp, or the operation itself specifies a 503 // timestamp, then we use the maximum ts found. Otherwise, we bound 504 // the Get to the current server time. We add 1 to the timerange since 505 // the upper bound of a timerange is exclusive yet we need to examine 506 // any cells found there inclusively. 507 long latestTs = Math.max(opTs, latestCellTs); 508 if (latestTs == 0 || latestTs == HConstants.LATEST_TIMESTAMP) { 509 latestTs = EnvironmentEdgeManager.currentTime(); 510 } 511 get.setTimeRange(0, latestTs + 1); 512 // In case of Put operation we set to read all versions. This was done to consider the case 513 // where columns are added with TS other than the Mutation TS. But normally this wont be the 514 // case with Put. There no need to get all versions but get latest version only. 515 if (!diffCellTsFromOpTs && request == OpType.PUT) { 516 get.readVersions(1); 517 } 518 if (LOG.isTraceEnabled()) { 519 LOG.trace("Scanning for cells with " + get); 520 } 521 // This Map is identical to familyMap. The key is a BR rather than byte[]. 522 // It will be easy to do gets over this new Map as we can create get keys over the Cell cf by 523 // new SimpleByteRange(cell.familyArray, cell.familyOffset, cell.familyLen) 524 Map<ByteRange, List<Cell>> familyMap1 = new HashMap<>(); 525 for (Entry<byte[], ? extends Collection<?>> entry : familyMap.entrySet()) { 526 if (entry.getValue() instanceof List) { 527 familyMap1.put(new SimpleMutableByteRange(entry.getKey()), (List<Cell>) entry.getValue()); 528 } 529 } 530 RegionScanner scanner = getRegion(e).getScanner(new Scan(get)); 531 List<Cell> cells = Lists.newArrayList(); 532 Cell prevCell = null; 533 ByteRange curFam = new SimpleMutableByteRange(); 534 boolean curColAllVersions = (request == OpType.DELETE); 535 long curColCheckTs = opTs; 536 boolean foundColumn = false; 537 try { 538 boolean more = false; 539 ScannerContext scannerContext = ScannerContext.newBuilder().setBatchLimit(1).build(); 540 541 do { 542 cells.clear(); 543 // scan with limit as 1 to hold down memory use on wide rows 544 more = scanner.next(cells, scannerContext); 545 for (Cell cell : cells) { 546 if (LOG.isTraceEnabled()) { 547 LOG.trace("Found cell " + cell); 548 } 549 boolean colChange = prevCell == null || !CellUtil.matchingColumn(prevCell, cell); 550 if (colChange) foundColumn = false; 551 prevCell = cell; 552 if (!curColAllVersions && foundColumn) { 553 continue; 554 } 555 if (colChange && considerCellTs) { 556 curFam.set(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength()); 557 List<Cell> cols = familyMap1.get(curFam); 558 for (Cell col : cols) { 559 // null/empty qualifier is used to denote a Family delete. The TS and delete type 560 // associated with this is applicable for all columns within the family. That is 561 // why the below (col.getQualifierLength() == 0) check. 562 if ( 563 (col.getQualifierLength() == 0 && request == OpType.DELETE) 564 || CellUtil.matchingQualifier(cell, col) 565 ) { 566 byte type = col.getTypeByte(); 567 if (considerCellTs) { 568 curColCheckTs = col.getTimestamp(); 569 } 570 // For a Delete op we pass allVersions as true. When a Delete Mutation contains 571 // a version delete for a column no need to check all the covering cells within 572 // that column. Check all versions when Type is DeleteColumn or DeleteFamily 573 // One version delete types are Delete/DeleteFamilyVersion 574 curColAllVersions = (KeyValue.Type.DeleteColumn.getCode() == type) 575 || (KeyValue.Type.DeleteFamily.getCode() == type); 576 break; 577 } 578 } 579 } 580 if (cell.getTimestamp() > curColCheckTs) { 581 // Just ignore this cell. This is not a covering cell. 582 continue; 583 } 584 foundColumn = true; 585 for (Action action : actions) { 586 // Are there permissions for this user for the cell? 587 if (!getAuthManager().authorizeCell(user, getTableName(e), cell, action)) { 588 // We can stop if the cell ACL denies access 589 return false; 590 } 591 } 592 cellGrants++; 593 } 594 } while (more); 595 } catch (AccessDeniedException ex) { 596 throw ex; 597 } catch (IOException ex) { 598 LOG.error("Exception while getting cells to calculate covering permission", ex); 599 } finally { 600 scanner.close(); 601 } 602 // We should not authorize unless we have found one or more cell ACLs that 603 // grant access. This code is used to check for additional permissions 604 // after no table or CF grants are found. 605 return cellGrants > 0; 606 } 607 608 private static void addCellPermissions(final byte[] perms, Map<byte[], List<Cell>> familyMap) { 609 // Iterate over the entries in the familyMap, replacing the cells therein 610 // with new cells including the ACL data 611 for (Map.Entry<byte[], List<Cell>> e : familyMap.entrySet()) { 612 List<Cell> newCells = Lists.newArrayList(); 613 for (Cell c : e.getValue()) { 614 assert c instanceof ExtendedCell; 615 ExtendedCell cell = (ExtendedCell) c; 616 // Prepend the supplied perms in a new ACL tag to an update list of tags for the cell 617 List<Tag> tags = new ArrayList<>(); 618 tags.add(new ArrayBackedTag(PermissionStorage.ACL_TAG_TYPE, perms)); 619 Iterator<Tag> tagIterator = PrivateCellUtil.tagsIterator(cell); 620 while (tagIterator.hasNext()) { 621 tags.add(tagIterator.next()); 622 } 623 newCells.add(PrivateCellUtil.createCell(cell, tags)); 624 } 625 // This is supposed to be safe, won't CME 626 e.setValue(newCells); 627 } 628 } 629 630 // Checks whether incoming cells contain any tag with type as ACL_TAG_TYPE. This tag 631 // type is reserved and should not be explicitly set by user. 632 private void checkForReservedTagPresence(User user, Mutation m) throws IOException { 633 // No need to check if we're not going to throw 634 if (!authorizationEnabled) { 635 m.setAttribute(TAG_CHECK_PASSED, TRUE); 636 return; 637 } 638 // Superusers are allowed to store cells unconditionally. 639 if (Superusers.isSuperUser(user)) { 640 m.setAttribute(TAG_CHECK_PASSED, TRUE); 641 return; 642 } 643 // We already checked (prePut vs preBatchMutation) 644 if (m.getAttribute(TAG_CHECK_PASSED) != null) { 645 return; 646 } 647 for (ExtendedCellScanner cellScanner = m.cellScanner(); cellScanner.advance();) { 648 Iterator<Tag> tagsItr = PrivateCellUtil.tagsIterator(cellScanner.current()); 649 while (tagsItr.hasNext()) { 650 if (tagsItr.next().getType() == PermissionStorage.ACL_TAG_TYPE) { 651 throw new AccessDeniedException("Mutation contains cell with reserved type tag"); 652 } 653 } 654 } 655 m.setAttribute(TAG_CHECK_PASSED, TRUE); 656 } 657 658 /* ---- MasterObserver implementation ---- */ 659 @Override 660 public void start(CoprocessorEnvironment env) throws IOException { 661 CompoundConfiguration conf = new CompoundConfiguration(); 662 conf.add(env.getConfiguration()); 663 664 authorizationEnabled = AccessChecker.isAuthorizationSupported(conf); 665 if (!authorizationEnabled) { 666 LOG.warn("AccessController has been loaded with authorization checks DISABLED!"); 667 } 668 669 shouldCheckExecPermission = conf.getBoolean(AccessControlConstants.EXEC_PERMISSION_CHECKS_KEY, 670 AccessControlConstants.DEFAULT_EXEC_PERMISSION_CHECKS); 671 672 cellFeaturesEnabled = (HFile.getFormatVersion(conf) >= HFile.MIN_FORMAT_VERSION_WITH_TAGS); 673 if (!cellFeaturesEnabled) { 674 LOG.info("A minimum HFile version of " + HFile.MIN_FORMAT_VERSION_WITH_TAGS 675 + " is required to persist cell ACLs. Consider setting " + HFile.FORMAT_VERSION_KEY 676 + " accordingly."); 677 } 678 679 if (env instanceof MasterCoprocessorEnvironment) { 680 // if running on HMaster 681 MasterCoprocessorEnvironment mEnv = (MasterCoprocessorEnvironment) env; 682 if (mEnv instanceof HasMasterServices) { 683 MasterServices masterServices = ((HasMasterServices) mEnv).getMasterServices(); 684 zkPermissionWatcher = masterServices.getZKPermissionWatcher(); 685 accessChecker = masterServices.getAccessChecker(); 686 } 687 } else if (env instanceof RegionServerCoprocessorEnvironment) { 688 RegionServerCoprocessorEnvironment rsEnv = (RegionServerCoprocessorEnvironment) env; 689 if (rsEnv instanceof HasRegionServerServices) { 690 RegionServerServices rsServices = 691 ((HasRegionServerServices) rsEnv).getRegionServerServices(); 692 zkPermissionWatcher = rsServices.getZKPermissionWatcher(); 693 accessChecker = rsServices.getAccessChecker(); 694 } 695 } else if (env instanceof RegionCoprocessorEnvironment) { 696 // if running at region 697 regionEnv = (RegionCoprocessorEnvironment) env; 698 conf.addBytesMap(regionEnv.getRegion().getTableDescriptor().getValues()); 699 compatibleEarlyTermination = conf.getBoolean(AccessControlConstants.CF_ATTRIBUTE_EARLY_OUT, 700 AccessControlConstants.DEFAULT_ATTRIBUTE_EARLY_OUT); 701 if (regionEnv instanceof HasRegionServerServices) { 702 RegionServerServices rsServices = 703 ((HasRegionServerServices) regionEnv).getRegionServerServices(); 704 zkPermissionWatcher = rsServices.getZKPermissionWatcher(); 705 accessChecker = rsServices.getAccessChecker(); 706 } 707 } 708 709 Preconditions.checkState(zkPermissionWatcher != null, "ZKPermissionWatcher is null"); 710 Preconditions.checkState(accessChecker != null, "AccessChecker is null"); 711 712 // set the user-provider. 713 this.userProvider = UserProvider.instantiate(env.getConfiguration()); 714 tableAcls = new MapMaker().weakValues().makeMap(); 715 } 716 717 @Override 718 public void stop(CoprocessorEnvironment env) { 719 } 720 721 /*********************************** Observer/Service Getters ***********************************/ 722 @Override 723 public Optional<RegionObserver> getRegionObserver() { 724 return Optional.of(this); 725 } 726 727 @Override 728 public Optional<MasterObserver> getMasterObserver() { 729 return Optional.of(this); 730 } 731 732 @Override 733 public Optional<EndpointObserver> getEndpointObserver() { 734 return Optional.of(this); 735 } 736 737 @Override 738 public Optional<BulkLoadObserver> getBulkLoadObserver() { 739 return Optional.of(this); 740 } 741 742 @Override 743 public Optional<RegionServerObserver> getRegionServerObserver() { 744 return Optional.of(this); 745 } 746 747 @Override 748 public Iterable<Service> getServices() { 749 return Collections 750 .singleton(AccessControlProtos.AccessControlService.newReflectiveService(this)); 751 } 752 753 /*********************************** Observer implementations ***********************************/ 754 755 @Override 756 public void preCreateTable(ObserverContext<MasterCoprocessorEnvironment> c, TableDescriptor desc, 757 RegionInfo[] regions) throws IOException { 758 Set<byte[]> families = desc.getColumnFamilyNames(); 759 Map<byte[], Set<byte[]>> familyMap = new TreeMap<>(Bytes.BYTES_COMPARATOR); 760 for (byte[] family : families) { 761 familyMap.put(family, null); 762 } 763 requireNamespacePermission(c, "createTable", desc.getTableName().getNamespaceAsString(), 764 desc.getTableName(), familyMap, Action.ADMIN, Action.CREATE); 765 } 766 767 @Override 768 public void postCompletedCreateTableAction(final ObserverContext<MasterCoprocessorEnvironment> c, 769 final TableDescriptor desc, final RegionInfo[] regions) throws IOException { 770 // When AC is used, it should be configured as the 1st CP. 771 // In Master, the table operations like create, are handled by a Thread pool but the max size 772 // for this pool is 1. So if multiple CPs create tables on startup, these creations will happen 773 // sequentially only. 774 // Related code in HMaster#startServiceThreads 775 // {code} 776 // // We depend on there being only one instance of this executor running 777 // // at a time. To do concurrency, would need fencing of enable/disable of 778 // // tables. 779 // this.service.startExecutorService(ExecutorType.MASTER_TABLE_OPERATIONS, 1); 780 // {code} 781 // In future if we change this pool to have more threads, then there is a chance for thread, 782 // creating acl table, getting delayed and by that time another table creation got over and 783 // this hook is getting called. In such a case, we will need a wait logic here which will 784 // wait till the acl table is created. 785 if (PermissionStorage.isAclTable(desc)) { 786 this.aclTabAvailable = true; 787 } else { 788 if (!aclTabAvailable) { 789 LOG.warn("Not adding owner permission for table " + desc.getTableName() + ". " 790 + PermissionStorage.ACL_TABLE_NAME + " is not yet created. " + getClass().getSimpleName() 791 + " should be configured as the first Coprocessor"); 792 } else { 793 String owner = getActiveUser(c).getShortName(); 794 final UserPermission userPermission = new UserPermission(owner, 795 Permission.newBuilder(desc.getTableName()).withActions(Action.values()).build()); 796 // switch to the real hbase master user for doing the RPC on the ACL table 797 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() { 798 @Override 799 public Void run() throws Exception { 800 try (Table table = 801 c.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) { 802 PermissionStorage.addUserPermission(c.getEnvironment().getConfiguration(), 803 userPermission, table); 804 } 805 return null; 806 } 807 }); 808 } 809 } 810 } 811 812 @Override 813 public void preDeleteTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) 814 throws IOException { 815 requirePermission(c, "deleteTable", tableName, null, null, Action.ADMIN, Action.CREATE); 816 } 817 818 @Override 819 public void postDeleteTable(ObserverContext<MasterCoprocessorEnvironment> c, 820 final TableName tableName) throws IOException { 821 final Configuration conf = c.getEnvironment().getConfiguration(); 822 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() { 823 @Override 824 public Void run() throws Exception { 825 try (Table table = 826 c.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) { 827 PermissionStorage.removeTablePermissions(conf, tableName, table); 828 } 829 return null; 830 } 831 }); 832 zkPermissionWatcher.deleteTableACLNode(tableName); 833 } 834 835 @Override 836 public void preTruncateTable(ObserverContext<MasterCoprocessorEnvironment> c, 837 final TableName tableName) throws IOException { 838 requirePermission(c, "truncateTable", tableName, null, null, Action.ADMIN, Action.CREATE); 839 840 final Configuration conf = c.getEnvironment().getConfiguration(); 841 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() { 842 @Override 843 public Void run() throws Exception { 844 List<UserPermission> acls = 845 PermissionStorage.getUserTablePermissions(conf, tableName, null, null, null, false); 846 if (acls != null) { 847 tableAcls.put(tableName, acls); 848 } 849 return null; 850 } 851 }); 852 } 853 854 @Override 855 public void postTruncateTable(ObserverContext<MasterCoprocessorEnvironment> ctx, 856 final TableName tableName) throws IOException { 857 final Configuration conf = ctx.getEnvironment().getConfiguration(); 858 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() { 859 @Override 860 public Void run() throws Exception { 861 List<UserPermission> perms = tableAcls.get(tableName); 862 if (perms != null) { 863 for (UserPermission perm : perms) { 864 try (Table table = 865 ctx.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) { 866 PermissionStorage.addUserPermission(conf, perm, table); 867 } 868 } 869 } 870 tableAcls.remove(tableName); 871 return null; 872 } 873 }); 874 } 875 876 @Override 877 public TableDescriptor preModifyTable(ObserverContext<MasterCoprocessorEnvironment> c, 878 TableName tableName, TableDescriptor currentDesc, TableDescriptor newDesc) throws IOException { 879 // TODO: potentially check if this is a add/modify/delete column operation 880 requirePermission(c, "modifyTable", tableName, null, null, Action.ADMIN, Action.CREATE); 881 return newDesc; 882 } 883 884 @Override 885 public String preModifyTableStoreFileTracker(ObserverContext<MasterCoprocessorEnvironment> c, 886 TableName tableName, String dstSFT) throws IOException { 887 requirePermission(c, "modifyTableStoreFileTracker", tableName, null, null, Action.ADMIN, 888 Action.CREATE); 889 return dstSFT; 890 } 891 892 @Override 893 public String preModifyColumnFamilyStoreFileTracker( 894 ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, byte[] family, 895 String dstSFT) throws IOException { 896 requirePermission(c, "modifyColumnFamilyStoreFileTracker", tableName, family, null, 897 Action.ADMIN, Action.CREATE); 898 return dstSFT; 899 } 900 901 @Override 902 public void postModifyTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName, 903 TableDescriptor oldDesc, TableDescriptor currentDesc) throws IOException { 904 final Configuration conf = c.getEnvironment().getConfiguration(); 905 // default the table owner to current user, if not specified. 906 final String owner = getActiveUser(c).getShortName(); 907 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() { 908 @Override 909 public Void run() throws Exception { 910 UserPermission userperm = new UserPermission(owner, 911 Permission.newBuilder(currentDesc.getTableName()).withActions(Action.values()).build()); 912 try (Table table = 913 c.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) { 914 PermissionStorage.addUserPermission(conf, userperm, table); 915 } 916 return null; 917 } 918 }); 919 } 920 921 @Override 922 public void preEnableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) 923 throws IOException { 924 requirePermission(c, "enableTable", tableName, null, null, Action.ADMIN, Action.CREATE); 925 } 926 927 @Override 928 public void preDisableTable(ObserverContext<MasterCoprocessorEnvironment> c, TableName tableName) 929 throws IOException { 930 if (Bytes.equals(tableName.getName(), PermissionStorage.ACL_GLOBAL_NAME)) { 931 // We have to unconditionally disallow disable of the ACL table when we are installed, 932 // even if not enforcing authorizations. We are still allowing grants and revocations, 933 // checking permissions and logging audit messages, etc. If the ACL table is not 934 // available we will fail random actions all over the place. 935 throw new AccessDeniedException("Not allowed to disable " + PermissionStorage.ACL_TABLE_NAME 936 + " table with AccessController installed"); 937 } 938 requirePermission(c, "disableTable", tableName, null, null, Action.ADMIN, Action.CREATE); 939 } 940 941 @Override 942 public void preAbortProcedure(ObserverContext<MasterCoprocessorEnvironment> ctx, 943 final long procId) throws IOException { 944 requirePermission(ctx, "abortProcedure", Action.ADMIN); 945 } 946 947 @Override 948 public void postAbortProcedure(ObserverContext<MasterCoprocessorEnvironment> ctx) 949 throws IOException { 950 // There is nothing to do at this time after the procedure abort request was sent. 951 } 952 953 @Override 954 public void preGetProcedures(ObserverContext<MasterCoprocessorEnvironment> ctx) 955 throws IOException { 956 requirePermission(ctx, "getProcedure", Action.ADMIN); 957 } 958 959 @Override 960 public void preGetLocks(ObserverContext<MasterCoprocessorEnvironment> ctx) throws IOException { 961 User user = getActiveUser(ctx); 962 accessChecker.requirePermission(user, "getLocks", null, Action.ADMIN); 963 } 964 965 @Override 966 public void preMove(ObserverContext<MasterCoprocessorEnvironment> c, RegionInfo region, 967 ServerName srcServer, ServerName destServer) throws IOException { 968 requirePermission(c, "move", region.getTable(), null, null, Action.ADMIN); 969 } 970 971 @Override 972 public void preAssign(ObserverContext<MasterCoprocessorEnvironment> c, RegionInfo regionInfo) 973 throws IOException { 974 requirePermission(c, "assign", regionInfo.getTable(), null, null, Action.ADMIN); 975 } 976 977 @Override 978 public void preUnassign(ObserverContext<MasterCoprocessorEnvironment> c, RegionInfo regionInfo) 979 throws IOException { 980 requirePermission(c, "unassign", regionInfo.getTable(), null, null, Action.ADMIN); 981 } 982 983 @Override 984 public void preRegionOffline(ObserverContext<MasterCoprocessorEnvironment> c, 985 RegionInfo regionInfo) throws IOException { 986 requirePermission(c, "regionOffline", regionInfo.getTable(), null, null, Action.ADMIN); 987 } 988 989 @Override 990 public void preSetSplitOrMergeEnabled(final ObserverContext<MasterCoprocessorEnvironment> ctx, 991 final boolean newValue, final MasterSwitchType switchType) throws IOException { 992 requirePermission(ctx, "setSplitOrMergeEnabled", Action.ADMIN); 993 } 994 995 @Override 996 public void preBalance(ObserverContext<MasterCoprocessorEnvironment> c, BalanceRequest request) 997 throws IOException { 998 requirePermission(c, "balance", Action.ADMIN); 999 } 1000 1001 @Override 1002 public void preBalanceSwitch(ObserverContext<MasterCoprocessorEnvironment> c, boolean newValue) 1003 throws IOException { 1004 requirePermission(c, "balanceSwitch", Action.ADMIN); 1005 } 1006 1007 @Override 1008 public void preShutdown(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException { 1009 requirePermission(c, "shutdown", Action.ADMIN); 1010 } 1011 1012 @Override 1013 public void preStopMaster(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException { 1014 requirePermission(c, "stopMaster", Action.ADMIN); 1015 } 1016 1017 @Override 1018 public void postStartMaster(ObserverContext<MasterCoprocessorEnvironment> ctx) 1019 throws IOException { 1020 try (Admin admin = ctx.getEnvironment().getConnection().getAdmin()) { 1021 if (!admin.tableExists(PermissionStorage.ACL_TABLE_NAME)) { 1022 createACLTable(admin); 1023 } else { 1024 this.aclTabAvailable = true; 1025 } 1026 } 1027 } 1028 1029 /** 1030 * Create the ACL table 1031 */ 1032 private static void createACLTable(Admin admin) throws IOException { 1033 /** Table descriptor for ACL table */ 1034 ColumnFamilyDescriptor cfd = 1035 ColumnFamilyDescriptorBuilder.newBuilder(PermissionStorage.ACL_LIST_FAMILY).setMaxVersions(1) 1036 .setInMemory(true).setBlockCacheEnabled(true).setBlocksize(8 * 1024) 1037 .setBloomFilterType(BloomType.NONE).setScope(HConstants.REPLICATION_SCOPE_LOCAL).build(); 1038 TableDescriptor td = TableDescriptorBuilder.newBuilder(PermissionStorage.ACL_TABLE_NAME) 1039 .setColumnFamily(cfd).build(); 1040 admin.createTable(td); 1041 } 1042 1043 @Override 1044 public void preSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx, 1045 final SnapshotDescription snapshot, final TableDescriptor hTableDescriptor) throws IOException { 1046 // Move this ACL check to SnapshotManager#checkPermissions as part of AC deprecation. 1047 requirePermission(ctx, "snapshot " + snapshot.getName(), hTableDescriptor.getTableName(), null, 1048 null, Permission.Action.ADMIN); 1049 } 1050 1051 @Override 1052 public void preListSnapshot(ObserverContext<MasterCoprocessorEnvironment> ctx, 1053 final SnapshotDescription snapshot) throws IOException { 1054 User user = getActiveUser(ctx); 1055 if (SnapshotDescriptionUtils.isSnapshotOwner(snapshot, user)) { 1056 // list it, if user is the owner of snapshot 1057 AuthResult result = AuthResult.allow("listSnapshot " + snapshot.getName(), 1058 "Snapshot owner check allowed", user, null, null, null); 1059 AccessChecker.logResult(result); 1060 } else { 1061 accessChecker.requirePermission(user, "listSnapshot " + snapshot.getName(), null, 1062 Action.ADMIN); 1063 } 1064 } 1065 1066 @Override 1067 public void preCloneSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx, 1068 final SnapshotDescription snapshot, final TableDescriptor hTableDescriptor) throws IOException { 1069 User user = getActiveUser(ctx); 1070 if ( 1071 SnapshotDescriptionUtils.isSnapshotOwner(snapshot, user) 1072 && hTableDescriptor.getTableName().getNameAsString().equals(snapshot.getTableNameAsString()) 1073 ) { 1074 // Snapshot owner is allowed to create a table with the same name as the snapshot he took 1075 AuthResult result = AuthResult.allow("cloneSnapshot " + snapshot.getName(), 1076 "Snapshot owner check allowed", user, null, hTableDescriptor.getTableName(), null); 1077 AccessChecker.logResult(result); 1078 } else if (SnapshotDescriptionUtils.isSnapshotOwner(snapshot, user)) { 1079 requireNamespacePermission(ctx, "cloneSnapshot", 1080 hTableDescriptor.getTableName().getNamespaceAsString(), Action.ADMIN); 1081 } else { 1082 accessChecker.requirePermission(user, "cloneSnapshot " + snapshot.getName(), null, 1083 Action.ADMIN); 1084 } 1085 } 1086 1087 @Override 1088 public void preRestoreSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx, 1089 final SnapshotDescription snapshot, final TableDescriptor hTableDescriptor) throws IOException { 1090 User user = getActiveUser(ctx); 1091 if (SnapshotDescriptionUtils.isSnapshotOwner(snapshot, user)) { 1092 accessChecker.requirePermission(user, "restoreSnapshot " + snapshot.getName(), 1093 hTableDescriptor.getTableName(), null, null, null, Permission.Action.ADMIN); 1094 } else { 1095 accessChecker.requirePermission(user, "restoreSnapshot " + snapshot.getName(), null, 1096 Action.ADMIN); 1097 } 1098 } 1099 1100 @Override 1101 public void preDeleteSnapshot(final ObserverContext<MasterCoprocessorEnvironment> ctx, 1102 final SnapshotDescription snapshot) throws IOException { 1103 User user = getActiveUser(ctx); 1104 if (SnapshotDescriptionUtils.isSnapshotOwner(snapshot, user)) { 1105 // Snapshot owner is allowed to delete the snapshot 1106 AuthResult result = AuthResult.allow("deleteSnapshot " + snapshot.getName(), 1107 "Snapshot owner check allowed", user, null, null, null); 1108 AccessChecker.logResult(result); 1109 } else { 1110 accessChecker.requirePermission(user, "deleteSnapshot " + snapshot.getName(), null, 1111 Action.ADMIN); 1112 } 1113 } 1114 1115 @Override 1116 public void preCreateNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, 1117 NamespaceDescriptor ns) throws IOException { 1118 requireGlobalPermission(ctx, "createNamespace", Action.ADMIN, ns.getName()); 1119 } 1120 1121 @Override 1122 public void preDeleteNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, 1123 String namespace) throws IOException { 1124 requireGlobalPermission(ctx, "deleteNamespace", Action.ADMIN, namespace); 1125 } 1126 1127 @Override 1128 public void postDeleteNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, 1129 final String namespace) throws IOException { 1130 final Configuration conf = ctx.getEnvironment().getConfiguration(); 1131 User.runAsLoginUser(new PrivilegedExceptionAction<Void>() { 1132 @Override 1133 public Void run() throws Exception { 1134 try (Table table = 1135 ctx.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) { 1136 PermissionStorage.removeNamespacePermissions(conf, namespace, table); 1137 } 1138 return null; 1139 } 1140 }); 1141 zkPermissionWatcher.deleteNamespaceACLNode(namespace); 1142 LOG.info(namespace + " entry deleted in " + PermissionStorage.ACL_TABLE_NAME + " table."); 1143 } 1144 1145 @Override 1146 public void preModifyNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, 1147 NamespaceDescriptor currentNsDesc, NamespaceDescriptor newNsDesc) throws IOException { 1148 // We require only global permission so that 1149 // a user with NS admin cannot altering namespace configurations. i.e. namespace quota 1150 requireGlobalPermission(ctx, "modifyNamespace", Action.ADMIN, newNsDesc.getName()); 1151 } 1152 1153 @Override 1154 public void preGetNamespaceDescriptor(ObserverContext<MasterCoprocessorEnvironment> ctx, 1155 String namespace) throws IOException { 1156 requireNamespacePermission(ctx, "getNamespaceDescriptor", namespace, Action.ADMIN); 1157 } 1158 1159 @Override 1160 public void postListNamespaces(ObserverContext<MasterCoprocessorEnvironment> ctx, 1161 List<String> namespaces) throws IOException { 1162 /* always allow namespace listing */ 1163 } 1164 1165 @Override 1166 public void postListNamespaceDescriptors(ObserverContext<MasterCoprocessorEnvironment> ctx, 1167 List<NamespaceDescriptor> descriptors) throws IOException { 1168 // Retains only those which passes authorization checks, as the checks weren't done as part 1169 // of preGetTableDescriptors. 1170 Iterator<NamespaceDescriptor> itr = descriptors.iterator(); 1171 User user = getActiveUser(ctx); 1172 while (itr.hasNext()) { 1173 NamespaceDescriptor desc = itr.next(); 1174 try { 1175 accessChecker.requireNamespacePermission(user, "listNamespaces", desc.getName(), null, 1176 Action.ADMIN); 1177 } catch (AccessDeniedException e) { 1178 itr.remove(); 1179 } 1180 } 1181 } 1182 1183 @Override 1184 public void preTableFlush(final ObserverContext<MasterCoprocessorEnvironment> ctx, 1185 final TableName tableName) throws IOException { 1186 // Move this ACL check to MasterFlushTableProcedureManager#checkPermissions as part of AC 1187 // deprecation. 1188 requirePermission(ctx, "flushTable", tableName, null, null, Action.ADMIN, Action.CREATE); 1189 } 1190 1191 @Override 1192 public void preSplitRegion(final ObserverContext<MasterCoprocessorEnvironment> ctx, 1193 final TableName tableName, final byte[] splitRow) throws IOException { 1194 requirePermission(ctx, "split", tableName, null, null, Action.ADMIN); 1195 } 1196 1197 @Override 1198 public void preClearDeadServers(ObserverContext<MasterCoprocessorEnvironment> ctx) 1199 throws IOException { 1200 requirePermission(ctx, "clearDeadServers", Action.ADMIN); 1201 } 1202 1203 @Override 1204 public void preDecommissionRegionServers(ObserverContext<MasterCoprocessorEnvironment> ctx, 1205 List<ServerName> servers, boolean offload) throws IOException { 1206 requirePermission(ctx, "decommissionRegionServers", Action.ADMIN); 1207 } 1208 1209 @Override 1210 public void preListDecommissionedRegionServers(ObserverContext<MasterCoprocessorEnvironment> ctx) 1211 throws IOException { 1212 requirePermission(ctx, "listDecommissionedRegionServers", Action.READ); 1213 } 1214 1215 @Override 1216 public void preRecommissionRegionServer(ObserverContext<MasterCoprocessorEnvironment> ctx, 1217 ServerName server, List<byte[]> encodedRegionNames) throws IOException { 1218 requirePermission(ctx, "recommissionRegionServers", Action.ADMIN); 1219 } 1220 1221 /* ---- RegionObserver implementation ---- */ 1222 1223 @Override 1224 public void preOpen(ObserverContext<RegionCoprocessorEnvironment> c) throws IOException { 1225 RegionCoprocessorEnvironment env = c.getEnvironment(); 1226 final Region region = env.getRegion(); 1227 if (region == null) { 1228 LOG.error("NULL region from RegionCoprocessorEnvironment in preOpen()"); 1229 } else { 1230 RegionInfo regionInfo = region.getRegionInfo(); 1231 if (regionInfo.getTable().isSystemTable()) { 1232 checkSystemOrSuperUser(getActiveUser(c)); 1233 } else { 1234 requirePermission(c, "preOpen", Action.ADMIN); 1235 } 1236 } 1237 } 1238 1239 @Override 1240 public void postOpen(ObserverContext<RegionCoprocessorEnvironment> c) { 1241 RegionCoprocessorEnvironment env = c.getEnvironment(); 1242 final Region region = env.getRegion(); 1243 if (region == null) { 1244 LOG.error("NULL region from RegionCoprocessorEnvironment in postOpen()"); 1245 return; 1246 } 1247 if (PermissionStorage.isAclRegion(region)) { 1248 aclRegion = true; 1249 try { 1250 initialize(env); 1251 } catch (IOException ex) { 1252 // if we can't obtain permissions, it's better to fail 1253 // than perform checks incorrectly 1254 throw new RuntimeException("Failed to initialize permissions cache", ex); 1255 } 1256 } else { 1257 initialized = true; 1258 } 1259 } 1260 1261 @Override 1262 public void preFlush(ObserverContext<RegionCoprocessorEnvironment> c, 1263 FlushLifeCycleTracker tracker) throws IOException { 1264 requirePermission(c, "flush", getTableName(c.getEnvironment()), null, null, Action.ADMIN, 1265 Action.CREATE); 1266 } 1267 1268 @Override 1269 public InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment> c, Store store, 1270 InternalScanner scanner, ScanType scanType, CompactionLifeCycleTracker tracker, 1271 CompactionRequest request) throws IOException { 1272 requirePermission(c, "compact", getTableName(c.getEnvironment()), null, null, Action.ADMIN, 1273 Action.CREATE); 1274 return scanner; 1275 } 1276 1277 private void internalPreRead(final ObserverContext<RegionCoprocessorEnvironment> c, 1278 final Query query, OpType opType) throws IOException { 1279 Filter filter = query.getFilter(); 1280 // Don't wrap an AccessControlFilter 1281 if (filter != null && filter instanceof AccessControlFilter) { 1282 return; 1283 } 1284 User user = getActiveUser(c); 1285 RegionCoprocessorEnvironment env = c.getEnvironment(); 1286 Map<byte[], ? extends Collection<byte[]>> families = null; 1287 switch (opType) { 1288 case GET: 1289 case EXISTS: 1290 families = ((Get) query).getFamilyMap(); 1291 break; 1292 case SCAN: 1293 families = ((Scan) query).getFamilyMap(); 1294 break; 1295 default: 1296 throw new RuntimeException("Unhandled operation " + opType); 1297 } 1298 AuthResult authResult = permissionGranted(opType, user, env, families, Action.READ); 1299 Region region = getRegion(env); 1300 TableName table = getTableName(region); 1301 Map<ByteRange, Integer> cfVsMaxVersions = Maps.newHashMap(); 1302 for (ColumnFamilyDescriptor hcd : region.getTableDescriptor().getColumnFamilies()) { 1303 cfVsMaxVersions.put(new SimpleMutableByteRange(hcd.getName()), hcd.getMaxVersions()); 1304 } 1305 if (!authResult.isAllowed()) { 1306 if (!cellFeaturesEnabled || compatibleEarlyTermination) { 1307 // Old behavior: Scan with only qualifier checks if we have partial 1308 // permission. Backwards compatible behavior is to throw an 1309 // AccessDeniedException immediately if there are no grants for table 1310 // or CF or CF+qual. Only proceed with an injected filter if there are 1311 // grants for qualifiers. Otherwise we will fall through below and log 1312 // the result and throw an ADE. We may end up checking qualifier 1313 // grants three times (permissionGranted above, here, and in the 1314 // filter) but that's the price of backwards compatibility. 1315 if (hasFamilyQualifierPermission(user, Action.READ, env, families)) { 1316 authResult.setAllowed(true); 1317 authResult.setReason("Access allowed with filter"); 1318 // Only wrap the filter if we are enforcing authorizations 1319 if (authorizationEnabled) { 1320 Filter ourFilter = new AccessControlFilter(getAuthManager(), user, table, 1321 AccessControlFilter.Strategy.CHECK_TABLE_AND_CF_ONLY, cfVsMaxVersions); 1322 // wrap any existing filter 1323 if (filter != null) { 1324 ourFilter = new FilterList(FilterList.Operator.MUST_PASS_ALL, 1325 Lists.newArrayList(ourFilter, filter)); 1326 } 1327 switch (opType) { 1328 case GET: 1329 case EXISTS: 1330 ((Get) query).setFilter(ourFilter); 1331 break; 1332 case SCAN: 1333 ((Scan) query).setFilter(ourFilter); 1334 break; 1335 default: 1336 throw new RuntimeException("Unhandled operation " + opType); 1337 } 1338 } 1339 } 1340 } else { 1341 // New behavior: Any access we might be granted is more fine-grained 1342 // than whole table or CF. Simply inject a filter and return what is 1343 // allowed. We will not throw an AccessDeniedException. This is a 1344 // behavioral change since 0.96. 1345 authResult.setAllowed(true); 1346 authResult.setReason("Access allowed with filter"); 1347 // Only wrap the filter if we are enforcing authorizations 1348 if (authorizationEnabled) { 1349 Filter ourFilter = new AccessControlFilter(getAuthManager(), user, table, 1350 AccessControlFilter.Strategy.CHECK_CELL_DEFAULT, cfVsMaxVersions); 1351 // wrap any existing filter 1352 if (filter != null) { 1353 ourFilter = new FilterList(FilterList.Operator.MUST_PASS_ALL, 1354 Lists.newArrayList(ourFilter, filter)); 1355 } 1356 switch (opType) { 1357 case GET: 1358 case EXISTS: 1359 ((Get) query).setFilter(ourFilter); 1360 break; 1361 case SCAN: 1362 ((Scan) query).setFilter(ourFilter); 1363 break; 1364 default: 1365 throw new RuntimeException("Unhandled operation " + opType); 1366 } 1367 } 1368 } 1369 } 1370 1371 AccessChecker.logResult(authResult); 1372 if (authorizationEnabled && !authResult.isAllowed()) { 1373 throw new AccessDeniedException("Insufficient permissions for user '" 1374 + (user != null ? user.getShortName() : "null") + "' (table=" + table + ", action=READ)"); 1375 } 1376 } 1377 1378 @Override 1379 public void preGetOp(final ObserverContext<RegionCoprocessorEnvironment> c, final Get get, 1380 final List<Cell> result) throws IOException { 1381 internalPreRead(c, get, OpType.GET); 1382 } 1383 1384 @Override 1385 public boolean preExists(final ObserverContext<RegionCoprocessorEnvironment> c, final Get get, 1386 final boolean exists) throws IOException { 1387 internalPreRead(c, get, OpType.EXISTS); 1388 return exists; 1389 } 1390 1391 @Override 1392 public void prePut(final ObserverContext<RegionCoprocessorEnvironment> c, final Put put, 1393 final WALEdit edit, final Durability durability) throws IOException { 1394 User user = getActiveUser(c); 1395 checkForReservedTagPresence(user, put); 1396 1397 // Require WRITE permission to the table, CF, or top visible value, if any. 1398 // NOTE: We don't need to check the permissions for any earlier Puts 1399 // because we treat the ACLs in each Put as timestamped like any other 1400 // HBase value. A new ACL in a new Put applies to that Put. It doesn't 1401 // change the ACL of any previous Put. This allows simple evolution of 1402 // security policy over time without requiring expensive updates. 1403 RegionCoprocessorEnvironment env = c.getEnvironment(); 1404 Map<byte[], ? extends Collection<Cell>> families = put.getFamilyCellMap(); 1405 AuthResult authResult = permissionGranted(OpType.PUT, user, env, families, Action.WRITE); 1406 AccessChecker.logResult(authResult); 1407 if (!authResult.isAllowed()) { 1408 if (cellFeaturesEnabled && !compatibleEarlyTermination) { 1409 put.setAttribute(CHECK_COVERING_PERM, TRUE); 1410 } else if (authorizationEnabled) { 1411 throw new AccessDeniedException("Insufficient permissions " + authResult.toContextString()); 1412 } 1413 } 1414 1415 // Add cell ACLs from the operation to the cells themselves 1416 byte[] bytes = put.getAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL); 1417 if (bytes != null) { 1418 if (cellFeaturesEnabled) { 1419 addCellPermissions(bytes, put.getFamilyCellMap()); 1420 } else { 1421 throw new DoNotRetryIOException("Cell ACLs cannot be persisted"); 1422 } 1423 } 1424 } 1425 1426 @Override 1427 public void postPut(final ObserverContext<RegionCoprocessorEnvironment> c, final Put put, 1428 final WALEdit edit, final Durability durability) { 1429 if (aclRegion) { 1430 updateACL(c.getEnvironment(), put.getFamilyCellMap()); 1431 } 1432 } 1433 1434 @Override 1435 public void preDelete(final ObserverContext<RegionCoprocessorEnvironment> c, final Delete delete, 1436 final WALEdit edit, final Durability durability) throws IOException { 1437 // An ACL on a delete is useless, we shouldn't allow it 1438 if (delete.getAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL) != null) { 1439 throw new DoNotRetryIOException("ACL on delete has no effect: " + delete.toString()); 1440 } 1441 // Require WRITE permissions on all cells covered by the delete. Unlike 1442 // for Puts we need to check all visible prior versions, because a major 1443 // compaction could remove them. If the user doesn't have permission to 1444 // overwrite any of the visible versions ('visible' defined as not covered 1445 // by a tombstone already) then we have to disallow this operation. 1446 RegionCoprocessorEnvironment env = c.getEnvironment(); 1447 Map<byte[], ? extends Collection<Cell>> families = delete.getFamilyCellMap(); 1448 User user = getActiveUser(c); 1449 AuthResult authResult = permissionGranted(OpType.DELETE, user, env, families, Action.WRITE); 1450 AccessChecker.logResult(authResult); 1451 if (!authResult.isAllowed()) { 1452 if (cellFeaturesEnabled && !compatibleEarlyTermination) { 1453 delete.setAttribute(CHECK_COVERING_PERM, TRUE); 1454 } else if (authorizationEnabled) { 1455 throw new AccessDeniedException("Insufficient permissions " + authResult.toContextString()); 1456 } 1457 } 1458 } 1459 1460 @Override 1461 public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c, 1462 MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException { 1463 if (cellFeaturesEnabled && !compatibleEarlyTermination) { 1464 TableName table = c.getEnvironment().getRegion().getRegionInfo().getTable(); 1465 User user = getActiveUser(c); 1466 for (int i = 0; i < miniBatchOp.size(); i++) { 1467 Mutation m = miniBatchOp.getOperation(i); 1468 if (m.getAttribute(CHECK_COVERING_PERM) != null) { 1469 // We have a failure with table, cf and q perm checks and now giving a chance for cell 1470 // perm check 1471 OpType opType; 1472 long timestamp; 1473 if (m instanceof Put) { 1474 checkForReservedTagPresence(user, m); 1475 opType = OpType.PUT; 1476 timestamp = m.getTimestamp(); 1477 } else if (m instanceof Delete) { 1478 opType = OpType.DELETE; 1479 timestamp = m.getTimestamp(); 1480 } else if (m instanceof Increment) { 1481 opType = OpType.INCREMENT; 1482 timestamp = ((Increment) m).getTimeRange().getMax(); 1483 } else if (m instanceof Append) { 1484 opType = OpType.APPEND; 1485 timestamp = ((Append) m).getTimeRange().getMax(); 1486 } else { 1487 // If the operation type is not Put/Delete/Increment/Append, do nothing 1488 continue; 1489 } 1490 AuthResult authResult = null; 1491 if ( 1492 checkCoveringPermission(user, opType, c.getEnvironment(), m.getRow(), 1493 m.getFamilyCellMap(), timestamp, Action.WRITE) 1494 ) { 1495 authResult = AuthResult.allow(opType.toString(), "Covering cell set", user, 1496 Action.WRITE, table, m.getFamilyCellMap()); 1497 } else { 1498 authResult = AuthResult.deny(opType.toString(), "Covering cell set", user, Action.WRITE, 1499 table, m.getFamilyCellMap()); 1500 } 1501 AccessChecker.logResult(authResult); 1502 if (authorizationEnabled && !authResult.isAllowed()) { 1503 throw new AccessDeniedException( 1504 "Insufficient permissions " + authResult.toContextString()); 1505 } 1506 } 1507 } 1508 } 1509 } 1510 1511 @Override 1512 public void postDelete(final ObserverContext<RegionCoprocessorEnvironment> c, final Delete delete, 1513 final WALEdit edit, final Durability durability) throws IOException { 1514 if (aclRegion) { 1515 updateACL(c.getEnvironment(), delete.getFamilyCellMap()); 1516 } 1517 } 1518 1519 @Override 1520 public boolean preCheckAndPut(final ObserverContext<RegionCoprocessorEnvironment> c, 1521 final byte[] row, final byte[] family, final byte[] qualifier, final CompareOperator op, 1522 final ByteArrayComparable comparator, final Put put, final boolean result) throws IOException { 1523 User user = getActiveUser(c); 1524 checkForReservedTagPresence(user, put); 1525 1526 // Require READ and WRITE permissions on the table, CF, and KV to update 1527 RegionCoprocessorEnvironment env = c.getEnvironment(); 1528 Map<byte[], ? extends Collection<byte[]>> families = makeFamilyMap(family, qualifier); 1529 AuthResult authResult = 1530 permissionGranted(OpType.CHECK_AND_PUT, user, env, families, Action.READ, Action.WRITE); 1531 AccessChecker.logResult(authResult); 1532 if (!authResult.isAllowed()) { 1533 if (cellFeaturesEnabled && !compatibleEarlyTermination) { 1534 put.setAttribute(CHECK_COVERING_PERM, TRUE); 1535 } else if (authorizationEnabled) { 1536 throw new AccessDeniedException("Insufficient permissions " + authResult.toContextString()); 1537 } 1538 } 1539 1540 byte[] bytes = put.getAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL); 1541 if (bytes != null) { 1542 if (cellFeaturesEnabled) { 1543 addCellPermissions(bytes, put.getFamilyCellMap()); 1544 } else { 1545 throw new DoNotRetryIOException("Cell ACLs cannot be persisted"); 1546 } 1547 } 1548 return result; 1549 } 1550 1551 @Override 1552 public boolean preCheckAndPutAfterRowLock(final ObserverContext<RegionCoprocessorEnvironment> c, 1553 final byte[] row, final byte[] family, final byte[] qualifier, final CompareOperator opp, 1554 final ByteArrayComparable comparator, final Put put, final boolean result) throws IOException { 1555 if (put.getAttribute(CHECK_COVERING_PERM) != null) { 1556 // We had failure with table, cf and q perm checks and now giving a chance for cell 1557 // perm check 1558 TableName table = c.getEnvironment().getRegion().getRegionInfo().getTable(); 1559 Map<byte[], ? extends Collection<byte[]>> families = makeFamilyMap(family, qualifier); 1560 AuthResult authResult = null; 1561 User user = getActiveUser(c); 1562 if ( 1563 checkCoveringPermission(user, OpType.CHECK_AND_PUT, c.getEnvironment(), row, families, 1564 HConstants.LATEST_TIMESTAMP, Action.READ) 1565 ) { 1566 authResult = AuthResult.allow(OpType.CHECK_AND_PUT.toString(), "Covering cell set", user, 1567 Action.READ, table, families); 1568 } else { 1569 authResult = AuthResult.deny(OpType.CHECK_AND_PUT.toString(), "Covering cell set", user, 1570 Action.READ, table, families); 1571 } 1572 AccessChecker.logResult(authResult); 1573 if (authorizationEnabled && !authResult.isAllowed()) { 1574 throw new AccessDeniedException("Insufficient permissions " + authResult.toContextString()); 1575 } 1576 } 1577 return result; 1578 } 1579 1580 @Override 1581 public boolean preCheckAndDelete(final ObserverContext<RegionCoprocessorEnvironment> c, 1582 final byte[] row, final byte[] family, final byte[] qualifier, final CompareOperator op, 1583 final ByteArrayComparable comparator, final Delete delete, final boolean result) 1584 throws IOException { 1585 // An ACL on a delete is useless, we shouldn't allow it 1586 if (delete.getAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL) != null) { 1587 throw new DoNotRetryIOException("ACL on checkAndDelete has no effect: " + delete.toString()); 1588 } 1589 // Require READ and WRITE permissions on the table, CF, and the KV covered 1590 // by the delete 1591 RegionCoprocessorEnvironment env = c.getEnvironment(); 1592 Map<byte[], ? extends Collection<byte[]>> families = makeFamilyMap(family, qualifier); 1593 User user = getActiveUser(c); 1594 AuthResult authResult = 1595 permissionGranted(OpType.CHECK_AND_DELETE, user, env, families, Action.READ, Action.WRITE); 1596 AccessChecker.logResult(authResult); 1597 if (!authResult.isAllowed()) { 1598 if (cellFeaturesEnabled && !compatibleEarlyTermination) { 1599 delete.setAttribute(CHECK_COVERING_PERM, TRUE); 1600 } else if (authorizationEnabled) { 1601 throw new AccessDeniedException("Insufficient permissions " + authResult.toContextString()); 1602 } 1603 } 1604 return result; 1605 } 1606 1607 @Override 1608 public boolean preCheckAndDeleteAfterRowLock( 1609 final ObserverContext<RegionCoprocessorEnvironment> c, final byte[] row, final byte[] family, 1610 final byte[] qualifier, final CompareOperator op, final ByteArrayComparable comparator, 1611 final Delete delete, final boolean result) throws IOException { 1612 if (delete.getAttribute(CHECK_COVERING_PERM) != null) { 1613 // We had failure with table, cf and q perm checks and now giving a chance for cell 1614 // perm check 1615 TableName table = c.getEnvironment().getRegion().getRegionInfo().getTable(); 1616 Map<byte[], ? extends Collection<byte[]>> families = makeFamilyMap(family, qualifier); 1617 AuthResult authResult = null; 1618 User user = getActiveUser(c); 1619 if ( 1620 checkCoveringPermission(user, OpType.CHECK_AND_DELETE, c.getEnvironment(), row, families, 1621 HConstants.LATEST_TIMESTAMP, Action.READ) 1622 ) { 1623 authResult = AuthResult.allow(OpType.CHECK_AND_DELETE.toString(), "Covering cell set", user, 1624 Action.READ, table, families); 1625 } else { 1626 authResult = AuthResult.deny(OpType.CHECK_AND_DELETE.toString(), "Covering cell set", user, 1627 Action.READ, table, families); 1628 } 1629 AccessChecker.logResult(authResult); 1630 if (authorizationEnabled && !authResult.isAllowed()) { 1631 throw new AccessDeniedException("Insufficient permissions " + authResult.toContextString()); 1632 } 1633 } 1634 return result; 1635 } 1636 1637 @Override 1638 public Result preAppend(ObserverContext<RegionCoprocessorEnvironment> c, Append append) 1639 throws IOException { 1640 User user = getActiveUser(c); 1641 checkForReservedTagPresence(user, append); 1642 1643 // Require WRITE permission to the table, CF, and the KV to be appended 1644 RegionCoprocessorEnvironment env = c.getEnvironment(); 1645 Map<byte[], ? extends Collection<Cell>> families = append.getFamilyCellMap(); 1646 AuthResult authResult = permissionGranted(OpType.APPEND, user, env, families, Action.WRITE); 1647 AccessChecker.logResult(authResult); 1648 if (!authResult.isAllowed()) { 1649 if (cellFeaturesEnabled && !compatibleEarlyTermination) { 1650 append.setAttribute(CHECK_COVERING_PERM, TRUE); 1651 } else if (authorizationEnabled) { 1652 throw new AccessDeniedException("Insufficient permissions " + authResult.toContextString()); 1653 } 1654 } 1655 1656 byte[] bytes = append.getAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL); 1657 if (bytes != null) { 1658 if (cellFeaturesEnabled) { 1659 addCellPermissions(bytes, append.getFamilyCellMap()); 1660 } else { 1661 throw new DoNotRetryIOException("Cell ACLs cannot be persisted"); 1662 } 1663 } 1664 1665 return null; 1666 } 1667 1668 @Override 1669 public Result preIncrement(final ObserverContext<RegionCoprocessorEnvironment> c, 1670 final Increment increment) throws IOException { 1671 User user = getActiveUser(c); 1672 checkForReservedTagPresence(user, increment); 1673 1674 // Require WRITE permission to the table, CF, and the KV to be replaced by 1675 // the incremented value 1676 RegionCoprocessorEnvironment env = c.getEnvironment(); 1677 Map<byte[], ? extends Collection<Cell>> families = increment.getFamilyCellMap(); 1678 AuthResult authResult = permissionGranted(OpType.INCREMENT, user, env, families, Action.WRITE); 1679 AccessChecker.logResult(authResult); 1680 if (!authResult.isAllowed()) { 1681 if (cellFeaturesEnabled && !compatibleEarlyTermination) { 1682 increment.setAttribute(CHECK_COVERING_PERM, TRUE); 1683 } else if (authorizationEnabled) { 1684 throw new AccessDeniedException("Insufficient permissions " + authResult.toContextString()); 1685 } 1686 } 1687 1688 byte[] bytes = increment.getAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL); 1689 if (bytes != null) { 1690 if (cellFeaturesEnabled) { 1691 addCellPermissions(bytes, increment.getFamilyCellMap()); 1692 } else { 1693 throw new DoNotRetryIOException("Cell ACLs cannot be persisted"); 1694 } 1695 } 1696 1697 return null; 1698 } 1699 1700 @Override 1701 public List<Pair<Cell, Cell>> postIncrementBeforeWAL( 1702 ObserverContext<RegionCoprocessorEnvironment> ctx, Mutation mutation, 1703 List<Pair<Cell, Cell>> cellPairs) throws IOException { 1704 // If the HFile version is insufficient to persist tags, we won't have any 1705 // work to do here 1706 if (!cellFeaturesEnabled || mutation.getACL() == null) { 1707 return cellPairs; 1708 } 1709 return cellPairs.stream() 1710 .map(pair -> new Pair<>(pair.getFirst(), 1711 createNewCellWithTags(mutation, pair.getFirst(), pair.getSecond()))) 1712 .collect(Collectors.toList()); 1713 } 1714 1715 @Override 1716 public List<Pair<Cell, Cell>> postAppendBeforeWAL( 1717 ObserverContext<RegionCoprocessorEnvironment> ctx, Mutation mutation, 1718 List<Pair<Cell, Cell>> cellPairs) throws IOException { 1719 // If the HFile version is insufficient to persist tags, we won't have any 1720 // work to do here 1721 if (!cellFeaturesEnabled || mutation.getACL() == null) { 1722 return cellPairs; 1723 } 1724 return cellPairs.stream() 1725 .map(pair -> new Pair<>(pair.getFirst(), 1726 createNewCellWithTags(mutation, pair.getFirst(), pair.getSecond()))) 1727 .collect(Collectors.toList()); 1728 } 1729 1730 private Cell createNewCellWithTags(Mutation mutation, Cell oldCell, Cell newCell) { 1731 // As Increment and Append operations have already copied the tags of oldCell to the newCell, 1732 // there is no need to rewrite them again. Just extract non-acl tags of newCell if we need to 1733 // add a new acl tag for the cell. Actually, oldCell is useless here. 1734 List<Tag> tags = Lists.newArrayList(); 1735 ExtendedCell newExtendedCell = (ExtendedCell) newCell; 1736 if (newExtendedCell != null) { 1737 Iterator<Tag> tagIterator = PrivateCellUtil.tagsIterator(newExtendedCell); 1738 while (tagIterator.hasNext()) { 1739 Tag tag = tagIterator.next(); 1740 if (tag.getType() != PermissionStorage.ACL_TAG_TYPE) { 1741 // Not an ACL tag, just carry it through 1742 if (LOG.isTraceEnabled()) { 1743 LOG.trace("Carrying forward tag from " + newCell + ": type " + tag.getType() 1744 + " length " + tag.getValueLength()); 1745 } 1746 tags.add(tag); 1747 } 1748 } 1749 } 1750 1751 // We have checked the ACL tag of mutation is not null. 1752 // So that the tags could not be empty. 1753 tags.add(new ArrayBackedTag(PermissionStorage.ACL_TAG_TYPE, mutation.getACL())); 1754 return PrivateCellUtil.createCell(newExtendedCell, tags); 1755 } 1756 1757 @Override 1758 public void preScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c, final Scan scan) 1759 throws IOException { 1760 internalPreRead(c, scan, OpType.SCAN); 1761 } 1762 1763 @Override 1764 public RegionScanner postScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c, 1765 final Scan scan, final RegionScanner s) throws IOException { 1766 User user = getActiveUser(c); 1767 if (user != null && user.getShortName() != null) { 1768 // store reference to scanner owner for later checks 1769 scannerOwners.put(s, user.getShortName()); 1770 } 1771 return s; 1772 } 1773 1774 @Override 1775 public boolean preScannerNext(final ObserverContext<RegionCoprocessorEnvironment> c, 1776 final InternalScanner s, final List<Result> result, final int limit, final boolean hasNext) 1777 throws IOException { 1778 requireScannerOwner(s); 1779 return hasNext; 1780 } 1781 1782 @Override 1783 public void preScannerClose(final ObserverContext<RegionCoprocessorEnvironment> c, 1784 final InternalScanner s) throws IOException { 1785 requireScannerOwner(s); 1786 } 1787 1788 @Override 1789 public void postScannerClose(final ObserverContext<RegionCoprocessorEnvironment> c, 1790 final InternalScanner s) throws IOException { 1791 // clean up any associated owner mapping 1792 scannerOwners.remove(s); 1793 } 1794 1795 /** 1796 * Verify, when servicing an RPC, that the caller is the scanner owner. If so, we assume that 1797 * access control is correctly enforced based on the checks performed in preScannerOpen() 1798 */ 1799 private void requireScannerOwner(InternalScanner s) throws AccessDeniedException { 1800 if (!RpcServer.isInRpcCallContext()) { 1801 return; 1802 } 1803 String requestUserName = RpcServer.getRequestUserName().orElse(null); 1804 String owner = scannerOwners.get(s); 1805 if (authorizationEnabled && owner != null && !owner.equals(requestUserName)) { 1806 throw new AccessDeniedException("User '" + requestUserName + "' is not the scanner owner!"); 1807 } 1808 } 1809 1810 /** 1811 * Verifies user has CREATE or ADMIN privileges on the Column Families involved in the 1812 * bulkLoadHFile request. Specific Column Write privileges are presently ignored. 1813 */ 1814 @Override 1815 public void preBulkLoadHFile(ObserverContext<RegionCoprocessorEnvironment> ctx, 1816 List<Pair<byte[], String>> familyPaths) throws IOException { 1817 User user = getActiveUser(ctx); 1818 for (Pair<byte[], String> el : familyPaths) { 1819 accessChecker.requirePermission(user, "preBulkLoadHFile", 1820 ctx.getEnvironment().getRegion().getTableDescriptor().getTableName(), el.getFirst(), null, 1821 null, Action.ADMIN, Action.CREATE); 1822 } 1823 } 1824 1825 /** 1826 * Authorization check for SecureBulkLoadProtocol.prepareBulkLoad() 1827 * @param ctx the context 1828 */ 1829 @Override 1830 public void prePrepareBulkLoad(ObserverContext<RegionCoprocessorEnvironment> ctx) 1831 throws IOException { 1832 requireAccess(ctx, "prePrepareBulkLoad", 1833 ctx.getEnvironment().getRegion().getTableDescriptor().getTableName(), Action.ADMIN, 1834 Action.CREATE); 1835 } 1836 1837 /** 1838 * Authorization security check for SecureBulkLoadProtocol.cleanupBulkLoad() 1839 * @param ctx the context 1840 */ 1841 @Override 1842 public void preCleanupBulkLoad(ObserverContext<RegionCoprocessorEnvironment> ctx) 1843 throws IOException { 1844 requireAccess(ctx, "preCleanupBulkLoad", 1845 ctx.getEnvironment().getRegion().getTableDescriptor().getTableName(), Action.ADMIN, 1846 Action.CREATE); 1847 } 1848 1849 /* ---- EndpointObserver implementation ---- */ 1850 1851 @Override 1852 public Message preEndpointInvocation(ObserverContext<RegionCoprocessorEnvironment> ctx, 1853 Service service, String methodName, Message request) throws IOException { 1854 // Don't intercept calls to our own AccessControlService, we check for 1855 // appropriate permissions in the service handlers 1856 if (shouldCheckExecPermission && !(service instanceof AccessControlService)) { 1857 requirePermission(ctx, 1858 "invoke(" + service.getDescriptorForType().getName() + "." + methodName + ")", 1859 getTableName(ctx.getEnvironment()), null, null, Action.EXEC); 1860 } 1861 return request; 1862 } 1863 1864 @Override 1865 public void postEndpointInvocation(ObserverContext<RegionCoprocessorEnvironment> ctx, 1866 Service service, String methodName, Message request, Message.Builder responseBuilder) 1867 throws IOException { 1868 } 1869 1870 /* ---- Protobuf AccessControlService implementation ---- */ 1871 1872 /** 1873 * @deprecated since 2.2.0 and will be removed in 4.0.0. Use 1874 * {@link Admin#grant(UserPermission, boolean)} instead. 1875 * @see Admin#grant(UserPermission, boolean) 1876 * @see <a href="https://issues.apache.org/jira/browse/HBASE-21739">HBASE-21739</a> 1877 */ 1878 @Deprecated 1879 @Override 1880 public void grant(RpcController controller, AccessControlProtos.GrantRequest request, 1881 RpcCallback<AccessControlProtos.GrantResponse> done) { 1882 final UserPermission perm = AccessControlUtil.toUserPermission(request.getUserPermission()); 1883 AccessControlProtos.GrantResponse response = null; 1884 try { 1885 // verify it's only running at .acl. 1886 if (aclRegion) { 1887 if (!initialized) { 1888 throw new CoprocessorException("AccessController not yet initialized"); 1889 } 1890 User caller = RpcServer.getRequestUser().orElse(null); 1891 if (LOG.isDebugEnabled()) { 1892 LOG.debug("Received request from {} to grant access permission {}", caller.getName(), 1893 perm.toString()); 1894 } 1895 preGrantOrRevoke(caller, "grant", perm); 1896 1897 // regionEnv is set at #start. Hopefully not null at this point. 1898 regionEnv.getConnection().getAdmin().grant( 1899 new UserPermission(perm.getUser(), perm.getPermission()), 1900 request.getMergeExistingPermissions()); 1901 if (AUDITLOG.isTraceEnabled()) { 1902 // audit log should store permission changes in addition to auth results 1903 AUDITLOG.trace("Granted permission " + perm.toString()); 1904 } 1905 } else { 1906 throw new CoprocessorException(AccessController.class, 1907 "This method " + "can only execute at " + PermissionStorage.ACL_TABLE_NAME + " table."); 1908 } 1909 response = AccessControlProtos.GrantResponse.getDefaultInstance(); 1910 } catch (IOException ioe) { 1911 // pass exception back up 1912 CoprocessorRpcUtils.setControllerException(controller, ioe); 1913 } 1914 done.run(response); 1915 } 1916 1917 /** 1918 * @deprecated since 2.2.0 and will be removed in 4.0.0. Use {@link Admin#revoke(UserPermission)} 1919 * instead. 1920 * @see Admin#revoke(UserPermission) 1921 * @see <a href="https://issues.apache.org/jira/browse/HBASE-21739">HBASE-21739</a> 1922 */ 1923 @Deprecated 1924 @Override 1925 public void revoke(RpcController controller, AccessControlProtos.RevokeRequest request, 1926 RpcCallback<AccessControlProtos.RevokeResponse> done) { 1927 final UserPermission perm = AccessControlUtil.toUserPermission(request.getUserPermission()); 1928 AccessControlProtos.RevokeResponse response = null; 1929 try { 1930 // only allowed to be called on _acl_ region 1931 if (aclRegion) { 1932 if (!initialized) { 1933 throw new CoprocessorException("AccessController not yet initialized"); 1934 } 1935 User caller = RpcServer.getRequestUser().orElse(null); 1936 if (LOG.isDebugEnabled()) { 1937 LOG.debug("Received request from {} to revoke access permission {}", 1938 caller.getShortName(), perm.toString()); 1939 } 1940 preGrantOrRevoke(caller, "revoke", perm); 1941 // regionEnv is set at #start. Hopefully not null here. 1942 regionEnv.getConnection().getAdmin() 1943 .revoke(new UserPermission(perm.getUser(), perm.getPermission())); 1944 if (AUDITLOG.isTraceEnabled()) { 1945 // audit log should record all permission changes 1946 AUDITLOG.trace("Revoked permission " + perm.toString()); 1947 } 1948 } else { 1949 throw new CoprocessorException(AccessController.class, 1950 "This method " + "can only execute at " + PermissionStorage.ACL_TABLE_NAME + " table."); 1951 } 1952 response = AccessControlProtos.RevokeResponse.getDefaultInstance(); 1953 } catch (IOException ioe) { 1954 // pass exception back up 1955 CoprocessorRpcUtils.setControllerException(controller, ioe); 1956 } 1957 done.run(response); 1958 } 1959 1960 /** 1961 * @deprecated since 2.2.0 and will be removed in 4.0.0. Use 1962 * {@link Admin#getUserPermissions(GetUserPermissionsRequest)} instead. 1963 * @see Admin#getUserPermissions(GetUserPermissionsRequest) 1964 * @see <a href="https://issues.apache.org/jira/browse/HBASE-21911">HBASE-21911</a> 1965 */ 1966 @Deprecated 1967 @Override 1968 public void getUserPermissions(RpcController controller, 1969 AccessControlProtos.GetUserPermissionsRequest request, 1970 RpcCallback<AccessControlProtos.GetUserPermissionsResponse> done) { 1971 AccessControlProtos.GetUserPermissionsResponse response = null; 1972 try { 1973 // only allowed to be called on _acl_ region 1974 if (aclRegion) { 1975 if (!initialized) { 1976 throw new CoprocessorException("AccessController not yet initialized"); 1977 } 1978 User caller = RpcServer.getRequestUser().orElse(null); 1979 final String userName = request.hasUserName() ? request.getUserName().toStringUtf8() : null; 1980 final String namespace = 1981 request.hasNamespaceName() ? request.getNamespaceName().toStringUtf8() : null; 1982 final TableName table = 1983 request.hasTableName() ? ProtobufUtil.toTableName(request.getTableName()) : null; 1984 final byte[] cf = 1985 request.hasColumnFamily() ? request.getColumnFamily().toByteArray() : null; 1986 final byte[] cq = 1987 request.hasColumnQualifier() ? request.getColumnQualifier().toByteArray() : null; 1988 preGetUserPermissions(caller, userName, namespace, table, cf, cq); 1989 GetUserPermissionsRequest getUserPermissionsRequest = null; 1990 if (request.getType() == AccessControlProtos.Permission.Type.Table) { 1991 getUserPermissionsRequest = GetUserPermissionsRequest.newBuilder(table).withFamily(cf) 1992 .withQualifier(cq).withUserName(userName).build(); 1993 } else if (request.getType() == AccessControlProtos.Permission.Type.Namespace) { 1994 getUserPermissionsRequest = 1995 GetUserPermissionsRequest.newBuilder(namespace).withUserName(userName).build(); 1996 } else { 1997 getUserPermissionsRequest = 1998 GetUserPermissionsRequest.newBuilder().withUserName(userName).build(); 1999 } 2000 List<UserPermission> perms = 2001 regionEnv.getConnection().getAdmin().getUserPermissions(getUserPermissionsRequest); 2002 response = AccessControlUtil.buildGetUserPermissionsResponse(perms); 2003 } else { 2004 throw new CoprocessorException(AccessController.class, 2005 "This method " + "can only execute at " + PermissionStorage.ACL_TABLE_NAME + " table."); 2006 } 2007 } catch (IOException ioe) { 2008 // pass exception back up 2009 CoprocessorRpcUtils.setControllerException(controller, ioe); 2010 } 2011 done.run(response); 2012 } 2013 2014 /** 2015 * @deprecated since 2.2.0 and will be removed 4.0.0. Use {@link Admin#hasUserPermissions(List)} 2016 * instead. 2017 * @see Admin#hasUserPermissions(List) 2018 * @see <a href="https://issues.apache.org/jira/browse/HBASE-22117">HBASE-22117</a> 2019 */ 2020 @Deprecated 2021 @Override 2022 public void checkPermissions(RpcController controller, 2023 AccessControlProtos.CheckPermissionsRequest request, 2024 RpcCallback<AccessControlProtos.CheckPermissionsResponse> done) { 2025 AccessControlProtos.CheckPermissionsResponse response = null; 2026 try { 2027 User user = RpcServer.getRequestUser().orElse(null); 2028 TableName tableName = regionEnv.getRegion().getTableDescriptor().getTableName(); 2029 List<Permission> permissions = new ArrayList<>(); 2030 for (int i = 0; i < request.getPermissionCount(); i++) { 2031 Permission permission = AccessControlUtil.toPermission(request.getPermission(i)); 2032 permissions.add(permission); 2033 if (permission instanceof TablePermission) { 2034 TablePermission tperm = (TablePermission) permission; 2035 if (!tperm.getTableName().equals(tableName)) { 2036 throw new CoprocessorException(AccessController.class, 2037 String.format( 2038 "This method can only execute at the table specified in " 2039 + "TablePermission. Table of the region:%s , requested table:%s", 2040 tableName, tperm.getTableName())); 2041 } 2042 } 2043 } 2044 for (Permission permission : permissions) { 2045 boolean hasPermission = 2046 accessChecker.hasUserPermission(user, "checkPermissions", permission); 2047 if (!hasPermission) { 2048 throw new AccessDeniedException("Insufficient permissions " + permission.toString()); 2049 } 2050 } 2051 response = AccessControlProtos.CheckPermissionsResponse.getDefaultInstance(); 2052 } catch (IOException ioe) { 2053 CoprocessorRpcUtils.setControllerException(controller, ioe); 2054 } 2055 done.run(response); 2056 } 2057 2058 private Region getRegion(RegionCoprocessorEnvironment e) { 2059 return e.getRegion(); 2060 } 2061 2062 private TableName getTableName(RegionCoprocessorEnvironment e) { 2063 Region region = e.getRegion(); 2064 if (region != null) { 2065 return getTableName(region); 2066 } 2067 return null; 2068 } 2069 2070 private TableName getTableName(Region region) { 2071 RegionInfo regionInfo = region.getRegionInfo(); 2072 if (regionInfo != null) { 2073 return regionInfo.getTable(); 2074 } 2075 return null; 2076 } 2077 2078 @Override 2079 public void preClose(ObserverContext<RegionCoprocessorEnvironment> c, boolean abortRequested) 2080 throws IOException { 2081 requirePermission(c, "preClose", Action.ADMIN); 2082 } 2083 2084 private void checkSystemOrSuperUser(User activeUser) throws IOException { 2085 // No need to check if we're not going to throw 2086 if (!authorizationEnabled) { 2087 return; 2088 } 2089 if (!Superusers.isSuperUser(activeUser)) { 2090 throw new AccessDeniedException( 2091 "User '" + (activeUser != null ? activeUser.getShortName() : "null") 2092 + "' is not system or super user."); 2093 } 2094 } 2095 2096 @Override 2097 public void preStopRegionServer(ObserverContext<RegionServerCoprocessorEnvironment> ctx) 2098 throws IOException { 2099 requirePermission(ctx, "preStopRegionServer", Action.ADMIN); 2100 } 2101 2102 private Map<byte[], ? extends Collection<byte[]>> makeFamilyMap(byte[] family, byte[] qualifier) { 2103 if (family == null) { 2104 return null; 2105 } 2106 2107 Map<byte[], Collection<byte[]>> familyMap = new TreeMap<>(Bytes.BYTES_COMPARATOR); 2108 familyMap.put(family, qualifier != null ? ImmutableSet.of(qualifier) : null); 2109 return familyMap; 2110 } 2111 2112 @Override 2113 public void preGetTableDescriptors(ObserverContext<MasterCoprocessorEnvironment> ctx, 2114 List<TableName> tableNamesList, List<TableDescriptor> descriptors, String regex) 2115 throws IOException { 2116 // We are delegating the authorization check to postGetTableDescriptors as we don't have 2117 // any concrete set of table names when a regex is present or the full list is requested. 2118 if (regex == null && tableNamesList != null && !tableNamesList.isEmpty()) { 2119 // Otherwise, if the requestor has ADMIN or CREATE privs for all listed tables, the 2120 // request can be granted. 2121 try (Admin admin = ctx.getEnvironment().getConnection().getAdmin()) { 2122 for (TableName tableName : tableNamesList) { 2123 // Skip checks for a table that does not exist 2124 if (!admin.tableExists(tableName)) { 2125 continue; 2126 } 2127 requirePermission(ctx, "getTableDescriptors", tableName, null, null, Action.ADMIN, 2128 Action.CREATE); 2129 } 2130 } 2131 } 2132 } 2133 2134 @Override 2135 public void postGetTableDescriptors(ObserverContext<MasterCoprocessorEnvironment> ctx, 2136 List<TableName> tableNamesList, List<TableDescriptor> descriptors, String regex) 2137 throws IOException { 2138 // Skipping as checks in this case are already done by preGetTableDescriptors. 2139 if (regex == null && tableNamesList != null && !tableNamesList.isEmpty()) { 2140 return; 2141 } 2142 2143 // Retains only those which passes authorization checks, as the checks weren't done as part 2144 // of preGetTableDescriptors. 2145 Iterator<TableDescriptor> itr = descriptors.iterator(); 2146 while (itr.hasNext()) { 2147 TableDescriptor htd = itr.next(); 2148 try { 2149 requirePermission(ctx, "getTableDescriptors", htd.getTableName(), null, null, Action.ADMIN, 2150 Action.CREATE); 2151 } catch (AccessDeniedException e) { 2152 itr.remove(); 2153 } 2154 } 2155 } 2156 2157 @Override 2158 public void postGetTableNames(ObserverContext<MasterCoprocessorEnvironment> ctx, 2159 List<TableDescriptor> descriptors, String regex) throws IOException { 2160 // Retains only those which passes authorization checks. 2161 Iterator<TableDescriptor> itr = descriptors.iterator(); 2162 while (itr.hasNext()) { 2163 TableDescriptor htd = itr.next(); 2164 try { 2165 requireAccess(ctx, "getTableNames", htd.getTableName(), Action.values()); 2166 } catch (AccessDeniedException e) { 2167 itr.remove(); 2168 } 2169 } 2170 } 2171 2172 @Override 2173 public void preMergeRegions(final ObserverContext<MasterCoprocessorEnvironment> ctx, 2174 final RegionInfo[] regionsToMerge) throws IOException { 2175 requirePermission(ctx, "mergeRegions", regionsToMerge[0].getTable(), null, null, Action.ADMIN); 2176 } 2177 2178 @Override 2179 public void preRollWALWriterRequest(ObserverContext<RegionServerCoprocessorEnvironment> ctx) 2180 throws IOException { 2181 requirePermission(ctx, "preRollLogWriterRequest", Permission.Action.ADMIN); 2182 } 2183 2184 @Override 2185 public void postRollWALWriterRequest(ObserverContext<RegionServerCoprocessorEnvironment> ctx) 2186 throws IOException { 2187 } 2188 2189 @Override 2190 public void preSetUserQuota(final ObserverContext<MasterCoprocessorEnvironment> ctx, 2191 final String userName, final GlobalQuotaSettings quotas) throws IOException { 2192 requirePermission(ctx, "setUserQuota", Action.ADMIN); 2193 } 2194 2195 @Override 2196 public void preSetUserQuota(final ObserverContext<MasterCoprocessorEnvironment> ctx, 2197 final String userName, final TableName tableName, final GlobalQuotaSettings quotas) 2198 throws IOException { 2199 requirePermission(ctx, "setUserTableQuota", tableName, null, null, Action.ADMIN); 2200 } 2201 2202 @Override 2203 public void preSetUserQuota(final ObserverContext<MasterCoprocessorEnvironment> ctx, 2204 final String userName, final String namespace, final GlobalQuotaSettings quotas) 2205 throws IOException { 2206 requirePermission(ctx, "setUserNamespaceQuota", Action.ADMIN); 2207 } 2208 2209 @Override 2210 public void preSetTableQuota(final ObserverContext<MasterCoprocessorEnvironment> ctx, 2211 final TableName tableName, final GlobalQuotaSettings quotas) throws IOException { 2212 requirePermission(ctx, "setTableQuota", tableName, null, null, Action.ADMIN); 2213 } 2214 2215 @Override 2216 public void preSetNamespaceQuota(final ObserverContext<MasterCoprocessorEnvironment> ctx, 2217 final String namespace, final GlobalQuotaSettings quotas) throws IOException { 2218 requirePermission(ctx, "setNamespaceQuota", Action.ADMIN); 2219 } 2220 2221 @Override 2222 public void preSetRegionServerQuota(ObserverContext<MasterCoprocessorEnvironment> ctx, 2223 final String regionServer, GlobalQuotaSettings quotas) throws IOException { 2224 requirePermission(ctx, "setRegionServerQuota", Action.ADMIN); 2225 } 2226 2227 @Override 2228 public ReplicationEndpoint postCreateReplicationEndPoint( 2229 ObserverContext<RegionServerCoprocessorEnvironment> ctx, ReplicationEndpoint endpoint) { 2230 return endpoint; 2231 } 2232 2233 @Override 2234 public void preReplicateLogEntries(ObserverContext<RegionServerCoprocessorEnvironment> ctx) 2235 throws IOException { 2236 requirePermission(ctx, "replicateLogEntries", Action.WRITE); 2237 } 2238 2239 @Override 2240 public void preClearCompactionQueues(ObserverContext<RegionServerCoprocessorEnvironment> ctx) 2241 throws IOException { 2242 requirePermission(ctx, "preClearCompactionQueues", Permission.Action.ADMIN); 2243 } 2244 2245 @Override 2246 public void preAddReplicationPeer(final ObserverContext<MasterCoprocessorEnvironment> ctx, 2247 String peerId, ReplicationPeerConfig peerConfig) throws IOException { 2248 requirePermission(ctx, "addReplicationPeer", Action.ADMIN); 2249 } 2250 2251 @Override 2252 public void preRemoveReplicationPeer(final ObserverContext<MasterCoprocessorEnvironment> ctx, 2253 String peerId) throws IOException { 2254 requirePermission(ctx, "removeReplicationPeer", Action.ADMIN); 2255 } 2256 2257 @Override 2258 public void preEnableReplicationPeer(final ObserverContext<MasterCoprocessorEnvironment> ctx, 2259 String peerId) throws IOException { 2260 requirePermission(ctx, "enableReplicationPeer", Action.ADMIN); 2261 } 2262 2263 @Override 2264 public void preDisableReplicationPeer(final ObserverContext<MasterCoprocessorEnvironment> ctx, 2265 String peerId) throws IOException { 2266 requirePermission(ctx, "disableReplicationPeer", Action.ADMIN); 2267 } 2268 2269 @Override 2270 public void preGetReplicationPeerConfig(final ObserverContext<MasterCoprocessorEnvironment> ctx, 2271 String peerId) throws IOException { 2272 requirePermission(ctx, "getReplicationPeerConfig", Action.ADMIN); 2273 } 2274 2275 @Override 2276 public void preUpdateReplicationPeerConfig( 2277 final ObserverContext<MasterCoprocessorEnvironment> ctx, String peerId, 2278 ReplicationPeerConfig peerConfig) throws IOException { 2279 requirePermission(ctx, "updateReplicationPeerConfig", Action.ADMIN); 2280 } 2281 2282 @Override 2283 public void preTransitReplicationPeerSyncReplicationState( 2284 final ObserverContext<MasterCoprocessorEnvironment> ctx, String peerId, 2285 SyncReplicationState clusterState) throws IOException { 2286 requirePermission(ctx, "transitSyncReplicationPeerState", Action.ADMIN); 2287 } 2288 2289 @Override 2290 public void preListReplicationPeers(final ObserverContext<MasterCoprocessorEnvironment> ctx, 2291 String regex) throws IOException { 2292 requirePermission(ctx, "listReplicationPeers", Action.ADMIN); 2293 } 2294 2295 @Override 2296 public void preRequestLock(ObserverContext<MasterCoprocessorEnvironment> ctx, String namespace, 2297 TableName tableName, RegionInfo[] regionInfos, String description) throws IOException { 2298 // There are operations in the CREATE and ADMIN domain which may require lock, READ 2299 // or WRITE. So for any lock request, we check for these two perms irrespective of lock type. 2300 String reason = String.format("Description=%s", description); 2301 checkLockPermissions(ctx, namespace, tableName, regionInfos, reason); 2302 } 2303 2304 @Override 2305 public void preLockHeartbeat(ObserverContext<MasterCoprocessorEnvironment> ctx, 2306 TableName tableName, String description) throws IOException { 2307 checkLockPermissions(ctx, null, tableName, null, description); 2308 } 2309 2310 @Override 2311 public void preExecuteProcedures(ObserverContext<RegionServerCoprocessorEnvironment> ctx) 2312 throws IOException { 2313 checkSystemOrSuperUser(getActiveUser(ctx)); 2314 } 2315 2316 @Override 2317 public void preSwitchRpcThrottle(ObserverContext<MasterCoprocessorEnvironment> ctx, 2318 boolean enable) throws IOException { 2319 requirePermission(ctx, "switchRpcThrottle", Action.ADMIN); 2320 } 2321 2322 @Override 2323 public void preIsRpcThrottleEnabled(ObserverContext<MasterCoprocessorEnvironment> ctx) 2324 throws IOException { 2325 requirePermission(ctx, "isRpcThrottleEnabled", Action.ADMIN); 2326 } 2327 2328 @Override 2329 public void preSwitchExceedThrottleQuota(ObserverContext<MasterCoprocessorEnvironment> ctx, 2330 boolean enable) throws IOException { 2331 requirePermission(ctx, "switchExceedThrottleQuota", Action.ADMIN); 2332 } 2333 2334 /** 2335 * Returns the active user to which authorization checks should be applied. If we are in the 2336 * context of an RPC call, the remote user is used, otherwise the currently logged in user is 2337 * used. 2338 */ 2339 private User getActiveUser(ObserverContext<?> ctx) throws IOException { 2340 // for non-rpc handling, fallback to system user 2341 Optional<User> optionalUser = ctx.getCaller(); 2342 if (optionalUser.isPresent()) { 2343 return optionalUser.get(); 2344 } 2345 return userProvider.getCurrent(); 2346 } 2347 2348 /** 2349 * @deprecated since 2.2.0 and will be removed in 4.0.0. Use 2350 * {@link Admin#hasUserPermissions(String, List)} instead. 2351 * @see Admin#hasUserPermissions(String, List) 2352 * @see <a href="https://issues.apache.org/jira/browse/HBASE-22117">HBASE-22117</a> 2353 */ 2354 @Deprecated 2355 @Override 2356 public void hasPermission(RpcController controller, HasPermissionRequest request, 2357 RpcCallback<HasPermissionResponse> done) { 2358 // Converts proto to a TablePermission object. 2359 TablePermission tPerm = AccessControlUtil.toTablePermission(request.getTablePermission()); 2360 // Check input user name 2361 if (!request.hasUserName()) { 2362 throw new IllegalStateException("Input username cannot be empty"); 2363 } 2364 final String inputUserName = request.getUserName().toStringUtf8(); 2365 AccessControlProtos.HasPermissionResponse response = null; 2366 try { 2367 User caller = RpcServer.getRequestUser().orElse(null); 2368 List<Permission> permissions = Lists.newArrayList(tPerm); 2369 preHasUserPermissions(caller, inputUserName, permissions); 2370 boolean hasPermission = 2371 regionEnv.getConnection().getAdmin().hasUserPermissions(inputUserName, permissions).get(0); 2372 response = ResponseConverter.buildHasPermissionResponse(hasPermission); 2373 } catch (IOException ioe) { 2374 ResponseConverter.setControllerException(controller, ioe); 2375 } 2376 done.run(response); 2377 } 2378 2379 @Override 2380 public void preGrant(ObserverContext<MasterCoprocessorEnvironment> ctx, 2381 UserPermission userPermission, boolean mergeExistingPermissions) throws IOException { 2382 preGrantOrRevoke(getActiveUser(ctx), "grant", userPermission); 2383 } 2384 2385 @Override 2386 public void preRevoke(ObserverContext<MasterCoprocessorEnvironment> ctx, 2387 UserPermission userPermission) throws IOException { 2388 preGrantOrRevoke(getActiveUser(ctx), "revoke", userPermission); 2389 } 2390 2391 private void preGrantOrRevoke(User caller, String request, UserPermission userPermission) 2392 throws IOException { 2393 switch (userPermission.getPermission().scope) { 2394 case GLOBAL: 2395 accessChecker.requireGlobalPermission(caller, request, Action.ADMIN, ""); 2396 break; 2397 case NAMESPACE: 2398 NamespacePermission namespacePerm = (NamespacePermission) userPermission.getPermission(); 2399 accessChecker.requireNamespacePermission(caller, request, namespacePerm.getNamespace(), 2400 null, Action.ADMIN); 2401 break; 2402 case TABLE: 2403 TablePermission tablePerm = (TablePermission) userPermission.getPermission(); 2404 accessChecker.requirePermission(caller, request, tablePerm.getTableName(), 2405 tablePerm.getFamily(), tablePerm.getQualifier(), null, Action.ADMIN); 2406 break; 2407 default: 2408 } 2409 if (!Superusers.isSuperUser(caller)) { 2410 accessChecker.performOnSuperuser(request, caller, userPermission.getUser()); 2411 } 2412 } 2413 2414 @Override 2415 public void preGetUserPermissions(ObserverContext<MasterCoprocessorEnvironment> ctx, 2416 String userName, String namespace, TableName tableName, byte[] family, byte[] qualifier) 2417 throws IOException { 2418 preGetUserPermissions(getActiveUser(ctx), userName, namespace, tableName, family, qualifier); 2419 } 2420 2421 private void preGetUserPermissions(User caller, String userName, String namespace, 2422 TableName tableName, byte[] family, byte[] qualifier) throws IOException { 2423 if (tableName != null) { 2424 accessChecker.requirePermission(caller, "getUserPermissions", tableName, family, qualifier, 2425 userName, Action.ADMIN); 2426 } else if (namespace != null) { 2427 accessChecker.requireNamespacePermission(caller, "getUserPermissions", namespace, userName, 2428 Action.ADMIN); 2429 } else { 2430 accessChecker.requirePermission(caller, "getUserPermissions", userName, Action.ADMIN); 2431 } 2432 } 2433 2434 @Override 2435 public void preHasUserPermissions(ObserverContext<MasterCoprocessorEnvironment> ctx, 2436 String userName, List<Permission> permissions) throws IOException { 2437 preHasUserPermissions(getActiveUser(ctx), userName, permissions); 2438 } 2439 2440 private void preHasUserPermissions(User caller, String userName, List<Permission> permissions) 2441 throws IOException { 2442 String request = "hasUserPermissions"; 2443 for (Permission permission : permissions) { 2444 if (!caller.getShortName().equals(userName)) { 2445 // User should have admin privilege if checking permission for other users 2446 if (permission instanceof TablePermission) { 2447 TablePermission tPerm = (TablePermission) permission; 2448 accessChecker.requirePermission(caller, request, tPerm.getTableName(), tPerm.getFamily(), 2449 tPerm.getQualifier(), userName, Action.ADMIN); 2450 } else if (permission instanceof NamespacePermission) { 2451 NamespacePermission nsPerm = (NamespacePermission) permission; 2452 accessChecker.requireNamespacePermission(caller, request, nsPerm.getNamespace(), userName, 2453 Action.ADMIN); 2454 } else { 2455 accessChecker.requirePermission(caller, request, userName, Action.ADMIN); 2456 } 2457 } else { 2458 // User don't need ADMIN privilege for self check. 2459 // Setting action as null in AuthResult to display empty action in audit log 2460 AuthResult result; 2461 if (permission instanceof TablePermission) { 2462 TablePermission tPerm = (TablePermission) permission; 2463 result = AuthResult.allow(request, "Self user validation allowed", caller, null, 2464 tPerm.getTableName(), tPerm.getFamily(), tPerm.getQualifier()); 2465 } else if (permission instanceof NamespacePermission) { 2466 NamespacePermission nsPerm = (NamespacePermission) permission; 2467 result = AuthResult.allow(request, "Self user validation allowed", caller, null, 2468 nsPerm.getNamespace()); 2469 } else { 2470 result = AuthResult.allow(request, "Self user validation allowed", caller, null, null, 2471 null, null); 2472 } 2473 AccessChecker.logResult(result); 2474 } 2475 } 2476 } 2477 2478 @Override 2479 public void preMoveServersAndTables(ObserverContext<MasterCoprocessorEnvironment> ctx, 2480 Set<Address> servers, Set<TableName> tables, String targetGroup) throws IOException { 2481 accessChecker.requirePermission(getActiveUser(ctx), "moveServersAndTables", null, 2482 Permission.Action.ADMIN); 2483 } 2484 2485 @Override 2486 public void preMoveServers(final ObserverContext<MasterCoprocessorEnvironment> ctx, 2487 Set<Address> servers, String targetGroup) throws IOException { 2488 accessChecker.requirePermission(getActiveUser(ctx), "moveServers", null, 2489 Permission.Action.ADMIN); 2490 } 2491 2492 @Override 2493 public void preMoveTables(ObserverContext<MasterCoprocessorEnvironment> ctx, 2494 Set<TableName> tables, String targetGroup) throws IOException { 2495 accessChecker.requirePermission(getActiveUser(ctx), "moveTables", null, 2496 Permission.Action.ADMIN); 2497 } 2498 2499 @Override 2500 public void preAddRSGroup(ObserverContext<MasterCoprocessorEnvironment> ctx, String name) 2501 throws IOException { 2502 accessChecker.requirePermission(getActiveUser(ctx), "addRSGroup", null, 2503 Permission.Action.ADMIN); 2504 } 2505 2506 @Override 2507 public void preRemoveRSGroup(ObserverContext<MasterCoprocessorEnvironment> ctx, String name) 2508 throws IOException { 2509 accessChecker.requirePermission(getActiveUser(ctx), "removeRSGroup", null, 2510 Permission.Action.ADMIN); 2511 } 2512 2513 @Override 2514 public void preBalanceRSGroup(ObserverContext<MasterCoprocessorEnvironment> ctx, String groupName, 2515 BalanceRequest request) throws IOException { 2516 accessChecker.requirePermission(getActiveUser(ctx), "balanceRSGroup", null, 2517 Permission.Action.ADMIN); 2518 } 2519 2520 @Override 2521 public void preRemoveServers(ObserverContext<MasterCoprocessorEnvironment> ctx, 2522 Set<Address> servers) throws IOException { 2523 accessChecker.requirePermission(getActiveUser(ctx), "removeServers", null, 2524 Permission.Action.ADMIN); 2525 } 2526 2527 @Override 2528 public void preGetRSGroupInfo(ObserverContext<MasterCoprocessorEnvironment> ctx, String groupName) 2529 throws IOException { 2530 accessChecker.requirePermission(getActiveUser(ctx), "getRSGroupInfo", null, 2531 Permission.Action.ADMIN); 2532 } 2533 2534 @Override 2535 public void preGetRSGroupInfoOfTable(ObserverContext<MasterCoprocessorEnvironment> ctx, 2536 TableName tableName) throws IOException { 2537 accessChecker.requirePermission(getActiveUser(ctx), "getRSGroupInfoOfTable", null, 2538 Permission.Action.ADMIN); 2539 // todo: should add check for table existence 2540 } 2541 2542 @Override 2543 public void preListRSGroups(ObserverContext<MasterCoprocessorEnvironment> ctx) 2544 throws IOException { 2545 accessChecker.requirePermission(getActiveUser(ctx), "listRSGroups", null, 2546 Permission.Action.ADMIN); 2547 } 2548 2549 @Override 2550 public void preListTablesInRSGroup(ObserverContext<MasterCoprocessorEnvironment> ctx, 2551 String groupName) throws IOException { 2552 accessChecker.requirePermission(getActiveUser(ctx), "listTablesInRSGroup", null, 2553 Permission.Action.ADMIN); 2554 } 2555 2556 @Override 2557 public void preGetConfiguredNamespacesAndTablesInRSGroup( 2558 ObserverContext<MasterCoprocessorEnvironment> ctx, String groupName) throws IOException { 2559 accessChecker.requirePermission(getActiveUser(ctx), "getConfiguredNamespacesAndTablesInRSGroup", 2560 null, Permission.Action.ADMIN); 2561 } 2562 2563 @Override 2564 public void preGetRSGroupInfoOfServer(ObserverContext<MasterCoprocessorEnvironment> ctx, 2565 Address server) throws IOException { 2566 accessChecker.requirePermission(getActiveUser(ctx), "getRSGroupInfoOfServer", null, 2567 Permission.Action.ADMIN); 2568 } 2569 2570 @Override 2571 public void preRenameRSGroup(ObserverContext<MasterCoprocessorEnvironment> ctx, String oldName, 2572 String newName) throws IOException { 2573 accessChecker.requirePermission(getActiveUser(ctx), "renameRSGroup", null, 2574 Permission.Action.ADMIN); 2575 } 2576 2577 @Override 2578 public void preUpdateRSGroupConfig(final ObserverContext<MasterCoprocessorEnvironment> ctx, 2579 final String groupName, final Map<String, String> configuration) throws IOException { 2580 accessChecker.requirePermission(getActiveUser(ctx), "updateRSGroupConfig", null, 2581 Permission.Action.ADMIN); 2582 } 2583 2584 @Override 2585 public void preClearRegionBlockCache(ObserverContext<RegionServerCoprocessorEnvironment> ctx) 2586 throws IOException { 2587 accessChecker.requirePermission(getActiveUser(ctx), "clearRegionBlockCache", null, 2588 Permission.Action.ADMIN); 2589 } 2590 2591 @Override 2592 public void preUpdateRegionServerConfiguration( 2593 ObserverContext<RegionServerCoprocessorEnvironment> ctx, Configuration preReloadConf) 2594 throws IOException { 2595 accessChecker.requirePermission(getActiveUser(ctx), "updateConfiguration", null, 2596 Permission.Action.ADMIN); 2597 } 2598 2599 @Override 2600 public void preUpdateMasterConfiguration(ObserverContext<MasterCoprocessorEnvironment> ctx, 2601 Configuration preReloadConf) throws IOException { 2602 accessChecker.requirePermission(getActiveUser(ctx), "updateConfiguration", null, 2603 Permission.Action.ADMIN); 2604 } 2605 2606}