org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl Java Examples

The following examples show how to use org.apache.ranger.plugin.policyengine.RangerAccessResourceImpl. 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: KnoxRangerPlugin.java    From ranger with Apache License 2.0 6 votes vote down vote up
RangerAccessRequest build() {
	// build resource
	RangerAccessResourceImpl resource = new RangerAccessResourceImpl();
	resource.setValue(ResourceName.Service, _service);
	resource.setValue(ResourceName.Topology, _topology);
	// build request
	RangerAccessRequestImpl request = new RangerAccessRequestImpl();
	request.setAction(AccessType.Allow);
	request.setAccessType(AccessType.Allow);
	request.setClientIPAddress(_clientIp);
	request.setUser(_user);
	request.setUserGroups(_groups);
	request.setResource(resource);
	request.setRemoteIPAddress(_remoteIp);
	request.setForwardedAddresses(_forwardedAddresses);
	return request;
}
 
Example #2
Source File: StormRangerPlugin.java    From ranger with Apache License 2.0 6 votes vote down vote up
public RangerAccessRequest buildAccessRequest(String _user, String[] _groups, String _clientIp, String _topology, String _operation) {
	
	RangerAccessRequestImpl request = new RangerAccessRequestImpl();
	request.setUser(_user);
	if (_groups != null && _groups.length > 0) {
		Set<String> groups = Sets.newHashSet(_groups);
		request.setUserGroups(groups);
	}

	request.setAccessType(getAccessType(_operation));
	request.setClientIPAddress(_clientIp);
	request.setAction(_operation);
	// build resource and connect stuff into request
	RangerAccessResourceImpl resource = new RangerAccessResourceImpl();
	resource.setValue(ResourceName.Topology, _topology);
	request.setResource(resource);
	
	if (LOG.isDebugEnabled()) {
		LOG.debug("Returning request: " + request.toString());
	}
	
	return request;
}
 
Example #3
Source File: RangerSolrAuthorizer.java    From ranger with Apache License 2.0 6 votes vote down vote up
/**
 * @param userName
 * @param userGroups
 * @param ip
 * @param eventTime
 * @param context
 * @param collectionRequest
 * @return
 */
private RangerAccessRequestImpl createRequest(String userName,
		Set<String> userGroups, String ip, Date eventTime,
		AuthorizationContext context, CollectionRequest collectionRequest) {

	String accessType = mapToRangerAccessType(context);
	String action = accessType;
	RangerAccessRequestImpl rangerRequest = createBaseRequest(userName,
			userGroups, ip, eventTime);
	RangerAccessResourceImpl rangerResource = new RangerAccessResourceImpl();
	if (collectionRequest == null) {
		rangerResource.setValue(KEY_COLLECTION, "*");
	} else {
		rangerResource.setValue(KEY_COLLECTION, collectionRequest.collectionName);
	}
	rangerRequest.setResource(rangerResource);
	rangerRequest.setAccessType(accessType);
	rangerRequest.setAction(action);

	return rangerRequest;
}
 
Example #4
Source File: RangerAtlasAuthorizer.java    From ranger with Apache License 2.0 6 votes vote down vote up
public RangerAtlasAuditHandler(AtlasEntityAccessRequest request, RangerServiceDef serviceDef) {
    Collection<String> classifications    = request.getEntityClassifications();
    String             strClassifications = classifications == null ? "[]" : classifications.toString();

    if (request.getClassification() != null) {
        strClassifications += ("," + request.getClassification().getTypeName());
    }

    RangerAccessResourceImpl rangerResource = new RangerAccessResourceImpl();

    rangerResource.setServiceDef(serviceDef);
    rangerResource.setValue(RESOURCE_ENTITY_TYPE, request.getEntityType());
    rangerResource.setValue(RESOURCE_ENTITY_CLASSIFICATION, strClassifications);
    rangerResource.setValue(RESOURCE_ENTITY_ID, request.getEntityId());

    if (AtlasPrivilege.ENTITY_ADD_LABEL.equals(request.getAction()) || AtlasPrivilege.ENTITY_REMOVE_LABEL.equals(request.getAction())) {
        rangerResource.setValue(RESOURCE_ENTITY_LABEL, "label=" + request.getLabel());
    } else if (AtlasPrivilege.ENTITY_UPDATE_BUSINESS_METADATA.equals(request.getAction())) {
        rangerResource.setValue(RESOURCE_ENTITY_BUSINESS_METADATA, "business-metadata=" + request.getBusinessMetadata());
    }

    auditEvents  = new HashMap<>();
    resourcePath = rangerResource.getAsString();
}
 
