List of usage examples for org.apache.hadoop.security UserGroupInformation getShortUserName
public String getShortUserName()
From source file:org.apache.ranger.authorization.hive.authorizer.RangerHiveAuthorizer.java
License:Apache License
/** * Check if user has privileges to do this action on these objects * @param objs//from w ww. j a v a2s . c o m * @param context * @throws HiveAuthzPluginException * @throws HiveAccessControlException */ // Commented out to avoid build errors until this interface is stable in Hive Branch // @Override public List<HivePrivilegeObject> filterListCmdObjects(List<HivePrivilegeObject> objs, HiveAuthzContext context) throws HiveAuthzPluginException, HiveAccessControlException { if (LOG.isDebugEnabled()) { LOG.debug(String.format("==> filterListCmdObjects(%s, %s)", objs, context)); } List<HivePrivilegeObject> ret = null; // bail out early if nothing is there to validate! if (objs == null) { LOG.debug("filterListCmdObjects: meta objects list was null!"); } else if (objs.isEmpty()) { LOG.debug("filterListCmdObjects: meta objects list was empty!"); ret = objs; } else if (getCurrentUserGroupInfo() == null) { /* * This is null for metastore and there doesn't seem to be a way to tell if one is running as metastore or hiveserver2! */ LOG.warn("filterListCmdObjects: user information not available"); ret = objs; } else { if (LOG.isDebugEnabled()) { LOG.debug("filterListCmdObjects: number of input objects[" + objs.size() + "]"); } // get user/group info UserGroupInformation ugi = getCurrentUserGroupInfo(); // we know this can't be null since we checked it above! HiveAuthzSessionContext sessionContext = getHiveAuthzSessionContext(); String user = ugi.getShortUserName(); Set<String> groups = Sets.newHashSet(ugi.getGroupNames()); if (LOG.isDebugEnabled()) { LOG.debug(String.format("filterListCmdObjects: user[%s], groups%s", user, groups)); } if (ret == null) { // if we got any items to filter then we can't return back a null. We must return back a list even if its empty. ret = new ArrayList<HivePrivilegeObject>(objs.size()); } for (HivePrivilegeObject privilegeObject : objs) { if (LOG.isDebugEnabled()) { HivePrivObjectActionType actionType = privilegeObject.getActionType(); HivePrivilegeObjectType objectType = privilegeObject.getType(); String objectName = privilegeObject.getObjectName(); String dbName = privilegeObject.getDbname(); List<String> columns = privilegeObject.getColumns(); List<String> partitionKeys = privilegeObject.getPartKeys(); String commandString = context == null ? null : context.getCommandString(); String ipAddress = context == null ? null : context.getIpAddress(); final String format = "filterListCmdObjects: actionType[%s], objectType[%s], objectName[%s], dbName[%s], columns[%s], partitionKeys[%s]; context: commandString[%s], ipAddress[%s]"; LOG.debug(String.format(format, actionType, objectType, objectName, dbName, columns, partitionKeys, commandString, ipAddress)); } RangerHiveResource resource = createHiveResource(privilegeObject); if (resource == null) { LOG.error("filterListCmdObjects: RangerHiveResource returned by createHiveResource is null"); } else { RangerHiveAccessRequest request = new RangerHiveAccessRequest(resource, user, groups, context, sessionContext); RangerAccessResult result = hivePlugin.isAccessAllowed(request); if (result == null) { LOG.error( "filterListCmdObjects: Internal error: null RangerAccessResult object received back from isAccessAllowed()!"); } else if (!result.getIsAllowed()) { if (!LOG.isDebugEnabled()) { String path = resource.getAsString(); LOG.debug(String.format( "filterListCmdObjects: Permission denied: user [%s] does not have [%s] privilege on [%s]. resource[%s], request[%s], result[%s]", user, request.getHiveAccessType().name(), path, resource, request, result)); } } else { if (LOG.isDebugEnabled()) { LOG.debug(String.format( "filterListCmdObjects: access allowed. resource[%s], request[%s], result[%s]", resource, request, result)); } ret.add(privilegeObject); } } } } if (LOG.isDebugEnabled()) { int count = ret == null ? 0 : ret.size(); LOG.debug(String.format("<== filterListCmdObjects: count[%d], ret[%s]", count, ret)); } return ret; }
From source file:org.apache.ranger.authorization.hive.authorizer.RangerHiveAuthorizer.java
License:Apache License
private String getRowFilterExpression(HiveAuthzContext context, String databaseName, String tableOrViewName) throws SemanticException { UserGroupInformation ugi = getCurrentUserGroupInfo(); if (ugi == null) { throw new SemanticException("user information not available"); }//w w w. j a va2s . c o m if (LOG.isDebugEnabled()) { LOG.debug("==> getRowFilterExpression(" + databaseName + ", " + tableOrViewName + ")"); } String ret = null; RangerHiveAuditHandler auditHandler = new RangerHiveAuditHandler(); try { HiveAuthzSessionContext sessionContext = getHiveAuthzSessionContext(); String user = ugi.getShortUserName(); Set<String> groups = Sets.newHashSet(ugi.getGroupNames()); HiveObjectType objectType = HiveObjectType.TABLE; RangerHiveResource resource = new RangerHiveResource(objectType, databaseName, tableOrViewName); RangerHiveAccessRequest request = new RangerHiveAccessRequest(resource, user, groups, objectType.name(), HiveAccessType.SELECT, context, sessionContext); RangerRowFilterResult result = hivePlugin.evalRowFilterPolicies(request, auditHandler); if (isRowFilterEnabled(result)) { ret = result.getFilterExpr(); } } finally { auditHandler.flushAudit(); } if (LOG.isDebugEnabled()) { LOG.debug("<== getRowFilterExpression(" + databaseName + ", " + tableOrViewName + "): " + ret); } return ret; }
From source file:org.apache.ranger.authorization.hive.authorizer.RangerHiveAuthorizer.java
License:Apache License
private String getCellValueTransformer(HiveAuthzContext context, String databaseName, String tableOrViewName, String columnName) throws SemanticException { UserGroupInformation ugi = getCurrentUserGroupInfo(); if (ugi == null) { throw new SemanticException("user information not available"); }/*from w ww. j a v a 2s. co m*/ if (LOG.isDebugEnabled()) { LOG.debug("==> getCellValueTransformer(" + databaseName + ", " + tableOrViewName + ", " + columnName + ")"); } String ret = columnName; RangerHiveAuditHandler auditHandler = new RangerHiveAuditHandler(); try { HiveAuthzSessionContext sessionContext = getHiveAuthzSessionContext(); String user = ugi.getShortUserName(); Set<String> groups = Sets.newHashSet(ugi.getGroupNames()); HiveObjectType objectType = HiveObjectType.COLUMN; RangerHiveResource resource = new RangerHiveResource(objectType, databaseName, tableOrViewName, columnName); RangerHiveAccessRequest request = new RangerHiveAccessRequest(resource, user, groups, objectType.name(), HiveAccessType.SELECT, context, sessionContext); RangerDataMaskResult result = hivePlugin.evalDataMaskPolicies(request, auditHandler); if (isDataMaskEnabled(result)) { String maskType = result.getMaskType(); RangerDataMaskTypeDef maskTypeDef = result.getMaskTypeDef(); String transformer = null; if (maskTypeDef != null) { transformer = maskTypeDef.getTransformer(); } if (StringUtils.equalsIgnoreCase(maskType, MASK_TYPE_NULL)) { ret = "NULL"; } else if (StringUtils.equalsIgnoreCase(maskType, MASK_TYPE_CUSTOM)) { String maskedValue = result.getMaskedValue(); if (maskedValue == null) { ret = "NULL"; } else { ret = maskedValue.replace("{col}", columnName); } } else if (StringUtils.isNotEmpty(transformer)) { ret = transformer.replace("{col}", columnName); } /* String maskCondition = result.getMaskCondition(); if(StringUtils.isNotEmpty(maskCondition)) { ret = "if(" + maskCondition + ", " + ret + ", " + columnName + ")"; } */ } } finally { auditHandler.flushAudit(); } if (LOG.isDebugEnabled()) { LOG.debug("<== getCellValueTransformer(" + databaseName + ", " + tableOrViewName + ", " + columnName + "): " + ret); } return ret; }
From source file:org.apache.ranger.authorization.hive.authorizer.RangerHiveAuthorizer.java
License:Apache License
private String getGrantorUsername(HivePrincipal grantorPrincipal) { String grantor = grantorPrincipal != null ? grantorPrincipal.getName() : null; if (StringUtil.isEmpty(grantor)) { UserGroupInformation ugi = this.getCurrentUserGroupInfo(); grantor = ugi != null ? ugi.getShortUserName() : null; }/*from w w w . j a v a 2s. c om*/ return grantor; }
From source file:org.apache.ranger.authorization.storm.authorizer.RangerStormAuthorizer.java
License:Apache License
/** * permit() method is invoked for each incoming Thrift request. * @param context request context includes info about * @param operation operation name/*w w w .j ava 2 s . co m*/ * @param topology_storm configuration of targeted topology * @return true if the request is authorized, false if reject */ @Override public boolean permit(ReqContext aRequestContext, String aOperationName, Map aTopologyConfigMap) { boolean accessAllowed = false; boolean isAuditEnabled = false; String topologyName = null; try { topologyName = (aTopologyConfigMap == null ? "" : (String) aTopologyConfigMap.get(Config.TOPOLOGY_NAME)); if (LOG.isDebugEnabled()) { LOG.debug("[req " + aRequestContext.requestID() + "] Access " + " from: [" + aRequestContext.remoteAddress() + "]" + " user: [" + aRequestContext.principal() + "]," + " op: [" + aOperationName + "]," + "topology: [" + topologyName + "]"); if (aTopologyConfigMap != null) { for (Object keyObj : aTopologyConfigMap.keySet()) { Object valObj = aTopologyConfigMap.get(keyObj); LOG.debug("TOPOLOGY CONFIG MAP [" + keyObj + "] => [" + valObj + "]"); } } else { LOG.debug("TOPOLOGY CONFIG MAP is passed as null."); } } if (noAuthzOperations.contains(aOperationName)) { accessAllowed = true; } else if (plugin == null) { LOG.info("Ranger plugin not initialized yet! Skipping authorization; allowedFlag => [" + accessAllowed + "], Audit Enabled:" + isAuditEnabled); } else { String userName = null; String[] groups = null; Principal user = aRequestContext.principal(); if (user != null) { userName = user.getName(); if (userName != null) { UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userName); userName = ugi.getShortUserName(); groups = ugi.getGroupNames(); if (LOG.isDebugEnabled()) { LOG.debug("User found from principal [" + user.getName() + "] => user:[" + userName + "], groups:[" + StringUtil.toString(groups) + "]"); } } } if (userName != null) { String clientIp = (aRequestContext.remoteAddress() == null ? null : aRequestContext.remoteAddress().getHostAddress()); RangerAccessRequest accessRequest = plugin.buildAccessRequest(userName, groups, clientIp, topologyName, aOperationName); RangerAccessResult result = plugin.isAccessAllowed(accessRequest); accessAllowed = result != null && result.getIsAllowed(); isAuditEnabled = result != null && result.getIsAudited(); if (LOG.isDebugEnabled()) { LOG.debug("User found from principal [" + userName + "], groups [" + StringUtil.toString(groups) + "]: verifying using [" + plugin.getClass().getName() + "], allowedFlag => [" + accessAllowed + "], Audit Enabled:" + isAuditEnabled); } } else { LOG.info("NULL User found from principal [" + user + "]: Skipping authorization; allowedFlag => [" + accessAllowed + "], Audit Enabled:" + isAuditEnabled); } } } catch (Throwable t) { LOG.error("RangerStormAuthorizer found this exception", t); } finally { if (LOG.isDebugEnabled()) { LOG.debug("[req " + aRequestContext.requestID() + "] Access " + " from: [" + aRequestContext.remoteAddress() + "]" + " user: [" + aRequestContext.principal() + "]," + " op: [" + aOperationName + "]," + "topology: [" + topologyName + "] => returns [" + accessAllowed + "], Audit Enabled:" + isAuditEnabled); } } return accessAllowed; }
From source file:org.apache.sentry.cli.tools.PermissionsMigrationToolCommon.java
License:Apache License
private void migrateSentryServiceConfig() throws Exception { Configuration conf = getSentryConf(); String component = getComponent(conf); String serviceName = getServiceName(conf); GenericPrivilegeConverter converter = new GenericPrivilegeConverter(component, serviceName, false); // instantiate a client for sentry service. This sets the ugi, so must // be done before getting the ugi below. try (SentryGenericServiceClient client = SentryGenericServiceClientFactory.create(getSentryConf())) { UserGroupInformation ugi = UserGroupInformation.getLoginUser(); String requestorName = ugi.getShortUserName(); for (TSentryRole r : client.listAllRoles(requestorName, component)) { for (TSentryPrivilege p : client.listAllPrivilegesByRoleName(requestorName, r.getRoleName(), component, serviceName)) { String privilegeStr = converter.toString(p); Collection<String> privileges = Collections.singleton(privilegeStr); Collection<String> migrated = transformPrivileges(privileges); if (!migrated.isEmpty()) { LOGGER.info("{} For role {} migrating privileges from {} to {}", getDryRunMessage(), r.getRoleName(), privileges, migrated); /*//from w w w.j a v a 2 s. c o m * Note that it is not possible to provide transactional (all-or-nothing) behavior for these configuration * changes since the Sentry client/server protocol does not support. e.g. under certain failure conditions * like crash of Sentry server or network disconnect between client/server, it is possible that the migration * can not complete but can also not be rolled back. Hence this migration tool relies on the fact that privilege * grant/revoke operations are idempotent and hence re-execution of the migration tool will fix any inconsistency * due to such failures. **/ boolean originalPermPresent = false; for (String perm : migrated) { if (perm.equalsIgnoreCase(privilegeStr)) { originalPermPresent = true; continue; } TSentryPrivilege x = converter.fromString(perm); LOGGER.info("{} GRANT permission {}", getDryRunMessage(), perm); if (!dryRun) { client.grantPrivilege(requestorName, r.getRoleName(), component, x); } } // Revoke old permission (only if not part of migrated permissions) if (!originalPermPresent) { LOGGER.info("{} REVOKE permission {}", getDryRunMessage(), privilegeStr); if (!dryRun) { client.revokePrivilege(requestorName, r.getRoleName(), component, p); } } } } } } }
From source file:org.apache.sentry.cli.tools.SentryConfigToolIndexer.java
License:Apache License
/** * Processes the necessary command based on the arguments parsed earlier. * @throws Exception//from w w w . ja va2 s . c o m */ public void run() throws Exception { String component = HBASE_INDEXER; Configuration conf = getSentryConf(); String service = conf.get(ApiConstants.ClientConfig.SERVICE_NAME, getServiceName()); if (service == null) { throw new IllegalArgumentException( "Service was not defined. Please, use -s command option, or sentry.provider.backend.generic.service-name configuration entry."); } LOGGER.info(String.format("Context: component=%s, service=%s", component, service)); // instantiate a solr client for sentry service. This sets the ugi, so must // be done before getting the ugi below. try (SentryGenericServiceClient client = SentryGenericServiceClientFactory.create(conf)) { UserGroupInformation ugi = UserGroupInformation.getLoginUser(); String requestorName = ugi.getShortUserName(); convertINIToSentryServiceCmds(component, service, requestorName, conf, client, getPolicyFile(), getValidate(), getImportPolicy(), getCheckCompat()); } }
From source file:org.apache.sentry.cli.tools.SentryConfigToolSolr.java
License:Apache License
@Override public void run() throws Exception { String component = "SOLR"; Configuration conf = getSentryConf(); String service = conf.get(SOLR_SERVICE_NAME, "service1"); // instantiate a solr client for sentry service. This sets the ugi, so must // be done before getting the ugi below. try (SentryGenericServiceClient client = SentryGenericServiceClientFactory.create(conf)) { UserGroupInformation ugi = UserGroupInformation.getLoginUser(); String requestorName = ugi.getShortUserName(); convertINIToSentryServiceCmds(component, service, requestorName, conf, client, getPolicyFile(), getValidate(), getImportPolicy(), getCheckCompat()); }// ww w.j av a 2s . com }
From source file:org.apache.sentry.cli.tools.SentryShellGeneric.java
License:Apache License
@Override public void run() throws Exception { String component = getComponent(); Configuration conf = getSentryConf(); String service = getService(conf); try (SentryGenericServiceClient client = SentryGenericServiceClientFactory.create(conf)) { UserGroupInformation ugi = UserGroupInformation.getLoginUser(); String requestorName = ugi.getShortUserName(); TSentryPrivilegeConverter converter = getPrivilegeConverter(component, service); ShellCommand command = new GenericShellCommand(client, component, service, converter); // check the requestor name if (StringUtils.isEmpty(requestorName)) { // The exception message will be recorded in log file. throw new Exception("The requestor name is empty."); }//ww w .ja v a 2 s . c o m if (isCreateRole) { command.createRole(requestorName, roleName); } else if (isDropRole) { command.dropRole(requestorName, roleName); } else if (isAddRoleGroup) { Set<String> groups = Sets.newHashSet(groupName.split(SentryShellCommon.GROUP_SPLIT_CHAR)); command.grantRoleToGroups(requestorName, roleName, groups); } else if (isDeleteRoleGroup) { Set<String> groups = Sets.newHashSet(groupName.split(SentryShellCommon.GROUP_SPLIT_CHAR)); command.revokeRoleFromGroups(requestorName, roleName, groups); } else if (isGrantPrivilegeRole) { command.grantPrivilegeToRole(requestorName, roleName, privilegeStr); } else if (isRevokePrivilegeRole) { command.revokePrivilegeFromRole(requestorName, roleName, privilegeStr); } else if (isListRole) { List<String> roles = command.listRoles(requestorName, groupName); for (String role : roles) { System.out.println(role); } } else if (isListPrivilege) { List<String> privileges = command.listPrivileges(requestorName, roleName); for (String privilege : privileges) { System.out.println(privilege); } } else if (isListGroup) { List<String> groups = command.listGroupRoles(requestorName); for (String group : groups) { System.out.println(group); } } } }
From source file:org.apache.sentry.cli.tools.SentryShellHive.java
License:Apache License
public void run() throws Exception { try (SentryPolicyServiceClient client = SentryServiceClientFactory.create(getSentryConf())) { UserGroupInformation ugi = UserGroupInformation.getLoginUser(); String requestorName = ugi.getShortUserName(); ShellCommand command = new HiveShellCommand(client); // check the requestor name if (StringUtils.isEmpty(requestorName)) { // The exception message will be recorded in the log file. throw new Exception("The requestor name is empty."); }//ww w . ja v a2 s .c o m if (isCreateRole) { command.createRole(requestorName, roleName); } else if (isDropRole) { command.dropRole(requestorName, roleName); } else if (isAddRoleGroup) { Set<String> groups = Sets.newHashSet(groupName.split(SentryShellCommon.GROUP_SPLIT_CHAR)); command.grantRoleToGroups(requestorName, roleName, groups); } else if (isDeleteRoleGroup) { Set<String> groups = Sets.newHashSet(groupName.split(SentryShellCommon.GROUP_SPLIT_CHAR)); command.revokeRoleFromGroups(requestorName, roleName, groups); } else if (isGrantPrivilegeRole) { command.grantPrivilegeToRole(requestorName, roleName, privilegeStr); } else if (isRevokePrivilegeRole) { command.revokePrivilegeFromRole(requestorName, roleName, privilegeStr); } else if (isListRole) { List<String> roles = command.listRoles(requestorName, groupName); for (String role : roles) { System.out.println(role); } } else if (isListPrivilege) { List<String> privileges = command.listPrivileges(requestorName, roleName); for (String privilege : privileges) { System.out.println(privilege); } } else if (isListGroup) { List<String> groups = command.listGroupRoles(requestorName); for (String group : groups) { System.out.println(group); } } } }