Java Code Examples for org.apache.ranger.plugin.policyengine.RangerAccessResult#getIsAllowed()

The following examples show how to use org.apache.ranger.plugin.policyengine.RangerAccessResult#getIsAllowed() . 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: RangerKmsAuthorizer.java    From ranger with Apache License 2.0 6 votes vote down vote up
public boolean hasAccess(Type type, UserGroupInformation ugi, String keyName, String clientIp) {
 if(LOG.isDebugEnabled()) {
	LOG.debug("==> RangerKmsAuthorizer.hasAccess(" + type + ", " + ugi + " , "+keyName+")");
}
boolean ret = false;
RangerKMSPlugin plugin = kmsPlugin;
String rangerAccessType = getRangerAccessType(type);
AccessControlList blacklist = blacklistedAcls.get(type);
   ret = (blacklist == null) || !blacklist.isUserInList(ugi);
   if(!ret){
   	LOG.debug("Operation "+rangerAccessType+" blocked in the blacklist for user "+ugi.getUserName());
   }
		
if(plugin != null && ret) {				
	RangerKMSAccessRequest request = new RangerKMSAccessRequest(keyName, rangerAccessType, ugi, clientIp);
	RangerAccessResult result = plugin.isAccessAllowed(request);
	ret = result != null && result.getIsAllowed();
}

if(LOG.isDebugEnabled()) {
	LOG.debug("<== RangerkmsAuthorizer.hasAccess(" + type + ", " + ugi +  " , "+keyName+ "): " + ret);
}

return ret;
}
 
Example 2
Source File: RangerAtlasAuthorizer.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Override
public void processResult(RangerAccessResult result) {
    if (denyExists) { // nothing more to do, if a deny already encountered
        return;
    }

    AuthzAuditEvent auditEvent = super.getAuthzEvents(result);

    if (auditEvent != null) {
        // audit event might have list of entity-types and classification-types; overwrite with the values in original request
        if (resourcePath != null) {
            auditEvent.setResourcePath(resourcePath);
        }

        if (!result.getIsAllowed()) {
            denyExists = true;

            auditEvents.clear();
        }

        auditEvents.put(auditEvent.getPolicyId() + auditEvent.getAccessType(), auditEvent);
    }
}
 
Example 3
Source File: RangerKylinAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public boolean checkPermission(String user, List<String> groups, String entityType, String entityUuid,
		Permission permission) {
	if (LOG.isDebugEnabled()) {
		LOG.debug("==> RangerKylinAuthorizer.checkPermission( user=" + user + ", groups=" + groups
				+ ", entityType=" + entityType + ", entityUuid=" + entityUuid + ", permission=" + permission + ")");
	}

	boolean ret = false;

	if (kylinPlugin != null) {
		String projectName = null;
		KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv();
		if (AclEntityType.PROJECT_INSTANCE.equals(entityType)) {
			ProjectInstance projectInstance = ProjectManager.getInstance(kylinConfig).getPrjByUuid(entityUuid);
			if (projectInstance != null) {
				projectName = projectInstance.getName();
			} else {
				if (LOG.isWarnEnabled()) {
					LOG.warn("Could not find kylin project for given uuid=" + entityUuid);
				}
			}
		}

		String accessType = ExternalAclProvider.transformPermission(permission);
		RangerKylinAccessRequest request = new RangerKylinAccessRequest(projectName, user, groups, accessType,
				clientIPAddress);

		RangerAccessResult result = kylinPlugin.isAccessAllowed(request);
		if (result != null && result.getIsAllowed()) {
			ret = true;
		}
	}

	if (LOG.isDebugEnabled()) {
		LOG.debug("<== RangerKylinAuthorizer.checkPermission(): result=" + ret);
	}

	return ret;
}
 