Example #5
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 #6
Source File: RangerSchemaRegistryAuthorizerImpl.java    From registry with Apache License 2.0 5 votes vote down vote up
RangerAccessResourceImpl registryResource2RangerResource(Resource registryResource) {
    RangerAccessResourceImpl rangerResource = new RangerAccessResourceImpl();

    if(registryResource instanceof SchemaMetadataResource) {
        SchemaMetadataResource smr = (SchemaMetadataResource) registryResource;
        rangerResource.setValue(RANGER_RESOURCE_SCHEMA_GROUP, smr.getsGroupName());
        rangerResource.setValue(RANGER_RESOURCE_SCHEMA_METADATA, smr.getsMetadataName());
    }

    if(registryResource instanceof SchemaBranchResource) {
        SchemaBranchResource sbr = (SchemaBranchResource) registryResource;
        rangerResource.setValue(RANGER_RESOURCE_SCHEMA_BRANCH, sbr.getsBranchName());
    }

    switch (registryResource.getResourceType()) {
        case SERDE: {
            rangerResource.setValue(RANGER_RESOURCE_SERDE, "ANY_VALUE");
            return rangerResource;
        }
        case SCHEMA_VERSION: {
            rangerResource.setValue(RANGER_RESOURCE_SCHEMA_VERSION, "ANY_VALUE");
            return rangerResource;
        }
        case SCHEMA_METADATA: case SCHEMA_BRANCH: {
            return rangerResource;
        }

        default:
            // In current implemetataion the exception should never be thrown. This is added for future if
            // the set of resources is extended but implemetation is not provided.
            throw new RuntimeException(
                    String.format("Cannot convert registry resource to ranger resource. ResourceType %s is not supported",
                            registryResource.getResourceType().name()));
    }

}
 
Example #7
Source File: TestPolicyEngine.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public RangerAccessResource deserialize(JsonElement jsonObj, Type type,
		JsonDeserializationContext context) throws JsonParseException {
	RangerAccessResourceImpl resource =  gsonBuilder.fromJson(jsonObj, RangerHBaseResource.class);
	resource.setValue("table", resource.getValue("table"));
	return resource;
}
 
Example #8
Source File: RangerSolrAuditHandler.java    From ranger with Apache License 2.0 5 votes vote down vote up
private boolean isAuditingNeeded(final RangerAccessResult result) {
    boolean                  ret       = true;
    RangerAccessRequest      request   = result.getAccessRequest();
    RangerAccessResourceImpl resource  = (RangerAccessResourceImpl) request.getResource();
    String resourceName                = (String) resource.getValue(RangerSolrAuthorizer.KEY_COLLECTION);
    String requestUser                 = request.getUser();
    if (resourceName != null && resourceName.equals(RANGER_AUDIT_COLLECTION) && excludeUsers.contains(requestUser)) {
       ret = false;
    }
    return ret;
}
 
Example #9
Source File: RangerPolicyFactory.java    From ranger with Apache License 2.0 5 votes vote down vote up
private static RangerAccessRequest mutate(RangerAccessRequest template, boolean shouldEvaluateToTrue) {
	RangerAccessRequestImpl accessRequest = (RangerAccessRequestImpl) template;
	accessRequest.setResource(new RangerAccessResourceImpl(createResourceElements(shouldEvaluateToTrue)));
	accessRequest.setAccessType(pickOneRandomly(ALWAYS_ALLOWED_ACCESS_TYPES ));
	accessRequest.setRequestData(null);
	accessRequest.setUser(pickOneRandomly(KNOWN_USERS));
	return accessRequest;
}
 
