org.apache.hadoop.hive.ql.security.authorization.plugin.HiveOperationType Java Examples

The following examples show how to use org.apache.hadoop.hive.ql.security.authorization.plugin.HiveOperationType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 6 votes vote down vote up
private boolean isBlockAccessIfRowfilterColumnMaskSpecified(HiveOperationType hiveOpType, RangerHiveAccessRequest request) {
	boolean            ret      = false;
	RangerHiveResource resource = (RangerHiveResource)request.getResource();
	HiveObjectType     objType  = resource.getObjectType();

	if(objType == HiveObjectType.TABLE || objType == HiveObjectType.VIEW || objType == HiveObjectType.COLUMN) {
		ret = hiveOpType == HiveOperationType.EXPORT;

		if(!ret) {
			if (request.getHiveAccessType() == HiveAccessType.UPDATE && hivePlugin.BlockUpdateIfRowfilterColumnMaskSpecified) {
				ret = true;
			}
		}
	}

	if(LOG.isDebugEnabled()) {
		LOG.debug("isBlockAccessIfRowfilterColumnMaskSpecified(" + hiveOpType + ", " + request + "): " + ret);
	}

	return ret;
}
 
Example #2
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 6 votes vote down vote up
private String buildPathForException(String path, HiveOperationType hiveOpType) {
	String ret  	= path;
	int endIndex 	= 0;
	switch(hiveOpType) {
		case DESCTABLE:
			ret = path + "/*";
			break;
		case QUERY:
			try {
				endIndex = StringUtils.ordinalIndexOf(path, "/", 2);
				ret = path.substring(0,endIndex) + "/*";
			} catch( Exception e) {
				//omit and return the path.Log error only in debug.
				if(LOG.isDebugEnabled()) {
					LOG.debug("RangerHiveAuthorizer.buildPathForException(): Error while creating exception message ", e);
				}
			}
			break;
	}
	return ret;
}
 
Example #3
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 6 votes vote down vote up
private RangerHiveAccessRequest createRangerHiveAccessRequest(String userOrGrantor, List<String> roleUsers, HiveOperationType hiveOperationType, HiveAccessType accessType, List<String> roleNames) {
	RangerHiveAccessRequest ret = null;

	HiveAuthzContext.Builder builder	   = new HiveAuthzContext.Builder();
	String					 roleNameStr   = createRoleString(roleNames);
	String 					 userNameStr   = createUserString(roleUsers);
	String					 commandString = getCommandString(hiveOperationType, userNameStr, roleNameStr);
	String 					 cmdStr		   = (commandString != null) ? commandString : StringUtils.EMPTY;
	builder.setCommandString(cmdStr);
	HiveAuthzContext 		hiveAuthzContext = builder.build();

	RangerHiveResource rangerHiveResource	= new RangerHiveResource(HiveObjectType.GLOBAL,"*");
	ret = new RangerHiveAccessRequest(rangerHiveResource, userOrGrantor, null, null, hiveOperationType, accessType, hiveAuthzContext, null);
	ret.setClusterName(hivePlugin.getClusterName());
	ret.setAction(hiveOperationType.name());
	ret.setClientIPAddress(getRemoteIp());
	ret.setRemoteIPAddress(getRemoteIp());

	return ret;
}
 
Example #4
Source File: TestAllHiveOperationInRanger.java    From ranger with Apache License 2.0 6 votes vote down vote up
/**
 * test that all enums in {@link HiveOperationType} match one map entry in
 * RangerHiveOperationType Map
 */
@Test
public void checkHiveOperationTypeMatch() {

    List<String> rangerHiveOperationList = new ArrayList<>();
    for (RangerHiveOperationType rangerHiveOperationType : RangerHiveOperationType.values()) {
        String rangerOpType = rangerHiveOperationType.name();
        rangerHiveOperationList.add(rangerOpType);
    }
    for (HiveOperationType operationType : HiveOperationType.values()) {
        String hiveOperationType = operationType.name();
        if (!rangerHiveOperationList.contains(hiveOperationType)) {
            fail("Unable to find corresponding HiveOperationType in RangerHiveOperation map.Please check this new operation.. "
                    + operationType);
        }
    }
    assert(true);
}
 
Example #5
Source File: HiveAuthorizationHelper.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Check authorization for "SHOW TABLES" command in given Hive db. A {@link HiveAccessControlException} is thrown
 * for illegal access.
 * @param dbName
 */
public void authorizeShowTables(final String dbName) throws HiveAccessControlException {
  if (!authzEnabled) {
    return;
  }

  final HivePrivilegeObject toRead = new HivePrivilegeObject(HivePrivilegeObjectType.DATABASE, dbName, null);

  authorize(HiveOperationType.SHOWTABLES, ImmutableList.of(toRead), Collections.<HivePrivilegeObject> emptyList(), "SHOW TABLES");
}
 