Example 4
Source File: RangerDefaultPolicyEvaluator.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public void updateAccessResult(RangerAccessResult result, RangerPolicyResourceMatcher.MatchType matchType, boolean isAllowed, String reason) {
	if (LOG.isDebugEnabled()) {
		LOG.debug("==> RangerDefaultPolicyEvaluator.updateAccessResult(" + result + ", " + matchType +", " + isAllowed + ", " + reason + ", " + getId() + ")");
	}
	if (!isAllowed) {
		if (matchType != RangerPolicyResourceMatcher.MatchType.DESCENDANT || !result.getAccessRequest().isAccessTypeAny()) {
			result.setIsAllowed(false);
			result.setPolicyPriority(getPolicyPriority());
			result.setPolicyId(getId());
			result.setReason(reason);
			result.setPolicyVersion(getPolicy().getVersion());
		}
	} else {
		if (!result.getIsAllowed()) { // if access is not yet allowed by another policy
			if (matchType != RangerPolicyResourceMatcher.MatchType.ANCESTOR) {
				result.setIsAllowed(true);
				result.setPolicyPriority(getPolicyPriority());
				result.setPolicyId(getId());
				result.setReason(reason);
				result.setPolicyVersion(getPolicy().getVersion());
			}
		}
	}
	if (LOG.isDebugEnabled()) {
		LOG.debug("<== RangerDefaultPolicyEvaluator.updateAccessResult(" + result + ", " + matchType +", " + isAllowed + ", " + reason + ", " + getId() + ")");
	}
}
 
Example 5
Source File: RangerElasticsearchAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public boolean checkPermission(String user, List<String> groups, String index, String action,
		String clientIPAddress) {
	if (LOG.isDebugEnabled()) {
		LOG.debug("==> RangerElasticsearchAuthorizer.checkPermission( user=" + user + ", groups=" + groups
				+ ", index=" + index + ", action=" + action + ", clientIPAddress=" + clientIPAddress + ")");
	}

	boolean ret = false;

	if (elasticsearchPlugin != null) {
		if (null == groups) {
			groups = new ArrayList <>(MiscUtil.getGroupsForRequestUser(user));
		}
		String privilege = IndexPrivilegeUtils.getPrivilegeFromAction(action);
		RangerElasticsearchAccessRequest request = new RangerElasticsearchAccessRequest(user, groups, index,
				privilege, clientIPAddress);

		RangerAccessResult result = elasticsearchPlugin.isAccessAllowed(request);
		if (result != null && result.getIsAllowed()) {
			ret = true;
		}
	}

	if (LOG.isDebugEnabled()) {
		LOG.debug("<== RangerElasticsearchAuthorizer.checkPermission(): result=" + ret);
	}

	return ret;
}
 
Example 6
Source File: RangerSystemAccessControl.java    From ranger with Apache License 2.0 5 votes vote down vote up
private boolean hasPermission(RangerPrestoResource resource, SystemSecurityContext context, PrestoAccessType accessType) {
  boolean ret = false;

  RangerPrestoAccessRequest request = createAccessRequest(resource, context, accessType);

  RangerAccessResult result = rangerPlugin.isAccessAllowed(request);
  if (result != null && result.getIsAllowed()) {
    ret = true;
  }

  return ret;
}
 
Example 7
Source File: RangerAtlasAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
private boolean checkAccess(RangerAccessRequestImpl request) {
    boolean          ret    = false;
    RangerBasePlugin plugin = atlasPlugin;

    if (plugin != null) {
        RangerAccessResult result = plugin.isAccessAllowed(request);

        ret = result != null && result.getIsAllowed();
    } else {
        LOG.warn("RangerAtlasPlugin not initialized. Access blocked!!!");
    }

    return ret;
}
 
Example 8
Source File: RangerKafkaAuditHandler.java    From ranger with Apache License 2.0 5 votes vote down vote up
private boolean isAuditingNeeded(final RangerAccessResult result) {
    boolean ret = true;
    boolean 			    isAllowed = result.getIsAllowed();
    RangerAccessRequest request = result.getAccessRequest();
    RangerAccessResourceImpl resource = (RangerAccessResourceImpl) request.getResource();
    String resourceName 			  = (String) resource.getValue(RangerKafkaAuthorizer.KEY_CLUSTER);
    if (resourceName != null) {
        if (request.getAccessType().equalsIgnoreCase(RangerKafkaAuthorizer.ACCESS_TYPE_CREATE) && !isAllowed) {
            ret = false;
        }
    }
    return ret;
}
 