Example #10
Source File: AuthorizationSession.java    From ranger with Apache License 2.0 5 votes vote down vote up
AuthorizationSession buildRequest() {

		verifyBuildable();
		// session can be reused so reset its state
		zapAuthorizationState();
		// TODO get this via a factory instead
		RangerAccessResourceImpl resource = new RangerHBaseResource();
		// policy engine should deal sensibly with null/empty values, if any
		if (isNameSpaceOperation() && StringUtils.isNotBlank(_otherInformation)) {
				resource.setValue(RangerHBaseResource.KEY_TABLE, _otherInformation + RangerHBaseResource.NAMESPACE_SEPARATOR);
		} else {
			resource.setValue(RangerHBaseResource.KEY_TABLE, _table);
		}
		resource.setValue(RangerHBaseResource.KEY_COLUMN_FAMILY, _columnFamily);
		resource.setValue(RangerHBaseResource.KEY_COLUMN, _column);
		
		String user = _userUtils.getUserAsString(_user);
		RangerAccessRequestImpl request = new RangerAccessRequestImpl(resource, _access, user, _groups, null);
		request.setAction(_operation);
		request.setRequestData(_otherInformation);
		request.setClientIPAddress(_remoteAddress);
		request.setResourceMatchingScope(_resourceMatchingScope);
		request.setAccessTime(new Date());
		
		_request = request;
		if (LOG.isDebugEnabled()) {
			LOG.debug("Built request: " + request.toString());
		}
		return this;
	}
 
Example #11
Source File: RangerBasePlugin.java    From ranger with Apache License 2.0 5 votes vote down vote up
private void auditGrantRevoke(GrantRevokeRequest request, String action, boolean isSuccess, RangerAccessResultProcessor resultProcessor) {
	if(request != null && resultProcessor != null) {
		RangerAccessRequestImpl accessRequest = new RangerAccessRequestImpl();

		accessRequest.setResource(new RangerAccessResourceImpl(StringUtil.toStringObjectMap(request.getResource())));
		accessRequest.setUser(request.getGrantor());
		accessRequest.setAccessType(RangerPolicyEngine.ADMIN_ACCESS);
		accessRequest.setAction(action);
		accessRequest.setClientIPAddress(request.getClientIPAddress());
		accessRequest.setClientType(request.getClientType());
		accessRequest.setRequestData(request.getRequestData());
		accessRequest.setSessionId(request.getSessionId());

		// call isAccessAllowed() to determine if audit is enabled or not
		RangerAccessResult accessResult = isAccessAllowed(accessRequest, null);

		if(accessResult != null && accessResult.getIsAudited()) {
			accessRequest.setAccessType(action);
			accessResult.setIsAllowed(isSuccess);

			if(! isSuccess) {
				accessResult.setPolicyId(-1);
			}

			resultProcessor.processResult(accessResult);
		}
	}
}
 
Example #12
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 #13
Source File: RangerAtlasAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isAccessAllowed(AtlasAdminAccessRequest request) throws AtlasAuthorizationException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> isAccessAllowed(" + request + ")");
    }

    final boolean    ret;
    RangerPerfTracer perf = null;

    try {
        if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
            perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerAtlasAuthorizer.isAccessAllowed(" + request + ")");
        }

        String                   action         = request.getAction() != null ? request.getAction().getType() : null;
        RangerAccessResourceImpl rangerResource = new RangerAccessResourceImpl(Collections.singletonMap(RESOURCE_SERVICE, "*"));
        RangerAccessRequestImpl  rangerRequest  = new RangerAccessRequestImpl(rangerResource, action, request.getUser(), request.getUserGroups(), null);

        rangerRequest.setClientIPAddress(request.getClientIPAddress());
        rangerRequest.setAccessTime(request.getAccessTime());
        rangerRequest.setAction(action);
        rangerRequest.setForwardedAddresses(request.getForwardedAddresses());
        rangerRequest.setRemoteIPAddress(request.getRemoteIPAddress());


        ret = checkAccess(rangerRequest);
    } finally {
        RangerPerfTracer.log(perf);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== isAccessAllowed(" + request + "): " + ret);
    }

    return ret;
}
 