Example #6
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
private String toString(HiveOperationType         hiveOpType,
						List<HivePrivilegeObject> inputHObjs,
						List<HivePrivilegeObject> outputHObjs,
						HiveAuthzContext          context,
						HiveAuthzSessionContext   sessionContext) {
	StringBuilder sb = new StringBuilder();
	
	sb.append("'checkPrivileges':{");
	sb.append("'hiveOpType':").append(hiveOpType);

	sb.append(", 'inputHObjs':[");
	toString(inputHObjs, sb);
	sb.append("]");

	sb.append(", 'outputHObjs':[");
	toString(outputHObjs, sb);
	sb.append("]");

	sb.append(", 'context':{");
	sb.append("'clientType':").append(sessionContext == null ? null : sessionContext.getClientType());
	sb.append(", 'commandString':").append(context == null ? "null" : context.getCommandString());
	sb.append(", 'ipAddress':").append(context == null ? "null" : context.getIpAddress());
	sb.append(", 'forwardedAddresses':").append(context == null ? "null" : StringUtils.join(context.getForwardedAddresses(), ", "));
	sb.append(", 'sessionString':").append(sessionContext == null ? "null" : sessionContext.getSessionString());
	sb.append("}");

	sb.append(", 'user':").append(this.getCurrentUserGroupInfo().getUserName());
	sb.append(", 'groups':[").append(StringUtil.toString(this.getCurrentUserGroupInfo().getGroupNames())).append("]");
	sb.append("}");

	return sb.toString();
}
 
Example #7
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
private void handleDfsCommand(HiveOperationType         hiveOpType,
							  List<HivePrivilegeObject> inputHObjs,
							  String                    user,
							  RangerHiveAuditHandler    auditHandler)
      throws HiveAuthzPluginException, HiveAccessControlException {

	String dfsCommandParams = null;

	if(inputHObjs != null) {
		for(HivePrivilegeObject hiveObj : inputHObjs) {
			if(hiveObj.getType() == HivePrivilegeObjectType.COMMAND_PARAMS) {
				dfsCommandParams = StringUtil.toString(hiveObj.getCommandParams());

				if(! StringUtil.isEmpty(dfsCommandParams)) {
					break;
				}
			}
		}
	}

	int    serviceType = -1;
	String serviceName = null;

	if(hivePlugin != null) {
		serviceType = hivePlugin.getServiceDefId();
		serviceName = hivePlugin.getServiceName();
	}

	auditHandler.logAuditEventForDfs(user, dfsCommandParams, false, serviceType, serviceName);

	throw new HiveAccessControlException(String.format("Permission denied: user [%s] does not have privilege for [%s] command",
										 user, hiveOpType.name()));
}
 
Example #8
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
private String getCommandString(HiveOperationType hiveOperationType, String user, String roleName) {
	String ret = StringUtils.EMPTY;

	switch (hiveOperationType) {
		case CREATEROLE:
			ret = String.format(CMD_CREATE_ROLE, roleName);
			break;
		case DROPROLE:
			ret = String.format(CMD_DROP_ROLE, roleName);
			break;
		case SHOW_ROLES:
			ret = CMD_SHOW_ROLES;
			break;
		case SHOW_ROLE_GRANT:
			ret = String.format(CMD_SHOW_ROLE_GRANT, user);
			break;
		case SHOW_ROLE_PRINCIPALS:
			ret = String.format(CMD_SHOW_PRINCIPALS, roleName);
			break;
		case GRANT_ROLE:
			ret = String.format(CMD_GRANT_ROLE, roleName, user);
			break;
		case REVOKE_ROLE:
			ret = String.format(CMD_REVOKE_ROLE, user, roleName);
			break;
	}

	return ret;
}
 
Example #9
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
/**
 * Revoke privileges for principals on the object
 * @param hivePrincipals
 * @param hivePrivileges
 * @param hivePrivObject
 * @param grantorPrincipal
 * @param grantOption
 * @throws HiveAuthzPluginException
 * @throws HiveAccessControlException
 */
@Override
public void revokePrivileges(List<HivePrincipal> hivePrincipals,
							 List<HivePrivilege> hivePrivileges,
							 HivePrivilegeObject hivePrivObject,
							 HivePrincipal       grantorPrincipal,
							 boolean             grantOption)
									 throws HiveAuthzPluginException, HiveAccessControlException {
	if(! RangerHivePlugin.UpdateXaPoliciesOnGrantRevoke) {
		throw new HiveAuthzPluginException("GRANT/REVOKE not supported in Ranger HiveAuthorizer. Please use Ranger Security Admin to setup access control.");
	}

	RangerHiveAuditHandler auditHandler = new RangerHiveAuditHandler();

	try {
		List<HivePrivilegeObject> outputs = new ArrayList<>(Arrays.asList(hivePrivObject));
		RangerHiveResource resource = getHiveResource(HiveOperationType.REVOKE_PRIVILEGE, hivePrivObject, null, outputs);
		GrantRevokeRequest request  = createGrantRevokeData(resource, hivePrincipals, hivePrivileges, grantorPrincipal, grantOption);

		LOG.info("revokePrivileges(): " + request);
		if(LOG.isDebugEnabled()) {
			LOG.debug("revokePrivileges(): " + request);
		}

		hivePlugin.revokeAccess(request, auditHandler);
	} catch(Exception excp) {
		throw new HiveAccessControlException(excp);
	} finally {
		auditHandler.flushAudit();
	}
}
 