Example 9
Source File: RangerSqoopAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public void checkPrivileges(MPrincipal principal, List<MPrivilege> privileges) throws SqoopException {
	if (LOG.isDebugEnabled()) {
		LOG.debug("==> RangerSqoopAuthorizer.checkPrivileges( principal=" + principal + ", privileges="
				+ privileges + ")");
	}

	if (CollectionUtils.isEmpty(privileges)) {
		if (LOG.isDebugEnabled()) {
			LOG.debug("<== RangerSqoopAuthorizer.checkPrivileges() return because privileges is empty.");
		}
		return;
	}

	RangerSqoopPlugin plugin = sqoopPlugin;

	if (plugin != null) {
		for (MPrivilege privilege : privileges) {
			RangerSqoopAccessRequest request = new RangerSqoopAccessRequest(principal, privilege, clientIPAddress);

			RangerAccessResult result = plugin.isAccessAllowed(request);
			if (result != null && !result.getIsAllowed()) {
				throw new SqoopException(SecurityError.AUTH_0014, "principal=" + principal
						+ " does not have privileges for : " + privilege);
			}
		}
	}

	if (LOG.isDebugEnabled()) {
		LOG.debug("<== RangerSqoopAuthorizer.checkPrivileges() success without exception.");
	}
}
 
Example 10
Source File: RangerHiveAuditHandler.java    From ranger with Apache License 2.0 5 votes vote down vote up
private boolean skipFilterOperationAuditing(RangerAccessResult result) {
	boolean ret = false;
	RangerAccessRequest accessRequest = result.getAccessRequest();
	if (accessRequest != null) {
		String action = accessRequest.getAction();
		if (ACTION_TYPE_METADATA_OPERATION.equals(action) && !result.getIsAllowed()) {
			ret = true;
		}
	}
	return ret;
}
 
Example 11
Source File: RangerKmsAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
/**
 * First Check if user is in ACL for the KMS operation, if yes, then
 * return true if user is not present in any configured blacklist for
 * the operation
 * @param type KMS Operation
 * @param ugi UserGroupInformation of user
 * @return true is user has access
 */
@Override
public boolean hasAccess(Type type, UserGroupInformation ugi, String clientIp) {
 if(LOG.isDebugEnabled()) {
	LOG.debug("==> RangerKmsAuthorizer.hasAccess(" + type + ", " + ugi + ")");
}
 RangerPerfTracer perf = null;

 if(RangerPerfTracer.isPerfTraceEnabled(PERF_KMSAUTH_REQUEST_LOG)) {
  perf = RangerPerfTracer.getPerfTracer(PERF_KMSAUTH_REQUEST_LOG, "RangerKmsAuthorizer.hasAccess(type=" + type + ")");
 }
boolean ret = false;
RangerKMSPlugin plugin = kmsPlugin;
String rangerAccessType = getRangerAccessType(type);
AccessControlList blacklist = blacklistedAcls.get(type);
   ret = (blacklist == null) || !blacklist.isUserInList(ugi);
   if(!ret){
   	LOG.debug("Operation "+rangerAccessType+" blocked in the blacklist for user "+ugi.getUserName());
   }
		
if(plugin != null && ret) {				
	RangerKMSAccessRequest request = new RangerKMSAccessRequest("", rangerAccessType, ugi, clientIp);
	RangerAccessResult result = plugin.isAccessAllowed(request);
	ret = result != null && result.getIsAllowed();
}
RangerPerfTracer.log(perf);
if(LOG.isDebugEnabled()) {
	LOG.debug("<== RangerkmsAuthorizer.hasAccess(" + type + ", " + ugi + "): " + ret);
}

return ret;
}
 
Example 12
Source File: RangerHdfsAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
private AuthzStatus isAccessAllowedForTraversal(INode inode, INodeAttributes inodeAttribs, String path, String user, Set<String> groups, RangerHdfsPlugin plugin, RangerHdfsAuditHandler auditHandler, boolean skipAuditOnAllow) {
	final AuthzStatus ret;
	String pathOwner = inodeAttribs != null ? inodeAttribs.getUserName() : null;
	FsAction access = FsAction.EXECUTE;


	if (pathOwner == null) {
		pathOwner = inode.getUserName();
	}

	if (RangerHadoopConstants.HDFS_ROOT_FOLDER_PATH_ALT.equals(path)) {
		path = HDFS_ROOT_FOLDER_PATH;
	}

	if (LOG.isDebugEnabled()) {
		LOG.debug("==> RangerAccessControlEnforcer.isAccessAllowedForTraversal(" + path + ", " + access + ", " + user + ", " + skipAuditOnAllow + ")");
	}

	RangerHdfsAccessRequest request = new RangerHdfsAccessRequest(inode, path, pathOwner, access, EXECUTE_ACCCESS_TYPE, user, groups);

	RangerAccessResult result = plugin.isAccessAllowed(request, null);

	if (result != null && result.getIsAccessDetermined() && !result.getIsAllowed()) {
		ret = AuthzStatus.DENY;
	} else {
		ret = AuthzStatus.ALLOW;
	}

	if (ret == AuthzStatus.DENY || (!skipAuditOnAllow && result != null && result.getIsAccessDetermined())) {
		auditHandler.processResult(result);
	}

	if (LOG.isDebugEnabled()) {
		LOG.debug("<== RangerAccessControlEnforcer.isAccessAllowedForTraversal(" + path + ", " + access + ", " + user + ", " + skipAuditOnAllow + "): " + ret);
	}

	return ret;
}
 