Example #14
Source File: TestDefaultPolicyResourceMatcher.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public RangerAccessResource deserialize(JsonElement jsonObj, Type type,
										JsonDeserializationContext context) throws JsonParseException {
	return gsonBuilder.fromJson(jsonObj, RangerAccessResourceImpl.class);
}
 
Example #15
Source File: RangerDefaultPolicyResourceMatcher.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isMatch(RangerPolicy policy, MatchScope scope, Map<String, Object> evalContext) {
    boolean ret = false;

    RangerPerfTracer perf = null;

    if(RangerPerfTracer.isPerfTraceEnabled(PERF_POLICY_RESOURCE_MATCHER_MATCH_LOG)) {
        perf = RangerPerfTracer.getPerfTracer(PERF_POLICY_RESOURCE_MATCHER_MATCH_LOG, "RangerDefaultPolicyResourceMatcher.getPoliciesNonLegacy()");
    }

    Map<String, RangerPolicyResource> resources = policy.getResources();

    if (policy.getPolicyType() == policyType && MapUtils.isNotEmpty(resources)) {
        List<RangerResourceDef> hierarchy = getMatchingHierarchy(resources.keySet());

        if (CollectionUtils.isNotEmpty(hierarchy)) {
            MatchType                matchType      = MatchType.NONE;
            RangerAccessResourceImpl accessResource = new RangerAccessResourceImpl();

            accessResource.setServiceDef(serviceDef);

            // Build up accessResource resourceDef by resourceDef.
            // For each resourceDef,
            //         examine policy-values one by one.
            //         The first value that is acceptable, that is,
            //             value matches in any way, is used for that resourceDef, and
            //            next resourceDef is processed.
            //         If none of the values matches, the policy as a whole definitely will not match,
            //        therefore, the match is failed
            // After all resourceDefs are processed, and some match is achieved at every
            // level, the final matchType (which is for the entire policy) is checked against
            // requested scope to determine the match-result.

            // Unit tests in TestDefaultPolicyResourceForPolicy.java, TestDefaultPolicyResourceMatcher.java
            // test_defaultpolicyresourcematcher_for_hdfs_policy.json, and
            // test_defaultpolicyresourcematcher_for_hive_policy.json, and
            // test_defaultPolicyResourceMatcher.json

            boolean skipped = false;

            for (RangerResourceDef resourceDef : hierarchy) {
                String               name           = resourceDef.getName();
                RangerPolicyResource policyResource = resources.get(name);

                if (policyResource != null && CollectionUtils.isNotEmpty(policyResource.getValues())) {
                    ret       = false;
                    matchType = MatchType.NONE;

                    if (!skipped) {
                        for (String value : policyResource.getValues()) {
                            accessResource.setValue(name, value);

                            matchType = getMatchType(accessResource, evalContext);

                            if (matchType != MatchType.NONE) { // One value for this resourceDef matched
                                ret = true;
                                break;
                            }
                        }
                    } else {
                        break;
                    }
                } else {
                    skipped = true;
                }

                if (!ret) { // None of the values specified for this resourceDef matched, no point in continuing with next resourceDef
                    break;
                }
            }

            ret = ret && isMatch(scope, matchType);
        }
    }

    RangerPerfTracer.log(perf);

    return ret;
}
 