Example #10
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
/**
 * Grant privileges for principals on the object
 * @param hivePrincipals
 * @param hivePrivileges
 * @param hivePrivObject
 * @param grantorPrincipal
 * @param grantOption
 * @throws HiveAuthzPluginException
 * @throws HiveAccessControlException
 */
@Override
public void grantPrivileges(List<HivePrincipal> hivePrincipals,
							List<HivePrivilege> hivePrivileges,
							HivePrivilegeObject hivePrivObject,
							HivePrincipal       grantorPrincipal,
							boolean             grantOption)
									throws HiveAuthzPluginException, HiveAccessControlException {
	if (LOG.isDebugEnabled()) {
			LOG.debug("grantPrivileges() => HivePrivilegeObject:" + toString(hivePrivObject, new StringBuilder()) + "grantorPrincipal: " + grantorPrincipal + "hivePrincipals" + hivePrincipals + "hivePrivileges" + hivePrivileges);
	}

	if(! RangerHivePlugin.UpdateXaPoliciesOnGrantRevoke) {
		throw new HiveAuthzPluginException("GRANT/REVOKE not supported in Ranger HiveAuthorizer. Please use Ranger Security Admin to setup access control.");
	}

	RangerHiveAuditHandler auditHandler = new RangerHiveAuditHandler();

	try {
		List<HivePrivilegeObject> outputs = new ArrayList<>(Arrays.asList(hivePrivObject));
		RangerHiveResource resource = getHiveResource(HiveOperationType.GRANT_PRIVILEGE, hivePrivObject, null, outputs);
		GrantRevokeRequest request  = createGrantRevokeData(resource, hivePrincipals, hivePrivileges, grantorPrincipal, grantOption);

		LOG.info("grantPrivileges(): " + request);
		if(LOG.isDebugEnabled()) {
			LOG.debug("grantPrivileges(): " + request);
		}

		hivePlugin.grantAccess(request, auditHandler);
	} catch(Exception excp) {
		throw new HiveAccessControlException(excp);
	} finally {
		auditHandler.flushAudit();
	}
}
 
Example #11
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getAllRoles()
		throws HiveAuthzPluginException, HiveAccessControlException {
	LOG.debug("RangerHiveAuthorizer.getAllRoles()");
	boolean	               result       = false;
	RangerHiveAuditHandler auditHandler = new RangerHiveAuditHandler();
	UserGroupInformation ugi = getCurrentUserGroupInfo();

	if(ugi == null) {
		throw new HiveAccessControlException("Permission denied: user information not available");
	}
	List<String> ret = null;

	String currentUserName = ugi.getShortUserName();
	List<String> userNames = Arrays.asList(currentUserName);

	try {
		if(LOG.isDebugEnabled()) {
			LOG.debug("<== getAllRoles()");
		}

		ret = hivePlugin.getAllRoles(ugi.getShortUserName(), auditHandler);
		result = true;

	} catch(Exception excp) {
		throw new HiveAuthzPluginException(excp);
	} finally {
		RangerAccessResult accessResult = createAuditEvent(hivePlugin, currentUserName, userNames, HiveOperationType.SHOW_ROLES, HiveAccessType.SELECT, null, result);
		auditHandler.processResult(accessResult);
		auditHandler.flushAudit();
	}

	return ret;
}
 
Example #12
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getCurrentRoleNames() throws HiveAuthzPluginException {
	if (LOG.isDebugEnabled()) {
		LOG.debug("RangerHiveAuthorizer.getCurrentRoleNames()");
	}
	UserGroupInformation ugi = getCurrentUserGroupInfo();
	boolean result = false;
	if (ugi == null) {
		throw new HiveAuthzPluginException("User information not available");
	}
	List<String> ret = new ArrayList<String>();
	String user = ugi.getShortUserName();
	List<String> userNames = Arrays.asList(user);
	RangerHiveAuditHandler auditHandler = new RangerHiveAuditHandler();
	try {
		if (LOG.isDebugEnabled()) {
			LOG.debug("<== getCurrentRoleNames() for user " + user);
		}
		for (String role : getCurrentRoles()) {
			ret.add(role);
		}
		result = true;
	} catch (Exception excp) {
		throw new HiveAuthzPluginException(excp);
	} finally {
		RangerAccessResult accessResult = createAuditEvent(hivePlugin, user, userNames,
				HiveOperationType.SHOW_ROLES, HiveAccessType.SELECT, ret, result);
		auditHandler.processResult(accessResult);
		auditHandler.flushAudit();
	}
	return ret;
}
 
