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

The following examples show how to use org.apache.ranger.plugin.policyengine.RangerAccessRequestImpl. 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: 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 #2
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 #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: RangerCustomConditionMatcherTest.java    From ranger with Apache License 2.0 6 votes vote down vote up
RangerAccessRequest createRequest(List<String> resourceTags) {
	RangerAccessResource                  resource          = mock(RangerAccessResource.class);
	RangerAccessRequest                   request           = new RangerAccessRequestImpl(resource,"dummy","test", null, null);
	Set<RangerTagForEval>                 rangerTagForEvals = new HashSet<>();
	RangerPolicyResourceMatcher.MatchType matchType         = RangerPolicyResourceMatcher.MatchType.NONE;

	if (resourceTags != null) {
		for (String resourceTag : resourceTags) {
			RangerTag tag = new RangerTag(UUID.randomUUID().toString(), resourceTag, null, null, null, null);
			rangerTagForEvals.add(new RangerTagForEval(tag, matchType));
		}
		request.getContext().put("TAGS", rangerTagForEvals);
	}  else {
		request.getContext().put("TAGS", null);
	}

	return request;
}
 
Example #5
Source File: RangerPolicyAdminImpl.java    From ranger with Apache License 2.0 6 votes vote down vote up
private List<RangerPolicy> getMatchingPolicies(RangerAccessResource resource, String accessType) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerPolicyAdminImpl.getMatchingPolicies(" + resource + ", " + accessType + ")");
    }

    List<RangerPolicy>      ret     = new ArrayList<>();
    RangerAccessRequestImpl request = new RangerAccessRequestImpl(resource, accessType, null, null, null);

    requestProcessor.preProcess(request);

    Set<String> zoneNames = policyEngine.getMatchedZonesForResourceAndChildren(resource);

    if (CollectionUtils.isEmpty(zoneNames)) {
        getMatchingPoliciesForZone(request, null, ret);
    } else {
        for (String zoneName : zoneNames) {
            getMatchingPoliciesForZone(request, zoneName, ret);
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerPolicyAdminImpl.getMatchingPolicies(" + resource + ", " + accessType + ") : " + ret.size());
    }

    return ret;
}
 
Example #6
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 #7
Source File: RangerAtlasAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
private boolean checkAccess(RangerAccessRequestImpl request, RangerAtlasAuditHandler auditHandler) {
    boolean          ret    = false;
    RangerBasePlugin plugin = atlasPlugin;

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

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

    return ret;
}
 
Example #8
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 #9
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 #10
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 #11
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 #12
Source File: RangerPolicyFactory.java    From ranger with Apache License 2.0 5 votes vote down vote up
/**
 * Generates and returns a list of {@link RangerAccessRequest requests}
 * @param nubmerOfRequests the number of requests to generate.
 * @return
 */
public static List<RangerAccessRequest> createAccessRequests(int nubmerOfRequests) {
	List<RangerAccessRequest> result = Lists.newArrayList();
	Gson gson = buildGson();
	String template = readResourceFile("/testdata/single-request-template.json");
	for (int i = 0; i < nubmerOfRequests; i++) {
		RangerAccessRequestImpl accessRequest = gson.fromJson(template, RangerAccessRequestImpl.class);
		result.add(mutate(accessRequest, isAllowed()));
	}
	return result;
}
 
Example #13
Source File: TestPolicyEngine.java    From ranger with Apache License 2.0 5 votes vote down vote up
@Override
public RangerAccessRequest deserialize(JsonElement jsonObj, Type type,
		JsonDeserializationContext context) throws JsonParseException {
	RangerAccessRequestImpl ret = gsonBuilder.fromJson(jsonObj, RangerAccessRequestImpl.class);

	ret.setAccessType(ret.getAccessType()); // to force computation of isAccessTypeAny and isAccessTypeDelegatedAdmin

	return ret;
}
 
Example #14
Source File: RangerSolrAuthorizer.java    From ranger with Apache License 2.0 5 votes vote down vote up
private RangerAccessRequestImpl createBaseRequest(String userName,
		Set<String> userGroups, String ip, Date eventTime) {
	RangerAccessRequestImpl rangerRequest = new RangerAccessRequestImpl();
	if (userName != null && !userName.isEmpty()) {
		rangerRequest.setUser(userName);
	}
	if (userGroups != null && userGroups.size() > 0) {
		rangerRequest.setUserGroups(userGroups);
	}
	if (ip != null && !ip.isEmpty()) {
		rangerRequest.setClientIPAddress(ip);
	}
	rangerRequest.setAccessTime(eventTime);
	return rangerRequest;
}
 