Example #16
Source File: RangerTagEnricher.java    From ranger with Apache License 2.0 4 votes vote down vote up
private boolean removeOldServiceResource(RangerServiceResource serviceResource, List<RangerServiceResourceMatcher> resourceMatchers, Map<String, RangerResourceTrie<RangerServiceResourceMatcher>> resourceTries) {
	boolean ret = true;

	if (enrichedServiceTags != null) {

		if (LOG.isDebugEnabled()) {
			LOG.debug("Removing service-resource:[" + serviceResource + "] from trie-map");
		}

		// Remove existing serviceResource from the copy

		RangerAccessResourceImpl accessResource = new RangerAccessResourceImpl();

		for (Map.Entry<String, RangerPolicy.RangerPolicyResource> entry : serviceResource.getResourceElements().entrySet()) {
			accessResource.setValue(entry.getKey(), entry.getValue());
		}
		if (LOG.isDebugEnabled()) {
			LOG.debug("RangerAccessResource:[" + accessResource + "] created to represent service-resource[" + serviceResource + "] to find evaluators from trie-map");
		}

		List<RangerServiceResourceMatcher> oldMatchers = getEvaluators(accessResource, enrichedServiceTags);

		if (LOG.isDebugEnabled()) {
			LOG.debug("Found [" + oldMatchers.size() + "] matchers for service-resource[" + serviceResource + "]");
		}

		for (RangerServiceResourceMatcher matcher : oldMatchers) {

			for (String resourceDefName : serviceResource.getResourceElements().keySet()) {
				RangerResourceTrie<RangerServiceResourceMatcher> trie = resourceTries.get(resourceDefName);
				if (trie != null) {
					trie.delete(serviceResource.getResourceElements().get(resourceDefName), matcher);
				} else {
					LOG.error("Cannot find resourceDef with name:[" + resourceDefName + "]. Should NOT happen!!");
					LOG.error("Setting tagVersion to -1 to ensure that in the next download all tags are downloaded");
					ret = false;
					break;
				}
			}
		}

		// Remove old resource matchers
		if (ret) {
			resourceMatchers.removeAll(oldMatchers);

			if (LOG.isDebugEnabled()) {
				LOG.debug("Found and removed [" + oldMatchers.size() + "] matchers for service-resource[" + serviceResource + "] from trie-map");
			}
		}
	}
	return ret;
}
 
Example #17
Source File: TestDefaultPolicyResourceMatcherForPolicy.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public RangerAccessResource deserialize(JsonElement jsonObj, Type type,
										JsonDeserializationContext context) throws JsonParseException {
	return gsonBuilder.fromJson(jsonObj, RangerAccessResourceImpl.class);
}
 
Example #18
Source File: RangerAtlasAuthorizer.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isAccessAllowed(AtlasTypeAccessRequest request) throws AtlasAuthorizationException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> isAccessAllowed(" + request + ")");
    }

    final boolean    ret;
    RangerPerfTracer perf = null;

    try {
        if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
            perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "RangerAtlasAuthorizer.isAccessAllowed(" + request + ")");
        }

        final String typeName     = request.getTypeDef() != null ? request.getTypeDef().getName() : null;
        final String typeCategory = request.getTypeDef() != null && request.getTypeDef().getCategory() != null ? request.getTypeDef().getCategory().name() : null;
        final String action       = request.getAction() != null ? request.getAction().getType() : null;

        RangerAccessResourceImpl rangerResource = new RangerAccessResourceImpl();

        rangerResource.setValue(RESOURCE_TYPE_NAME, typeName);
        rangerResource.setValue(RESOURCE_TYPE_CATEGORY, typeCategory);

        RangerAccessRequestImpl rangerRequest = new RangerAccessRequestImpl(rangerResource, action, request.getUser(), request.getUserGroups(), null);
        rangerRequest.setClientIPAddress(request.getClientIPAddress());
        rangerRequest.setAccessTime(request.getAccessTime());
        rangerRequest.setAction(action);
        rangerRequest.setForwardedAddresses(request.getForwardedAddresses());
        rangerRequest.setRemoteIPAddress(request.getRemoteIPAddress());

        ret = checkAccess(rangerRequest);
    } finally {
        RangerPerfTracer.log(perf);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== isAccessAllowed(" + request + "): " + ret);
    }

    return ret;
}
 