Example #13
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public void dropRole(String roleName)
		throws HiveAuthzPluginException, HiveAccessControlException {
	if(LOG.isDebugEnabled()) {
		LOG.debug("RangerHiveAuthorizer.dropRole()");
	}

	RangerHiveAuditHandler auditHandler = new RangerHiveAuditHandler();

	UserGroupInformation ugi       = getCurrentUserGroupInfo();
	boolean	             result    = false;
	List<String>	     roleNames = Arrays.asList(roleName);

	if(ugi == null) {
		throw new HiveAccessControlException("Permission denied: user information not available");
	}

	if (RESERVED_ROLE_NAMES.contains(roleName.trim().toUpperCase())) {
		throw new HiveAuthzPluginException("Role name cannot be one of the reserved roles: " +
				RESERVED_ROLE_NAMES);
	}

	String currentUserName = ugi.getShortUserName();
	List<String> userNames = Arrays.asList(currentUserName);

	try {
		if(LOG.isDebugEnabled()) {
			LOG.debug("<== dropRole(): " + roleName);
		}
		hivePlugin.dropRole(currentUserName, roleName, auditHandler);
		result = true;
	} catch(Exception excp) {
		throw new HiveAccessControlException(excp);
	} finally {
		RangerAccessResult accessResult = createAuditEvent(hivePlugin, currentUserName, userNames, HiveOperationType.DROPROLE, HiveAccessType.DROP, roleNames, result);
		auditHandler.processResult(accessResult);
		auditHandler.flushAudit();
	}

}
 
Example #14
Source File: HiveAuthorizationHelper.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Check authorization for "SHOW DATABASES" command. A {@link HiveAccessControlException} is thrown
 * for illegal access.
 */
public void authorizeShowDatabases() throws HiveAccessControlException {
  if (!authzEnabled) {
    return;
  }

  authorize(HiveOperationType.SHOWDATABASES, Collections.<HivePrivilegeObject> emptyList(), Collections.<HivePrivilegeObject> emptyList(), "SHOW DATABASES");
}
 
Example #15
Source File: RangerHiveAccessRequest.java    From ranger with Apache License 2.0 5 votes vote down vote up
public RangerHiveAccessRequest(RangerHiveResource      resource,
		   String                  user,
		   Set<String>             userGroups,
		   Set<String>             userRoles,
		   HiveOperationType       hiveOpType,
		   HiveAccessType          accessType,
		   HiveAuthzContext        context,
		   HiveAuthzSessionContext sessionContext) {
	this(resource, user, userGroups, userRoles, hiveOpType.name(), accessType, context, sessionContext);
}
 
Example #16
Source File: HiveAuthorizationHelper.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Check authorization for "READ TABLE" for given db.table. A {@link HiveAccessControlException} is thrown
 * for illegal access.
 * @param dbName
 * @param tableName
 */
public void authorizeReadTable(final String dbName, final String tableName) throws HiveAccessControlException {
  if (!authzEnabled) {
    return;
  }

  HivePrivilegeObject toRead = new HivePrivilegeObject(HivePrivilegeObjectType.TABLE_OR_VIEW, dbName, tableName);
  authorize(HiveOperationType.QUERY, ImmutableList.of(toRead), Collections.<HivePrivilegeObject> emptyList(), "READ TABLE");
}
 
Example #17
Source File: DefaultSentryValidator.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
private List<HivePrivilegeObject> filterShowTables(List<HivePrivilegeObject> listObjs,
    String userName, HiveAuthzBinding hiveAuthzBinding) {
  List<HivePrivilegeObject> filteredResult = new ArrayList<HivePrivilegeObject>();
  Subject subject = new Subject(userName);
  HiveAuthzPrivileges tableMetaDataPrivilege =
      new HiveAuthzPrivileges.AuthzPrivilegeBuilder()
          .addInputObjectPriviledge(AuthorizableType.Column,
              EnumSet.of(DBModelAction.SELECT, DBModelAction.INSERT))
          .setOperationScope(HiveOperationScope.TABLE)
          .setOperationType(
              org.apache.sentry.binding.hive.authz.HiveAuthzPrivileges.HiveOperationType.INFO)
          .build();

  for (HivePrivilegeObject obj : listObjs) {
    // if user has privileges on table, add to filtered list, else discard
    Table table = new Table(obj.getObjectName());
    Database database;
    database = new Database(obj.getDbname());

    List<List<DBModelAuthorizable>> inputHierarchy = new ArrayList<List<DBModelAuthorizable>>();
    List<List<DBModelAuthorizable>> outputHierarchy = new ArrayList<List<DBModelAuthorizable>>();
    List<DBModelAuthorizable> externalAuthorizableHierarchy =
        new ArrayList<DBModelAuthorizable>();
    externalAuthorizableHierarchy.add(hiveAuthzBinding.getAuthServer());
    externalAuthorizableHierarchy.add(database);
    externalAuthorizableHierarchy.add(table);
    externalAuthorizableHierarchy.add(Column.ALL);
    inputHierarchy.add(externalAuthorizableHierarchy);

    try {
      hiveAuthzBinding.authorize(HiveOperation.SHOWTABLES, tableMetaDataPrivilege, subject,
          inputHierarchy, outputHierarchy);
      filteredResult.add(obj);
    } catch (AuthorizationException e) {
      // squash the exception, user doesn't have privileges, so the table is
      // not added to
      // filtered list.
    }
  }
  return filteredResult;
}
 