Example 13
Source File: RangerSchemaRegistryAuthorizerImpl.java    From registry with Apache License 2.0 5 votes vote down vote up
private boolean authorize(RangerAccessResourceImpl resource,
                          AccessType accessType,
                          UserAndGroups userAndGroups) {
    RangerAccessRequestImpl request = new RangerAccessRequestImpl(resource, accessType.getName(),
            userAndGroups.getUser(),
            userAndGroups.getGroups());

    RangerAccessResult res = plg.isAccessAllowed(request);

    return res != null && res.getIsAllowed();
}
 
Example 14
Source File: RangerKafkaAuthorizer.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public boolean authorize(Session session, Operation operation,
		Resource resource) {

	if (rangerPlugin == null) {
		MiscUtil.logErrorMessageByInterval(logger,
				"Authorizer is still not initialized");
		return false;
	}

	RangerPerfTracer perf = null;

	if(RangerPerfTracer.isPerfTraceEnabled(PERF_KAFKAAUTH_REQUEST_LOG)) {
		perf = RangerPerfTracer.getPerfTracer(PERF_KAFKAAUTH_REQUEST_LOG, "RangerKafkaAuthorizer.authorize(resource=" + resource + ")");
	}
	String userName = null;
	if (session.principal() != null) {
		userName = session.principal().getName();
	}
	java.util.Set<String> userGroups = MiscUtil
			.getGroupsForRequestUser(userName);
	String ip = session.clientAddress().getHostAddress();

	// skip leading slash
	if (StringUtils.isNotEmpty(ip) && ip.charAt(0) == '/') {
		ip = ip.substring(1);
	}

	Date eventTime = new Date();
	String accessType = mapToRangerAccessType(operation);
	boolean validationFailed = false;
	String validationStr = "";

	if (accessType == null) {
		if (MiscUtil.logErrorMessageByInterval(logger,
				"Unsupported access type. operation=" + operation)) {
			logger.fatal("Unsupported access type. session=" + session
					+ ", operation=" + operation + ", resource=" + resource);
		}
		validationFailed = true;
		validationStr += "Unsupported access type. operation=" + operation;
	}
	String action = accessType;

	RangerAccessRequestImpl rangerRequest = new RangerAccessRequestImpl();
	rangerRequest.setUser(userName);
	rangerRequest.setUserGroups(userGroups);
	rangerRequest.setClientIPAddress(ip);
	rangerRequest.setAccessTime(eventTime);

	RangerAccessResourceImpl rangerResource = new RangerAccessResourceImpl();
	rangerRequest.setResource(rangerResource);
	rangerRequest.setAccessType(accessType);
	rangerRequest.setAction(action);
	rangerRequest.setRequestData(resource.name());

	if (resource.resourceType().equals(Topic$.MODULE$)) {
		rangerResource.setValue(KEY_TOPIC, resource.name());
	} else if (resource.resourceType().equals(Cluster$.MODULE$)) {
		rangerResource.setValue(KEY_CLUSTER, resource.name());
	} else if (resource.resourceType().equals(Group$.MODULE$)) {
		rangerResource.setValue(KEY_CONSUMER_GROUP, resource.name());
	} else if (resource.resourceType().equals(TransactionalId$.MODULE$)) {
		rangerResource.setValue(KEY_TRANSACTIONALID, resource.name());
	} else if (resource.resourceType().equals(DelegationToken$.MODULE$)) {
		rangerResource.setValue(KEY_DELEGATIONTOKEN, resource.name());
	} else {
		logger.fatal("Unsupported resourceType=" + resource.resourceType());
		validationFailed = true;
	}

	boolean returnValue = false;
	if (validationFailed) {
		MiscUtil.logErrorMessageByInterval(logger, validationStr
				+ ", request=" + rangerRequest);
	} else {

		try {
			RangerAccessResult result = rangerPlugin
					.isAccessAllowed(rangerRequest);
			if (result == null) {
				logger.error("Ranger Plugin returned null. Returning false");
			} else {
				returnValue = result.getIsAllowed();
			}
		} catch (Throwable t) {
			logger.error("Error while calling isAccessAllowed(). request="
					+ rangerRequest, t);
		} finally {
			auditHandler.flushAudit();
		}
	}
	RangerPerfTracer.log(perf);

	if (logger.isDebugEnabled()) {
		logger.debug("rangerRequest=" + rangerRequest + ", return="
				+ returnValue);
	}
	return returnValue;
}
 