Example #19
Source File: RangerAuthorizationCoprocessor.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public void getUserPermissions(RpcController controller, AccessControlProtos.GetUserPermissionsRequest request,
		RpcCallback<AccessControlProtos.GetUserPermissionsResponse> done) {
	AccessControlProtos.GetUserPermissionsResponse response = null;
	try {
		String operation = "userPermissions";
		final RangerAccessResourceImpl resource = new RangerAccessResourceImpl();
		User user = getActiveUser(null);
		Set<String> groups = _userUtils.getUserGroups(user);
		if (groups.isEmpty() && user.getUGI() != null) {
			String[] groupArray = user.getUGI().getGroupNames();
			if (groupArray != null) {
				groups = Sets.newHashSet(groupArray);
			}
		}
		RangerAccessRequestImpl rangerAccessrequest = new RangerAccessRequestImpl(resource, null,
				_userUtils.getUserAsString(user), groups, null);
		rangerAccessrequest.setAction(operation);
		rangerAccessrequest.setClientIPAddress(getRemoteAddress());
		rangerAccessrequest.setResourceMatchingScope(RangerAccessRequest.ResourceMatchingScope.SELF);
		List<UserPermission> perms = null;
		if (request.getType() == AccessControlProtos.Permission.Type.Table) {
			final TableName table = request.hasTableName() ? ProtobufUtil.toTableName(request.getTableName()) : null;
			requirePermission(null, operation, table.getName(), Action.ADMIN);
			resource.setValue(RangerHBaseResource.KEY_TABLE, table.getNameAsString());
			perms = User.runAsLoginUser(new PrivilegedExceptionAction<List<UserPermission>>() {
				@Override
				public List<UserPermission> run() throws Exception {
					return getUserPermissions(
							hbasePlugin.getResourceACLs(rangerAccessrequest),
							table.getNameAsString(), false);
				}
			});
		} else if (request.getType() == AccessControlProtos.Permission.Type.Namespace) {
			final String namespace = request.getNamespaceName().toStringUtf8();
			requireGlobalPermission(null, "getUserPermissionForNamespace", namespace, Action.ADMIN);
			resource.setValue(RangerHBaseResource.KEY_TABLE, namespace + RangerHBaseResource.NAMESPACE_SEPARATOR);
			rangerAccessrequest.setRequestData(namespace);
			perms = User.runAsLoginUser(new PrivilegedExceptionAction<List<UserPermission>>() {
				@Override
				public List<UserPermission> run() throws Exception {
					return getUserPermissions(
							hbasePlugin.getResourceACLs(rangerAccessrequest),
							namespace, true);
				}
			});
		} else {
			requirePermission(null, "userPermissions", Action.ADMIN);
			perms = User.runAsLoginUser(new PrivilegedExceptionAction<List<UserPermission>>() {
				@Override
				public List<UserPermission> run() throws Exception {
					return getUserPermissions(
							hbasePlugin.getResourceACLs(rangerAccessrequest), null,
							false);
				}
			});
			if (_userUtils.isSuperUser(user)) {
				perms.add(new UserPermission(Bytes.toBytes(_userUtils.getUserAsString(user)),
						AccessControlLists.ACL_TABLE_NAME, null, Action.values()));
			}
		}
		response = AccessControlUtil.buildGetUserPermissionsResponse(perms);
	} catch (IOException ioe) {
		// pass exception back up
		ResponseConverter.setControllerException(controller, ioe);
	}
	done.run(response);
}
 