Example #18
Source File: DefaultSentryValidator.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
private List<HivePrivilegeObject> filterShowDatabases(List<HivePrivilegeObject> listObjs,
    String userName, HiveAuthzBinding hiveAuthzBinding) {
  List<HivePrivilegeObject> filteredResult = new ArrayList<HivePrivilegeObject>();
  Subject subject = new Subject(userName);
  HiveAuthzPrivileges anyPrivilege =
      new HiveAuthzPrivileges.AuthzPrivilegeBuilder()
          .addInputObjectPriviledge(
              AuthorizableType.Column,
              EnumSet.of(DBModelAction.SELECT, DBModelAction.INSERT, DBModelAction.ALTER,
                  DBModelAction.CREATE, DBModelAction.DROP, DBModelAction.INDEX,
                  DBModelAction.LOCK))
          .setOperationScope(HiveOperationScope.CONNECT)
          .setOperationType(
              org.apache.sentry.binding.hive.authz.HiveAuthzPrivileges.HiveOperationType.QUERY)
          .build();

  for (HivePrivilegeObject obj : listObjs) {
    // if user has privileges on database, add to filtered list, else discard
    Database database = null;

    // if default is not restricted, continue
    if (DEFAULT_DATABASE_NAME.equalsIgnoreCase(obj.getObjectName())
        && "false".equalsIgnoreCase(hiveAuthzBinding.getAuthzConf().get(
            HiveAuthzConf.AuthzConfVars.AUTHZ_RESTRICT_DEFAULT_DB.getVar(), "false"))) {
      filteredResult.add(obj);
      continue;
    }

    database = new Database(obj.getObjectName());

    List<List<DBModelAuthorizable>> inputHierarchy = new ArrayList<List<DBModelAuthorizable>>();
    List<List<DBModelAuthorizable>> outputHierarchy = new ArrayList<List<DBModelAuthorizable>>();
    List<DBModelAuthorizable> externalAuthorizableHierarchy =
        new ArrayList<DBModelAuthorizable>();
    externalAuthorizableHierarchy.add(hiveAuthzBinding.getAuthServer());
    externalAuthorizableHierarchy.add(database);
    externalAuthorizableHierarchy.add(Table.ALL);
    externalAuthorizableHierarchy.add(Column.ALL);
    inputHierarchy.add(externalAuthorizableHierarchy);

    try {
      hiveAuthzBinding.authorize(HiveOperation.SHOWDATABASES, anyPrivilege, subject,
          inputHierarchy, outputHierarchy);
      filteredResult.add(obj);
    } catch (AuthorizationException e) {
      // squash the exception, user doesn't have privileges, so the table is
      // not added to
      // filtered list.
    }
  }
  return filteredResult;
}
 
Example #19
Source File: SentryHiveAuthorizer.java    From incubator-sentry with Apache License 2.0 4 votes vote down vote up
@Override
public void checkPrivileges(HiveOperationType hiveOpType, List<HivePrivilegeObject> inputHObjs,
    List<HivePrivilegeObject> outputHObjs, HiveAuthzContext context)
    throws HiveAuthzPluginException, HiveAccessControlException {
  authValidator.checkPrivileges(hiveOpType, inputHObjs, outputHObjs, context);
}
 
Example #20
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 4 votes vote down vote up
private RangerAccessResult createAuditEvent(RangerHivePlugin hivePlugin, String userOrGrantor, List<String> roleUsers, HiveOperationType hiveOperationType, HiveAccessType accessType, List<String> roleNames, boolean result) {
	RangerHiveAccessRequest	rangerHiveAccessRequest	= createRangerHiveAccessRequest(userOrGrantor, roleUsers, hiveOperationType, accessType, roleNames);
	RangerAccessResult		accessResult 			= createRangerHiveAccessResult(hivePlugin, userOrGrantor, rangerHiveAccessRequest, result);
	return accessResult;
}
 