Example 15
Source File: RangerHdfsAuthorizer.java    From ranger with Apache License 2.0 4 votes vote down vote up
private AuthzStatus isAccessAllowedForHierarchy(INode inode, INodeAttributes inodeAttribs, String path, FsAction access, String user, Set<String> groups, RangerHdfsPlugin plugin) {
	AuthzStatus ret   = null;
	String  pathOwner = inodeAttribs != null ? inodeAttribs.getUserName() : null;

	if (pathOwner == null && inode != null) {
		pathOwner = inode.getUserName();
	}

	if (RangerHadoopConstants.HDFS_ROOT_FOLDER_PATH_ALT.equals(path)) {
		path = HDFS_ROOT_FOLDER_PATH;
	}

	if (LOG.isDebugEnabled()) {
		LOG.debug("==> RangerAccessControlEnforcer.isAccessAllowedForHierarchy(" + path + ", " + access + ", " + user + ")");
	}

	if (path != null) {

		Set<String> accessTypes = access2ActionListMapper.get(access);

		if (accessTypes == null) {
			LOG.warn("RangerAccessControlEnforcer.isAccessAllowedForHierarchy(" + path + ", " + access + ", " + user + "): no Ranger accessType found for " + access);

			accessTypes = access2ActionListMapper.get(FsAction.NONE);
		}

		String subDirPath = path;
		if (subDirPath.charAt(subDirPath.length() - 1) != Path.SEPARATOR_CHAR) {
			subDirPath = subDirPath + Character.toString(Path.SEPARATOR_CHAR);
		}
		subDirPath = subDirPath + rangerPlugin.getRandomizedWildcardPathName();

		for (String accessType : accessTypes) {
			RangerHdfsAccessRequest request = new RangerHdfsAccessRequest(null, subDirPath, pathOwner, access, accessType, user, groups);

			RangerAccessResult result = plugin.isAccessAllowed(request, null);

			if (result == null || !result.getIsAccessDetermined()) {
				ret = AuthzStatus.NOT_DETERMINED;
				// don't break yet; subsequent accessType could be denied
			} else if(! result.getIsAllowed()) { // explicit deny
				ret = AuthzStatus.DENY;
				break;
			} else { // allowed
				if(!AuthzStatus.NOT_DETERMINED.equals(ret)) { // set to ALLOW only if there was no NOT_DETERMINED earlier
					ret = AuthzStatus.ALLOW;
				}
			}
		}
	}

	if(ret == null) {
		ret = AuthzStatus.NOT_DETERMINED;
	}

	if (LOG.isDebugEnabled()) {
		LOG.debug("<== RangerAccessControlEnforcer.isAccessAllowedForHierarchy(" + path + ", " + access + ", " + user + "): " + ret);
	}

	return ret;
}
 