Example #20
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 #21
Source File: RangerAtlasAuthorizer.java    From ranger with Apache License 2.0 4 votes vote down vote up
private boolean isAccessAllowed(AtlasEntityAccessRequest request, RangerAtlasAuditHandler auditHandler) throws AtlasAuthorizationException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> isAccessAllowed(" + request + ")");
    }

    boolean ret = true;

    try {
        final String                   action         = request.getAction() != null ? request.getAction().getType() : null;
        final Set<String>              entityTypes    = request.getEntityTypeAndAllSuperTypes();
        final String                   entityId       = request.getEntityId();
        final String                   classification = request.getClassification() != null ? request.getClassification().getTypeName() : null;
        final RangerAccessRequestImpl  rangerRequest  = new RangerAccessRequestImpl();
        final RangerAccessResourceImpl rangerResource = new RangerAccessResourceImpl();
        final String                   ownerUser      = request.getEntity() != null ? (String) request.getEntity().getAttribute(RESOURCE_ENTITY_OWNER) : null;

        rangerResource.setValue(RESOURCE_ENTITY_TYPE, entityTypes);
        rangerResource.setValue(RESOURCE_ENTITY_ID, entityId);
        rangerResource.setOwnerUser(ownerUser);
        rangerRequest.setAccessType(action);
        rangerRequest.setAction(action);
        rangerRequest.setUser(request.getUser());
        rangerRequest.setUserGroups(request.getUserGroups());
        rangerRequest.setClientIPAddress(request.getClientIPAddress());
        rangerRequest.setAccessTime(request.getAccessTime());
        rangerRequest.setResource(rangerResource);
        rangerRequest.setForwardedAddresses(request.getForwardedAddresses());
        rangerRequest.setRemoteIPAddress(request.getRemoteIPAddress());

        if (AtlasPrivilege.ENTITY_ADD_LABEL.equals(request.getAction()) || AtlasPrivilege.ENTITY_REMOVE_LABEL.equals(request.getAction())) {
            rangerResource.setValue(RESOURCE_ENTITY_LABEL, request.getLabel());
        } else if (AtlasPrivilege.ENTITY_UPDATE_BUSINESS_METADATA.equals(request.getAction())) {
            rangerResource.setValue(RESOURCE_ENTITY_BUSINESS_METADATA, request.getBusinessMetadata());
        }

        if (StringUtils.isNotEmpty(classification)) {
            rangerResource.setValue(RESOURCE_ENTITY_CLASSIFICATION, request.getClassificationTypeAndAllSuperTypes(classification));

            ret = checkAccess(rangerRequest, auditHandler);
        }

        if (ret) {
            if (CollectionUtils.isNotEmpty(request.getEntityClassifications())) {
                // check authorization for each classification
                for (String classificationToAuthorize : request.getEntityClassifications()) {
                    rangerResource.setValue(RESOURCE_ENTITY_CLASSIFICATION, request.getClassificationTypeAndAllSuperTypes(classificationToAuthorize));

                    ret = checkAccess(rangerRequest, auditHandler);

                    if (!ret) {
                        break;
                    }
                }
            } else {
                rangerResource.setValue(RESOURCE_ENTITY_CLASSIFICATION, ENTITY_NOT_CLASSIFIED);

                ret = checkAccess(rangerRequest, auditHandler);
            }
        }

    } finally {
        if(auditHandler != null) {
            auditHandler.flushAudit();
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== isAccessAllowed(" + request + "): " + ret);
    }

    return ret;
}
 
Example #22
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 #23
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 #24
Source File: ServiceREST.java    From ranger with Apache License 2.0 4 votes vote down vote up
@GET
@Path("/policies/{serviceDefName}/for-resource")
@Produces({ "application/json", "application/xml" })
public List<RangerPolicy> getPoliciesForResource(@PathParam("serviceDefName") String serviceDefName,
											  @DefaultValue("") @QueryParam("serviceName") String serviceName,
											  @Context HttpServletRequest request) {
	if (LOG.isDebugEnabled()) {
		LOG.debug("==> ServiceREST.getPoliciesForResource(service-type=" + serviceDefName + ", service-name=" + serviceName + ")");
	}

	List<RangerPolicy> ret = new ArrayList<>();

	List<RangerService> services = new ArrayList<>();
	Map<String, Object> resource = new HashMap<>();

	String validationMessage = validateResourcePoliciesRequest(serviceDefName, serviceName, request, services, resource);

	if (StringUtils.isNotEmpty(validationMessage)) {
		LOG.error("Invalid request: [" + validationMessage + "]");
		throw restErrorUtil.createRESTException(validationMessage,
				MessageEnums.INVALID_INPUT_DATA);
	} else {
		RangerService service = services.get(0);
		if (LOG.isDebugEnabled()) {
			LOG.debug("getServicePolicies with service-name=" + service.getName());
		}

		RangerPolicyAdmin policyAdmin = null;

		try {
			policyAdmin = getPolicyAdminForSearch(service.getName());
		} catch (Exception e) {
			LOG.error("Cannot initialize Policy-Engine", e);
			throw restErrorUtil.createRESTException("Cannot initialize Policy Engine",
					MessageEnums.ERROR_SYSTEM);
		}

		if (policyAdmin != null) {
			ret = policyAdmin.getMatchingPolicies(new RangerAccessResourceImpl(resource));
		}

	}

	if (LOG.isDebugEnabled()) {
		LOG.debug("<== ServiceREST.getPoliciesForResource(service-type=" + serviceDefName + ", service-name=" + serviceName + ") : " + ret.toString());
	}
	return ret;
}
 