Example #21
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 4 votes vote down vote up
private HiveObjectType getObjectType(HivePrivilegeObject hiveObj, HiveOperationType hiveOpType) {
	HiveObjectType objType = HiveObjectType.NONE;
	String hiveOpTypeName  = hiveOpType.name().toLowerCase();

	if (hiveObj.getType() == null) {
		return HiveObjectType.DATABASE;
	}

	switch(hiveObj.getType()) {
		case DATABASE:
			objType = HiveObjectType.DATABASE;
		break;

		case PARTITION:
			objType = HiveObjectType.PARTITION;
		break;

		case TABLE_OR_VIEW:
			if(hiveOpTypeName.contains("index")) {
				objType = HiveObjectType.INDEX;
			} else if(! StringUtil.isEmpty(hiveObj.getColumns())) {
				objType = HiveObjectType.COLUMN;
			} else if(hiveOpTypeName.contains("view")) {
				objType = HiveObjectType.VIEW;
			} else {
				objType = HiveObjectType.TABLE;
			}
		break;

		case FUNCTION:
			objType = HiveObjectType.FUNCTION;
			if (isTempUDFOperation(hiveOpTypeName, hiveObj)) {
				objType = HiveObjectType.GLOBAL;
			}
		break;

		case DFS_URI:
		case LOCAL_URI:
               objType = HiveObjectType.URI;
           break;

		case COMMAND_PARAMS:
		case GLOBAL:
			if ( "add".equals(hiveOpTypeName) || "compile".equals(hiveOpTypeName)) {
				objType = HiveObjectType.GLOBAL;
			}
		break;

		case SERVICE_NAME:
			objType = HiveObjectType.SERVICE_NAME;
		break;

		case COLUMN:
			// Thejas: this value is unused in Hive; the case should not be hit.
		break;
	}

	return objType;
}
 
Example #22
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 4 votes vote down vote up
private RangerHiveResource getHiveResource(HiveOperationType   hiveOpType,
										   HivePrivilegeObject hiveObj,
										   List<HivePrivilegeObject> inputs,
										   List<HivePrivilegeObject> outputs) {
	RangerHiveResource ret = null;

	HiveObjectType objectType = getObjectType(hiveObj, hiveOpType);

	switch(objectType) {
		case DATABASE:
			ret = new RangerHiveResource(objectType, hiveObj.getDbname());
			/*
			if (!isCreateOperation(hiveOpType)) {
				ret.setOwnerUser(hiveObj.getOwnerName());
			}

			 */
		break;

		case TABLE:
		case VIEW:
		case FUNCTION:
			ret = new RangerHiveResource(objectType, hiveObj.getDbname(), hiveObj.getObjectName());
			// To suppress PMD violations
			if (LOG.isDebugEnabled()) {
				LOG.debug("Size of inputs = [" + (CollectionUtils.isNotEmpty(inputs) ? inputs.size() : 0) +
						", Size of outputs = [" + (CollectionUtils.isNotEmpty(outputs) ? outputs.size() : 0) + "]");
			}

			/*
			String ownerName = hiveObj.getOwnerName();

			if (isCreateOperation(hiveOpType)) {
				HivePrivilegeObject dbObject = getDatabaseObject(hiveObj.getDbname(), inputs, outputs);
				if (dbObject != null) {
					ownerName = dbObject.getOwnerName();
				}
			}

			ret.setOwnerUser(ownerName);

			 */

		break;

		case PARTITION:
		case INDEX:
			ret = new RangerHiveResource(objectType, hiveObj.getDbname(), hiveObj.getObjectName());
		break;

		case COLUMN:
			ret = new RangerHiveResource(objectType, hiveObj.getDbname(), hiveObj.getObjectName(), StringUtils.join(hiveObj.getColumns(), COLUMN_SEP));
			//ret.setOwnerUser(hiveObj.getOwnerName());
		break;

           case URI:
		case SERVICE_NAME:
			ret = new RangerHiveResource(objectType, hiveObj.getObjectName());
           break;

		case GLOBAL:
			ret = new RangerHiveResource(objectType,hiveObj.getObjectName());
		break;

		case NONE:
		break;
	}

	if (ret != null) {
		ret.setServiceDef(hivePlugin == null ? null : hivePlugin.getServiceDef());
	}

	return ret;
}
 