Example 16
Source File: RangerNiFiAuthorizer.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public AuthorizationResult authorize(final AuthorizationRequest request) throws AuthorizationAccessException {
    final String identity = request.getIdentity();
    final Set<String> userGroups = request.getGroups();
    final String resourceIdentifier = request.getResource().getIdentifier();

    // if a ranger admin identity was provided, and it equals the identity making the request,
    // and the request is to retrieve the resources, then allow it through
    if (StringUtils.isNotBlank(rangerAdminIdentity) && rangerAdminIdentity.equals(identity)
            && resourceIdentifier.equals(RESOURCES_RESOURCE)) {
        return AuthorizationResult.approved();
    }

    final String clientIp;
    if (request.getUserContext() != null) {
        clientIp = request.getUserContext().get(UserContextKeys.CLIENT_ADDRESS.name());
    } else {
        clientIp = null;
    }

    final RangerAccessResourceImpl resource = new RangerAccessResourceImpl();
    resource.setValue(RANGER_NIFI_RESOURCE_NAME, resourceIdentifier);

    final RangerAccessRequestImpl rangerRequest = new RangerAccessRequestImpl();
    rangerRequest.setResource(resource);
    rangerRequest.setAction(request.getAction().name());
    rangerRequest.setAccessType(request.getAction().name());
    rangerRequest.setUser(identity);
    rangerRequest.setUserGroups(userGroups);
    rangerRequest.setAccessTime(new Date());

    if (!StringUtils.isBlank(clientIp)) {
        rangerRequest.setClientIPAddress(clientIp);
    }

    final RangerAccessResult result = nifiPlugin.isAccessAllowed(rangerRequest);

    // store the result for auditing purposes later if appropriate
    if (request.isAccessAttempt()) {
        synchronized (resultLookup) {
            resultLookup.put(request, result);
        }
    }

    if (result != null && result.getIsAllowed()) {
        // return approved
        return AuthorizationResult.approved();
    } else {
        // if result.getIsAllowed() is false, then we need to determine if it was because no policy exists for the
        // given resource, or if it was because a policy exists but not for the given user or action
        final boolean doesPolicyExist = nifiPlugin.doesPolicyExist(request.getResource().getIdentifier(), request.getAction());

        if (doesPolicyExist) {
            final String reason = result == null ? null : result.getReason();
            if (reason != null) {
                logger.debug(String.format("Unable to authorize %s due to %s", identity, reason));
            }

            // a policy does exist for the resource so we were really denied access here
            return AuthorizationResult.denied(request.getExplanationSupplier().get());
        } else {
            // a policy doesn't exist so return resource not found so NiFi can work back up the resource hierarchy
            return AuthorizationResult.resourceNotFound();
        }
    }
}
 