Example #15
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 #16
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 #17
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 #18
Source File: RangerDefaultRequestProcessor.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public void preProcess(RangerAccessRequest request) {

    setResourceServiceDef(request);
    if (request instanceof RangerAccessRequestImpl) {
        RangerAccessRequestImpl reqImpl = (RangerAccessRequestImpl) request;

        if (reqImpl.getClientIPAddress() == null) {
            reqImpl.extractAndSetClientIPAddress(policyEngine.getUseForwardedIPAddress(), policyEngine.getTrustedProxyAddresses());
        }

        if(policyEngine.getPluginContext() != null) {
            if (reqImpl.getClusterName() == null) {
                reqImpl.setClusterName(policyEngine.getPluginContext().getClusterName());
            }

            if (reqImpl.getClusterType() == null) {
                reqImpl.setClusterType(policyEngine.getPluginContext().getClusterType());
            }
        }
    }

    RangerAccessRequestUtil.setCurrentUserInContext(request.getContext(), request.getUser());

    String owner = request.getResource() != null ? request.getResource().getOwnerUser() : null;

    if (StringUtils.isNotEmpty(owner)) {
        RangerAccessRequestUtil.setOwnerInContext(request.getContext(), owner);
    }

    Set<String> roles = request.getUserRoles();
    if (CollectionUtils.isEmpty(roles)) {
        roles = policyEngine.getPluginContext().getAuthContext().getRolesForUserAndGroups(request.getUser(), request.getUserGroups());
    }

    if (CollectionUtils.isNotEmpty(roles)) {
        RangerAccessRequestUtil.setCurrentUserRolesInContext(request.getContext(), roles);
    }

    enrich(request);
}
 
Example #19
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 #20
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 #21
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 #22
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 #23
Source File: RangerHiveAuthorizer.java    From ranger with Apache License 2.0 4 votes vote down vote up
private RangerResourceACLs getRangerResourceACLs(HivePrivilegeObject hiveObject) {

		RangerResourceACLs ret = null;

		if (LOG.isDebugEnabled()) {
			LOG.debug("==> RangerHivePolicyProvider.getRangerResourceACLs:[" + hiveObject + "]");
		}

		RangerHiveResource hiveResource = RangerHiveAuthorizer.createHiveResource(hiveObject);
		RangerAccessRequestImpl request = new RangerAccessRequestImpl(hiveResource, RangerPolicyEngine.ANY_ACCESS, null, null, null);

		ret = hivePlugin.getResourceACLs(request);

		if (LOG.isDebugEnabled()) {
			LOG.debug("<== RangerHivePolicyProvider.getRangerResourceACLs:[" + hiveObject + "], Computed ACLS:[" + ret + "]");
		}

		return ret;
	}
 
Example #24
Source File: RangerHivePolicyProvider.java    From ranger with Apache License 2.0 4 votes vote down vote up
public HiveResourceACLs getResourceACLs(RangerHiveResource hiveResource) {
 HiveResourceACLs ret;

 RangerAccessRequestImpl request = new RangerAccessRequestImpl(hiveResource, RangerPolicyEngine.ANY_ACCESS, null, null, null);

 RangerResourceACLs acls = rangerPlugin.getResourceACLs(request);

 if (LOG.isDebugEnabled()) {
 	LOG.debug("HiveResource:[" + hiveResource.getAsString() + "], Computed ACLS:[" + acls + "]");
 }

 Map<String, Map<HiveResourceACLs.Privilege, HiveResourceACLs.AccessResult>> userPermissions = convertRangerACLsToHiveACLs(acls.getUserACLs());
 Map<String, Map<HiveResourceACLs.Privilege, HiveResourceACLs.AccessResult>> groupPermissions = convertRangerACLsToHiveACLs(acls.getGroupACLs());

 ret = new RangerHiveResourceACLs(userPermissions, groupPermissions);

 return ret;
}
 
Example #25
Source File: RangerAccessRequestDeserializer.java    From ranger with Apache License 2.0 4 votes vote down vote up
@Override
public RangerAccessRequest deserialize(JsonElement jsonObj, Type type, JsonDeserializationContext context) throws JsonParseException {
	RangerAccessRequestImpl ret = gsonBuilder.create().fromJson(jsonObj, RangerAccessRequestImpl.class);
	ret.setAccessType(ret.getAccessType()); // to force computation of isAccessTypeAny and isAccessTypeDelegatedAdmin
	return ret;
}
 
Example #26
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 #27
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();
}