Example #23
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public void revokeRole(List<HivePrincipal> hivePrincipals, List<String> roles,
					   boolean grantOption, HivePrincipal grantorPrinc)
		throws HiveAuthzPluginException, HiveAccessControlException {
	LOG.debug("RangerHiveAuthorizerBase.revokeRole()");

	boolean result = false;

	RangerHiveAuditHandler auditHandler = new RangerHiveAuditHandler();

	String 		  grantorUserName = getGrantorUsername(grantorPrinc);
	List<String>  principals      = new ArrayList<>();

	try {
		GrantRevokeRoleRequest request  = new GrantRevokeRoleRequest();
		request.setGrantor(grantorUserName);
		request.setGrantorGroups(getGrantorGroupNames(grantorPrinc));
		Set<String> userList = new HashSet<>();
		Set<String> roleList = new HashSet<>();
		Set<String> groupList = new HashSet<>();
		for(HivePrincipal principal : hivePrincipals) {
			String principalName = null;
			switch(principal.getType()) {
				case USER:
					principalName = principal.getName();
					userList.add(principalName);
					principals.add("USER " + principalName);
					break;

				case GROUP:
					principalName = principal.getName();
					groupList.add(principalName);
					principals.add("GROUP " + principalName);
					break;
				case ROLE:
					principalName = principal.getName();
					roleList.add(principalName);
					principals.add("ROLE " + principalName);
					break;

				case UNKNOWN:
					break;
			}
		}

		request.setUsers(userList);
		request.setGroups(groupList);
		request.setRoles(roleList);
		request.setGrantOption(grantOption);
		request.setTargetRoles(new HashSet<>(roles));
		SessionState ss = SessionState.get();
		if(ss != null) {
			request.setClientIPAddress(ss.getUserIpAddress());
			request.setSessionId(ss.getSessionId());

			HiveConf hiveConf = ss.getConf();

			if(hiveConf != null) {
				request.setRequestData(hiveConf.get(HIVE_CONF_VAR_QUERY_STRING));
			}
		}

		HiveAuthzSessionContext sessionContext = getHiveAuthzSessionContext();
		if(sessionContext != null) {
			request.setClientType(sessionContext.getClientType() == null ? null : sessionContext.getClientType().toString());
		}

		LOG.info("revokeRole(): " + request);
		if(LOG.isDebugEnabled()) {
			LOG.debug("revokeRole(): " + request);
		}
		hivePlugin.revokeRole(request, auditHandler);
		result = true;
	} catch(Exception excp) {
		throw new HiveAccessControlException(excp);
	} finally {
		RangerAccessResult accessResult = createAuditEvent(hivePlugin, grantorUserName, principals, HiveOperationType.REVOKE_ROLE, HiveAccessType.ALTER, roles, result);
		auditHandler.processResult(accessResult);
		auditHandler.flushAudit();
	}
}
 
Example #24
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public void grantRole(List<HivePrincipal> hivePrincipals, List<String> roles,
					  boolean grantOption, HivePrincipal grantorPrinc)
		throws HiveAuthzPluginException, HiveAccessControlException {
	LOG.debug("RangerHiveAuthorizerBase.grantRole()");

	boolean	               result       = false;
	RangerHiveAuditHandler auditHandler = new RangerHiveAuditHandler();
	String 				   username     = getGrantorUsername(grantorPrinc);
	List<String> 		   principals   = new ArrayList<>();
	try {
		GrantRevokeRoleRequest request  = new GrantRevokeRoleRequest();
		request.setGrantor(username);
		request.setGrantorGroups(getGrantorGroupNames(grantorPrinc));
		Set<String> userList = new HashSet<>();
		Set<String> roleList = new HashSet<>();
		Set<String> groupList = new HashSet<>();
		for(HivePrincipal principal : hivePrincipals) {
			String  name = null;
			switch(principal.getType()) {
				case USER:
					name = principal.getName();
					userList.add(name);
					principals.add("USER " + name);
					break;

				case GROUP:
					name = principal.getName();
					groupList.add(name);
					principals.add("GROUP " + name);
					break;

				case ROLE:
					name = principal.getName();
					roleList.add(name);
					principals.add("ROLE "+ name);
					break;

				case UNKNOWN:
					break;
			}
		}
		request.setUsers(userList);
		request.setGroups(groupList);
		request.setRoles(roleList);
		request.setGrantOption(grantOption);
		request.setTargetRoles(new HashSet<>(roles));
		SessionState ss = SessionState.get();
		if(ss != null) {
			request.setClientIPAddress(ss.getUserIpAddress());
			request.setSessionId(ss.getSessionId());

			HiveConf hiveConf = ss.getConf();

			if(hiveConf != null) {
				request.setRequestData(hiveConf.get(HIVE_CONF_VAR_QUERY_STRING));
			}
		}

		HiveAuthzSessionContext sessionContext = getHiveAuthzSessionContext();
		if(sessionContext != null) {
			request.setClientType(sessionContext.getClientType() == null ? null : sessionContext.getClientType().toString());
		}


		hivePlugin.grantRole(request, auditHandler);
		result = true;
	} catch(Exception excp) {
		throw new HiveAccessControlException(excp);
	} finally {
		RangerAccessResult accessResult = createAuditEvent(hivePlugin, username, principals, HiveOperationType.GRANT_ROLE, HiveAccessType.ALTER, roles, result);
		auditHandler.processResult(accessResult);
		auditHandler.flushAudit();
	}
}
 