Example 17
Source File: RangerStormAuthorizer.java    From ranger with Apache License 2.0 4 votes vote down vote up
/**
    * permit() method is invoked for each incoming Thrift request.
    * @param aRequestContext request context includes info about
    * @param aOperationName operation name
    * @param aTopologyConfigMap 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;

	RangerPerfTracer perf = null;

	try {

		if(RangerPerfTracer.isPerfTraceEnabled(PERF_STORMAUTH_REQUEST_LOG)) {
			perf = RangerPerfTracer.getPerfTracer(PERF_STORMAUTH_REQUEST_LOG, "RangerStormAuthorizer.permit()");
		}

		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 {
		RangerPerfTracer.log(perf);
		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;
}
 
Example 18
Source File: RangerAuthorizer.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
@Override
public AuthorizationResult authorize(final AuthorizationRequest request) throws SecurityProviderCreationException {
    final String identity = request.getIdentity();
    final Set<String> userGroups = request.getGroups();
    final String resourceIdentifier = request.getResource().getIdentifier();

    // if a ranger admin identity was provided, and it equals the identity making the request,
    // and the request is to retrieve the resources, then allow it through
    if (StringUtils.isNotBlank(rangerAdminIdentity) && rangerAdminIdentity.equals(identity)
            && resourceIdentifier.equals(RESOURCES_RESOURCE)) {
        return AuthorizationResult.approved();
    }

    final String clientIp;
    if (request.getUserContext() != null) {
        clientIp = request.getUserContext().get(UserContextKeys.CLIENT_ADDRESS.name());
    } else {
        clientIp = null;
    }

    final RangerAccessResourceImpl resource = new RangerAccessResourceImpl();
    resource.setValue(RANGER_NIFI_REG_RESOURCE_NAME, resourceIdentifier);

    final RangerAccessRequestImpl rangerRequest = new RangerAccessRequestImpl();
    rangerRequest.setResource(resource);
    rangerRequest.setAction(request.getAction().name());
    rangerRequest.setAccessType(request.getAction().name());
    rangerRequest.setUser(identity);
    rangerRequest.setUserGroups(userGroups);
    rangerRequest.setAccessTime(new Date());

    if (!StringUtils.isBlank(clientIp)) {
        rangerRequest.setClientIPAddress(clientIp);
    }

    final RangerAccessResult result = rangerPlugin.isAccessAllowed(rangerRequest);

    // store the result for auditing purposes later if appropriate
    if (request.isAccessAttempt()) {
        synchronized (resultLookup) {
            resultLookup.put(request, result);
        }
    }

    if (result != null && result.getIsAllowed()) {
        // return approved
        return AuthorizationResult.approved();
    } else {
        // if result.getIsAllowed() is false, then we need to determine if it was because no policy exists for the
        // given resource, or if it was because a policy exists but not for the given user or action
        final boolean doesPolicyExist = rangerPlugin.doesPolicyExist(request.getResource().getIdentifier(), request.getAction());

        if (doesPolicyExist) {
            final String reason = result == null ? null : result.getReason();
            if (reason != null) {
                logger.debug(String.format("Unable to authorize %s due to %s", identity, reason));
            }

            // a policy does exist for the resource so we were really denied access here
            return AuthorizationResult.denied(request.getExplanationSupplier().get());
        } else {
            // a policy doesn't exist so return resource not found so NiFi Registry can work back up the resource hierarchy
            return AuthorizationResult.resourceNotFound();
        }
    }
}
 
Example 19
Source File: RangerNiFiAuthorizer.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public AuthorizationResult authorize(final AuthorizationRequest request) throws AuthorizationAccessException {
    final String identity = request.getIdentity();
    final String resourceIdentifier = request.getResource().getIdentifier();

    // if a ranger admin identity was provided, and it equals the identity making the request,
    // and the request is to retrieve the resources, then allow it through
    if (StringUtils.isNotBlank(rangerAdminIdentity) && rangerAdminIdentity.equals(identity)
            && resourceIdentifier.equals(RESOURCES_RESOURCE)) {
        return AuthorizationResult.approved();
    }

    final String clientIp;
    if (request.getUserContext() != null) {
        clientIp = request.getUserContext().get(UserContextKeys.CLIENT_ADDRESS.name());
    } else {
        clientIp = null;
    }

    final RangerAccessResourceImpl resource = new RangerAccessResourceImpl();
    resource.setValue(RANGER_NIFI_RESOURCE_NAME, resourceIdentifier);

    final RangerAccessRequestImpl rangerRequest = new RangerAccessRequestImpl();
    rangerRequest.setResource(resource);
    rangerRequest.setAction(request.getAction().name());
    rangerRequest.setAccessType(request.getAction().name());
    rangerRequest.setUser(identity);
    rangerRequest.setAccessTime(new Date());

    if (!StringUtils.isBlank(clientIp)) {
        rangerRequest.setClientIPAddress(clientIp);
    }

    // for a direct access request use the default audit handler so we generate audit logs
    // for non-direct access provide a null result processor so no audit logs get generated
    final RangerAccessResultProcessor resultProcessor = request.isAccessAttempt() ?  defaultAuditHandler : null;

    final RangerAccessResult result = nifiPlugin.isAccessAllowed(rangerRequest, resultProcessor);

    if (result != null && result.getIsAllowed()) {
        return AuthorizationResult.approved();
    } else {
        // if result.getIsAllowed() is false, then we need to determine if it was because no policy exists for the
        // given resource, or if it was because a policy exists but not for the given user or action
        final boolean doesPolicyExist = nifiPlugin.doesPolicyExist(request.getResource().getIdentifier());

        if (doesPolicyExist) {
            final String reason = result == null ? null : result.getReason();
            if (reason != null) {
                logger.debug(String.format("Unable to authorize %s due to %s", identity, reason));
            }

            // a policy does exist for the resource so we were really denied access here
            return AuthorizationResult.denied(request.getExplanationSupplier().get());
        } else {
            // a policy doesn't exist so return resource not found so NiFi can work back up the resource hierarchy
            return AuthorizationResult.resourceNotFound();
        }
    }
}
 
Example 20
Source File: RangerAuthorizer.java    From ranger with Apache License 2.0 3 votes vote down vote up
public boolean authorize(String fileName, String accessType, String user, Set<String> userGroups) {
    RangerAccessResourceImpl resource = new RangerAccessResourceImpl();
    resource.setValue("path", fileName); // "path" must be a value resource name in servicedef JSON

    RangerAccessRequest request = new RangerAccessRequestImpl(resource, accessType, user, userGroups, null);

    RangerAccessResult result = plugin.isAccessAllowed(request);

    return result != null && result.getIsAllowed();
}