Example #25
Source File: RangerResourceDeserializer.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public RangerAccessResource deserialize(JsonElement jsonObj, Type type, JsonDeserializationContext context) throws JsonParseException {
	return gsonBuilder.create().fromJson(jsonObj, RangerAccessResourceImpl.class);
}
 
Example #26
Source File: RangerSchemaRegistryAuthorizerImplTest.java    From registry with Apache License 2.0 4 votes vote down vote up
@Test
public void registryResource2RangerResource() {
    RangerSchemaRegistryAuthorizerImpl rangerSchemaRegistryAuthorizer =
            (RangerSchemaRegistryAuthorizerImpl) authorizer;

    Authorizer.Resource serde = new Authorizer.SerdeResource();
    RangerAccessResourceImpl rangerAccessResource =
            rangerSchemaRegistryAuthorizer.registryResource2RangerResource(serde);
    assertThat(rangerAccessResource.getKeys().size(), is(1));
    assertTrue(rangerAccessResource.exists("serde"));

    Authorizer.Resource schema =
            new Authorizer.SchemaMetadataResource("Group", "Schema");
    rangerAccessResource = rangerSchemaRegistryAuthorizer.registryResource2RangerResource(schema);
    assertThat(rangerAccessResource.getKeys().size(), is(2));
    assertTrue(rangerAccessResource.exists("schema-group"));
    assertThat(rangerAccessResource.getValue("schema-group"), is("Group"));
    assertTrue(rangerAccessResource.exists("schema-metadata"));
    assertThat(rangerAccessResource.getValue("schema-metadata"), is("Schema"));

    Authorizer.Resource branch =
            new Authorizer.SchemaBranchResource("Group", "Schema", "Branch");
    rangerAccessResource = rangerSchemaRegistryAuthorizer.registryResource2RangerResource(branch);
    assertThat(rangerAccessResource.getKeys().size(), is(3));
    assertTrue(rangerAccessResource.exists("schema-group"));
    assertThat(rangerAccessResource.getValue("schema-group"), is("Group"));
    assertTrue(rangerAccessResource.exists("schema-metadata"));
    assertThat(rangerAccessResource.getValue("schema-metadata"), is("Schema"));
    assertTrue(rangerAccessResource.exists("schema-branch"));
    assertThat(rangerAccessResource.getValue("schema-branch"), is("Branch"));

    Authorizer.Resource version =
            new Authorizer.SchemaVersionResource("Group", "Schema", "Branch");
    rangerAccessResource = rangerSchemaRegistryAuthorizer.registryResource2RangerResource(version);
    assertThat(rangerAccessResource.getKeys().size(), is(4));
    assertTrue(rangerAccessResource.exists("schema-group"));
    assertThat(rangerAccessResource.getValue("schema-group"), is("Group"));
    assertTrue(rangerAccessResource.exists("schema-metadata"));
    assertThat(rangerAccessResource.getValue("schema-metadata"), is("Schema"));
    assertTrue(rangerAccessResource.exists("schema-branch"));
    assertThat(rangerAccessResource.getValue("schema-branch"), is("Branch"));
    assertTrue(rangerAccessResource.exists("schema-version"));

}
 
Example #27
Source File: RangerSchemaRegistryAuthorizerImpl.java    From registry with Apache License 2.0 4 votes vote down vote up
boolean authorizeRangerSchemaRegistryResource(AccessType accessType, UserAndGroups userAndGroups) {
    RangerAccessResourceImpl resource = new RangerAccessResourceImpl();
    resource.setValue(RANGER_RESOURCE_REGISTRY_SERVICE, "ANY_VALUE");

    return authorize(resource, accessType, userAndGroups);
}
 
Example #28
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 #29
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();
}