Example #25
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public void createRole(String roleName, HivePrincipal adminGrantor)
		throws HiveAuthzPluginException, HiveAccessControlException {
	if(LOG.isDebugEnabled()) {
		LOG.debug(" ==> RangerHiveAuthorizer.createRole()");
	}
	RangerHiveAuditHandler auditHandler = new RangerHiveAuditHandler();
	String currentUserName = getGrantorUsername(adminGrantor);
	List<String> roleNames     = Arrays.asList(roleName);
	List<String> userNames     = Arrays.asList(currentUserName);
	boolean		 result		   = false;

	if (RESERVED_ROLE_NAMES.contains(roleName.trim().toUpperCase())) {
		throw new HiveAuthzPluginException("Role name cannot be one of the reserved roles: " +
				RESERVED_ROLE_NAMES);
	}

	try {
		RangerRole role  = new RangerRole();
		role.setName(roleName);
		role.setCreatedByUser(currentUserName);
		role.setCreatedBy(currentUserName);
		role.setUpdatedBy(currentUserName);
		//Add grantor as the member to this role with grant option.
		RangerRole.RoleMember userMember = new RangerRole.RoleMember(currentUserName, true);
		List<RangerRole.RoleMember> userMemberList = new ArrayList<>();
		userMemberList.add(userMember);
		role.setUsers(userMemberList);
		RangerRole ret = hivePlugin.createRole(role, auditHandler);
		if(LOG.isDebugEnabled()) {
			LOG.debug("<== createRole(): " + ret);
		}
		result = true;
	} catch(Exception excp) {
		throw new HiveAccessControlException(excp);
	} finally {
		RangerAccessResult accessResult = createAuditEvent(hivePlugin, currentUserName, userNames, HiveOperationType.CREATEROLE, HiveAccessType.CREATE, roleNames, result);
		auditHandler.processResult(accessResult);
		auditHandler.flushAudit();
	}
}
 
Example #26
Source File: RangerHiveAuditHandler.java    From ranger with Apache License 2.0 4 votes vote down vote up
AuthzAuditEvent createAuditEvent(RangerAccessResult result, String accessType, String resourcePath) {
	RangerAccessRequest  request      = result.getAccessRequest();
	RangerAccessResource resource     = request.getResource();
	String               resourceType = resource != null ? resource.getLeafName() : null;

	AuthzAuditEvent auditEvent = super.getAuthzEvents(result);

	auditEvent.setAccessType(accessType);
	auditEvent.setResourcePath(resourcePath);
	auditEvent.setResourceType("@" + resourceType); // to be consistent with earlier release

	if (request instanceof RangerHiveAccessRequest && resource instanceof RangerHiveResource) {
		RangerHiveAccessRequest hiveAccessRequest = (RangerHiveAccessRequest) request;
		RangerHiveResource hiveResource = (RangerHiveResource) resource;
		HiveAccessType hiveAccessType = hiveAccessRequest.getHiveAccessType();

		if (hiveAccessType == HiveAccessType.USE && hiveResource.getObjectType() == HiveObjectType.DATABASE && StringUtils.isBlank(hiveResource.getDatabase())) {
			// this should happen only for SHOWDATABASES
			auditEvent.setTags(null);
		}

		if (hiveAccessType == HiveAccessType.REPLADMIN ) {
			// In case of REPL commands Audit should show what REPL Command instead of REPLADMIN access type
			String context = request.getRequestData();
				String replAccessType = getReplCmd(context);
				auditEvent.setAccessType(replAccessType);
		}

		if (hiveAccessType == HiveAccessType.SERVICEADMIN) {
			String hiveOperationType = request.getAction();
			String commandStr = request.getRequestData();
			if (HiveOperationType.KILL_QUERY.name().equalsIgnoreCase(hiveOperationType)) {
				String queryId = getServiceAdminQueryId(commandStr);
				if (!StringUtils.isEmpty(queryId)) {
					auditEvent.setRequestData(queryId);
				}
				commandStr = getServiceAdminCmd(commandStr);
				if (StringUtils.isEmpty(commandStr)) {
					commandStr = hiveAccessType.name();
				}
			}
			auditEvent.setAccessType(commandStr);
		}

		String action = request.getAction();
		if (hiveResource.getObjectType() == HiveObjectType.GLOBAL && isRoleOperation(action)) {
			auditEvent.setAccessType(action);
		}
	}

	return auditEvent;
}
 
Example #27
Source File: SentryHiveAuthorizationValidator.java    From incubator-sentry with Apache License 2.0 2 votes vote down vote up
/**
 * Check if current user has privileges to perform given operation type hiveOpType on the given
 * input and output objects.
 *
 * @param hiveOpType
 * @param inputHObjs
 * @param outputHObjs
 * @param context
 * @throws HiveAuthzPluginException, HiveAccessControlException
 */
@Override
public abstract void checkPrivileges(HiveOperationType hiveOpType,
    List<HivePrivilegeObject> inputHObjs, List<HivePrivilegeObject> outputHObjs,
    HiveAuthzContext context) throws HiveAuthzPluginException, HiveAccessControlException;