Search in sources :

Example 1 with PolicyEvaluator

use of com.sun.identity.policy.PolicyEvaluator in project OpenAM by OpenRock.

the class EvaluatePolicyServlet method processRequest.

/**
     * Reads the resource which the user needs to access from the servlet
     * request parameter <code>resource</code>.
     * if the user's session is invalid, the user gets redirected to the 
     * amserver login page to log in first.
     * Once the session is valid, the access permissions for the requested 
     * resource  is computed and sent back in the servlet response.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException
     * @throws java.io.IOException
     */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
    try {
        SSOTokenManager mgr = SSOTokenManager.getInstance();
        SSOToken ssoToken = mgr.createSSOToken(request);
        if (mgr.isValidToken(ssoToken)) {
            if (ssoToken.getProperty(Constants.UNIVERSAL_IDENTIFIER) != null) {
                debug.message("UNIV ID in ssoToken:" + ssoToken.getProperty(Constants.UNIVERSAL_IDENTIFIER));
            } else {
                debug.message("univ id is null");
                if (debug.messageEnabled()) {
                    debug.message("principal:" + ssoToken.getPrincipal().getName());
                }
            }
            String resource = request.getParameter("resource");
            PolicyEvaluator pe = new PolicyEvaluator(WEB_AGENT_SERVICE);
            Set actions = new HashSet();
            actions.add("GET");
            PolicyDecision pd = pe.getPolicyDecision(ssoToken, resource, actions, null);
            boolean allowed = pe.isAllowed(ssoToken, resource, "GET", null);
            StringBuffer message = new StringBuffer("<pre>");
            message.append("isAllowed() for ").append(resource).append(" action:GET is:   ");
            message = message.append(allowed);
            message.append(NEWLINE);
            message.append(NEWLINE);
            message.append("getPolicyDecision() for ").append(resource).append(" action:GET is:");
            message.append(NEWLINE);
            message.append(XMLUtils.escapeSpecialCharacters(pd.toXML()));
            message.append("</pre>");
            sendResponse(response, message.toString());
        }
    } catch (Exception ire) {
        debug.error("processRequest::exception:", ire);
        String requestUrl = request.getRequestURL().toString();
        String redirectUrl = serverUrl + "?goto=" + requestUrl;
        response.sendRedirect(redirectUrl);
        return;
    }
}
Also used : SSOTokenManager(com.iplanet.sso.SSOTokenManager) PolicyDecision(com.sun.identity.policy.PolicyDecision) SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) PolicyEvaluator(com.sun.identity.policy.PolicyEvaluator) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) HashSet(java.util.HashSet)

Example 2 with PolicyEvaluator

use of com.sun.identity.policy.PolicyEvaluator in project OpenAM by OpenRock.

the class DelegationPolicyImpl method initialize.

/**
     * Initialize (or configure) the <code>DelegationInterface</code>
     * object. Usually it will be initialized with the environmrnt
     * parameters set by the system administrator via Service management service.
     *
     * @param token <code>SSOToken</code> of an administrator
     * @param configParams configuration parameters as a <code>Map</code>.
     * The values in the <code>Map</code> is <code>java.util.Set</code>,
     * which contains one or more configuration parameters.
     *
     * @throws DelegationException if an error occurred during
     * initialization of <code>DelegationInterface</code> instance
     */
public void initialize(SSOToken token, Map configParams) throws DelegationException {
    this.appToken = token;
    try {
        maxCacheSize = SystemProperties.getAsInt(CONFIGURED_CACHE_SIZE, DEFAULT_CACHE_SIZE);
        // specifying cache size as 0 would virtually disable the delegation cache.
        if (maxCacheSize < 0) {
            maxCacheSize = DEFAULT_CACHE_SIZE;
        }
        delegationCache = new Cache(maxCacheSize);
        if (DelegationManager.debug.messageEnabled()) {
            DelegationManager.debug.message("DelegationPolicyImpl.initialize(): cache size=" + maxCacheSize);
        }
        pe = new PolicyEvaluator(POLICY_REPOSITORY_REALM, DelegationManager.DELEGATION_SERVICE);
        // listen on delegation policy changes. once there is 
        // delegation policy change, we need to update the cache.
        pe.addPolicyListener(this);
        // listen on root realm subject changes.
        AMIdentityRepository idRepo = new AMIdentityRepository(appToken, "/");
        idRepo.addEventListener(this);
        if (DelegationManager.debug.messageEnabled()) {
            DelegationManager.debug.message("DelegationPolicyImpl: IdRepo event listener added " + "for root realm.");
        }
        // listen on sub realm subject changes.     
        OrganizationConfigManager ocm = new OrganizationConfigManager(appToken, "/");
        Set orgNames = ocm.getSubOrganizationNames("*", true);
        if ((orgNames != null) && (!orgNames.isEmpty())) {
            Iterator it = orgNames.iterator();
            while (it.hasNext()) {
                String org = (String) it.next();
                AMIdentityRepository idr = new AMIdentityRepository(appToken, org);
                idr.addEventListener(this);
                idRepoListeners.put(org, idRepo);
                if (DelegationManager.debug.messageEnabled()) {
                    DelegationManager.debug.message("DelegationPolicyImpl: IdRepo event listener " + "added for realm (" + org + ").");
                }
            }
        }
        scm = new ServiceConfigManager(PolicyConfig.POLICY_CONFIG_SERVICE, token);
        //DelegationManager.DELEGATION_SERVICE, token);
        /**
             *  listen on org config changes. once there is realm added,
             * or removed, we need to add or remove listeners on the
             * affected realm accordingly.
             */
        scm.addListener(this);
    } catch (Exception e) {
        DelegationManager.debug.error("DelegationPolicyImpl: initialize() failed");
        throw new DelegationException(e);
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) PolicyEvaluator(com.sun.identity.policy.PolicyEvaluator) OrganizationConfigManager(com.sun.identity.sm.OrganizationConfigManager) AMIdentityRepository(com.sun.identity.idm.AMIdentityRepository) Iterator(java.util.Iterator) DelegationException(com.sun.identity.delegation.DelegationException) ServiceConfigManager(com.sun.identity.sm.ServiceConfigManager) DelegationException(com.sun.identity.delegation.DelegationException) PolicyException(com.sun.identity.policy.PolicyException) SSOException(com.iplanet.sso.SSOException) IdRepoException(com.sun.identity.idm.IdRepoException) Cache(com.iplanet.am.util.Cache) SubjectEvaluationCache(com.sun.identity.policy.SubjectEvaluationCache)

Example 3 with PolicyEvaluator

use of com.sun.identity.policy.PolicyEvaluator in project OpenAM by OpenRock.

the class XACMLAuthzDecisionQueryHandler method handleQuery.

/**
     * Processes an XACMLAuthzDecisionQuery and retruns a SAML2 Response.
     *
     * @param pdpEntityId EntityID of PDP
     * @param pepEntityId EntityID of PEP
     * @param samlpRequest SAML2 Request, an XAMLAuthzDecisionQuery
     * @param soapMessage SOAPMessage that carried the SAML2 Request
     * @return SAML2 Response with an XAMLAuthzDecisionStatement
     * @exception SAML2Exception if the query can not be handled
     */
public com.sun.identity.saml2.protocol.Response handleQuery(String pdpEntityId, String pepEntityId, RequestAbstract samlpRequest, SOAPMessage soapMessage) throws SAML2Exception {
    //TODO: logging, i18n
    //TODO: long term, allow different mapper impls for  different
    //combination of pdp, pep
    SubjectMapper subjectMapper = new FMSubjectMapper();
    subjectMapper.initialize(pdpEntityId, pepEntityId, null);
    ResourceMapper resourceMapper = new FMResourceMapper();
    resourceMapper.initialize(pdpEntityId, pepEntityId, null);
    ActionMapper actionMapper = new FMActionMapper();
    actionMapper.initialize(pdpEntityId, pepEntityId, null);
    EnvironmentMapper environmentMapper = new FMEnvironmentMapper();
    environmentMapper.initialize(pdpEntityId, pepEntityId, null);
    ResultMapper resultMapper = new FMResultMapper();
    resultMapper.initialize(pdpEntityId, pepEntityId, null);
    boolean evaluationFailed = false;
    String statusCodeValue = null;
    if (XACMLSDKUtils.debug.messageEnabled()) {
        XACMLSDKUtils.debug.message("XACMLAuthzDecisionQueryHandler.handleQuery(), entering" + ":pdpEntityId=" + pdpEntityId + ":pepEntityId=" + pepEntityId + ":samlpRequest=\n" + samlpRequest.toXMLString(true, true) + ":soapMessage=\n" + soapMessage);
    }
    Request xacmlRequest = ((XACMLAuthzDecisionQuery) samlpRequest).getRequest();
    boolean returnContext = ((XACMLAuthzDecisionQuery) samlpRequest).getReturnContext();
    SSOToken ssoToken = null;
    String resourceName = null;
    String serviceName = null;
    String actionName = null;
    Map environment = null;
    boolean booleanDecision = false;
    try {
        //get native sso token
        ssoToken = (SSOToken) subjectMapper.mapToNativeSubject(xacmlRequest.getSubjects());
        if (ssoToken == null) {
            //TODO: log message and fill missing attribute details 
            statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
            evaluationFailed = true;
        } else {
            if (XACMLSDKUtils.debug.messageEnabled()) {
                XACMLSDKUtils.debug.message("XACMLAuthzDecisionQueryHandler.handleQuery()," + "created ssoToken");
            }
        }
        if (ssoToken != null) {
            //get native service name, resource name 
            List resources = xacmlRequest.getResources();
            Resource resource = null;
            if (!resources.isEmpty()) {
                //We deal with only one resource for now
                resource = (Resource) resources.get(0);
            }
            if (resource != null) {
                String[] resourceService = resourceMapper.mapToNativeResource(resource);
                if (resourceService != null) {
                    if (resourceService.length > 0) {
                        resourceName = resourceService[0];
                    }
                    if (resourceService.length > 1) {
                        serviceName = resourceService[1];
                    }
                }
            }
            if (resourceName == null) {
                //TODO: log message and fill missing attribute details 
                statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
                evaluationFailed = true;
            }
            if (serviceName == null) {
                //TODO: log message and fill missing attribute details
                throw new SAML2Exception(XACMLSDKUtils.xacmlResourceBundle.getString("missing_attribute"));
            }
        }
        if (serviceName != null) {
            //get native action name
            if (serviceName != null) {
                actionName = actionMapper.mapToNativeAction(xacmlRequest.getAction(), serviceName);
            }
            if (actionName == null) {
                //TODO: log message and fill missing attribute details
                statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
                evaluationFailed = true;
            }
        }
    //get environment map
    /*
            environment = environmentMapper.mapToNativeEnvironment(
                    xacmlRequest.getEnvironment(), 
                    xacmlRequest.getSubjects());
            */
    } catch (XACMLException xe) {
        statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
        evaluationFailed = true;
        if (XACMLSDKUtils.debug.warningEnabled()) {
            XACMLSDKUtils.debug.warning("XACMLAuthzDecisionQueryHandler.handleQuery()," + "caught exception", xe);
        }
    }
    //get native policy deicison using native policy evaluator
    if (!evaluationFailed) {
        try {
            PolicyEvaluator pe = new PolicyEvaluator(serviceName);
            booleanDecision = pe.isAllowed(ssoToken, resourceName, actionName, environment);
        } catch (SSOException ssoe) {
            if (XACMLSDKUtils.debug.warningEnabled()) {
                XACMLSDKUtils.debug.warning("XACMLAuthzDecisionQueryHandler.handleQuery()," + "caught exception", ssoe);
            }
            evaluationFailed = true;
        } catch (PolicyException pe) {
            if (XACMLSDKUtils.debug.warningEnabled()) {
                XACMLSDKUtils.debug.warning("XACMLAuthzDecisionQueryHandler.handleQuery()," + "caught exception", pe);
            }
            evaluationFailed = true;
        }
    }
    //decision: Indeterminate, Deny, Permit, NotApplicable
    //status code: missing_attribute, syntax_error, processing_error, ok
    Decision decision = ContextFactory.getInstance().createDecision();
    Status status = ContextFactory.getInstance().createStatus();
    StatusCode code = ContextFactory.getInstance().createStatusCode();
    StatusMessage message = ContextFactory.getInstance().createStatusMessage();
    StatusDetail detail = ContextFactory.getInstance().createStatusDetail();
    detail.getElement().insertBefore(detail.getElement().cloneNode(true), null);
    if (evaluationFailed) {
        decision.setValue(XACMLConstants.INDETERMINATE);
        if (statusCodeValue == null) {
            statusCodeValue = XACMLConstants.STATUS_CODE_PROCESSING_ERROR;
        }
        code.setValue(statusCodeValue);
        //TODO: i18n
        message.setValue("processing_error");
    } else if (booleanDecision) {
        decision.setValue(XACMLConstants.PERMIT);
        code.setValue(XACMLConstants.STATUS_CODE_OK);
        //TODO: i18n
        message.setValue("ok");
    } else {
        decision.setValue(XACMLConstants.DENY);
        code.setValue(XACMLConstants.STATUS_CODE_OK);
        //TODO: i18n
        message.setValue("ok");
    }
    Result result = ContextFactory.getInstance().createResult();
    String resourceId = resourceName;
    List resources = xacmlRequest.getResources();
    Resource resource = null;
    if (!resources.isEmpty()) {
        //We deal with only one resource for now
        resource = (Resource) resources.get(0);
        if (resource != null) {
            List attributes = resource.getAttributes();
            if (attributes != null) {
                for (int count = 0; count < attributes.size(); count++) {
                    Attribute attr = (Attribute) attributes.get(count);
                    if (attr != null) {
                        URI tmpURI = attr.getAttributeId();
                        if (tmpURI.toString().equals(XACMLConstants.RESOURCE_ID)) {
                            Element element = (Element) attr.getAttributeValues().get(0);
                            resourceId = XMLUtils.getElementValue(element);
                            break;
                        }
                    }
                }
            }
        }
    }
    result.setResourceId(resourceId);
    result.setDecision(decision);
    status.setStatusCode(code);
    status.setStatusMessage(message);
    status.setStatusDetail(detail);
    result.setStatus(status);
    Response response = ContextFactory.getInstance().createResponse();
    response.addResult(result);
    XACMLAuthzDecisionStatement statement = ContextFactory.getInstance().createXACMLAuthzDecisionStatement();
    statement.setResponse(response);
    if (returnContext) {
        statement.setRequest(xacmlRequest);
    }
    com.sun.identity.saml2.protocol.Response samlpResponse = createSamlpResponse(statement, status.getStatusCode().getValue());
    if (XACMLSDKUtils.debug.messageEnabled()) {
        XACMLSDKUtils.debug.message("XACMLAuthzDecisionQueryHandler.handleQuery(), returning" + ":samlResponse=\n" + samlpResponse.toXMLString(true, true));
    }
    return samlpResponse;
}
Also used : SSOToken(com.iplanet.sso.SSOToken) Attribute(com.sun.identity.xacml.context.Attribute) Element(org.w3c.dom.Element) SSOException(com.iplanet.sso.SSOException) StatusCode(com.sun.identity.xacml.context.StatusCode) URI(java.net.URI) Result(com.sun.identity.xacml.context.Result) ResourceResult(com.sun.identity.policy.ResourceResult) ActionMapper(com.sun.identity.xacml.spi.ActionMapper) XACMLAuthzDecisionStatement(com.sun.identity.xacml.saml2.XACMLAuthzDecisionStatement) PolicyEvaluator(com.sun.identity.policy.PolicyEvaluator) SubjectMapper(com.sun.identity.xacml.spi.SubjectMapper) PolicyException(com.sun.identity.policy.PolicyException) ResourceMapper(com.sun.identity.xacml.spi.ResourceMapper) ArrayList(java.util.ArrayList) List(java.util.List) Status(com.sun.identity.xacml.context.Status) Request(com.sun.identity.xacml.context.Request) Resource(com.sun.identity.xacml.context.Resource) EnvironmentMapper(com.sun.identity.xacml.spi.EnvironmentMapper) Decision(com.sun.identity.xacml.context.Decision) XACMLException(com.sun.identity.xacml.common.XACMLException) StatusMessage(com.sun.identity.xacml.context.StatusMessage) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Response(com.sun.identity.xacml.context.Response) ResultMapper(com.sun.identity.xacml.spi.ResultMapper) StatusDetail(com.sun.identity.xacml.context.StatusDetail) XACMLAuthzDecisionQuery(com.sun.identity.xacml.saml2.XACMLAuthzDecisionQuery) Map(java.util.Map)

Example 4 with PolicyEvaluator

use of com.sun.identity.policy.PolicyEvaluator in project OpenAM by OpenRock.

the class PolicyRequestHandler method addPolicyListener.

/*
     *  Register a policy change listener to the policy framework.
     */
private boolean addPolicyListener(SSOToken appToken, PolicyListenerRequest policyListenerReq, Map<String, Set<String>> appAttributes) {
    if (policyListenerReq == null) {
        debug.error("PolicyRequestHandler.addPolicyListener: " + "invalid policy listener request received");
        return false;
    }
    String serviceTypeName = policyListenerReq.getServiceTypeName();
    String notiURL = policyListenerReq.getNotificationURL();
    if (listenerRegistry.containsKey(notiURL)) {
        if (debug.messageEnabled()) {
            debug.message("PolicyRequestHandler.addPolicyListener: " + "policy listener for service " + serviceTypeName + " has already been registered; the notification URL is " + notiURL);
        }
        return true;
    }
    PolicyEvaluator policyEvaluator = null;
    try {
        // Get an instance of the policy evaluator
        policyEvaluator = getPolicyEvaluator(appToken, serviceTypeName, appAttributes);
        if (policyEvaluator != null) {
            // add the policy listener to the policy framework
            policyEvaluator.addPolicyListener(policyListenerReq);
            listenerRegistry.put(notiURL, policyListenerReq);
            if (debug.messageEnabled()) {
                debug.message("PolicyRequestHandler.addPolicyListener: " + "policy listener for service " + serviceTypeName + " added");
            }
        }
    } catch (PolicyException e) {
        debug.error("PolicyRequestHandler.addPolicyListener: " + "failed to add policy change listener", e);
        return false;
    }
    return true;
}
Also used : PolicyEvaluator(com.sun.identity.policy.PolicyEvaluator) PolicyException(com.sun.identity.policy.PolicyException)

Example 5 with PolicyEvaluator

use of com.sun.identity.policy.PolicyEvaluator in project OpenAM by OpenRock.

the class PolicyRequestHandler method getPolicyEvaluator.

/**
     * Provides an instance of a policy evaluator.
     * <p/>
     * It is understood that serviceName == serviceTypeName == applicationTypeName.
     * <p/>
     * First attempts to provide an evaluator based on a configured realm and application for the subject making
     * the request. If the realm and application are present, then the application's type is retrieved and passed
     * through as the serviceTypeName to the evaluator along with the realm and application name.
     * <p/>
     * If the application name does not exist then the logic falls back to the old behaviour whereby the
     * applicationName is set to the serviceTypeName. This legacy behaviour assumes that an application exists with a
     * name that maps to the passed serviceTypeName.
     *
     * @param appToken
     *         the SSO token of the requester
     * @param serviceTypeName
     *         the service type name
     * @param appAttributes
     *         the app attributes
     *
     * @return an policy evaluator
     *
     * @throws PolicyException
     *         should an error occur during the retrieval of an appropriate policy evaluator
     */
private PolicyEvaluator getPolicyEvaluator(final SSOToken appToken, final String serviceTypeName, final Map<String, Set<String>> appAttributes) throws PolicyException {
    try {
        final String realm = CollectionUtils.getFirstItem(appAttributes.get(EVALUATION_REALM), "/");
        final String applicationName = CollectionUtils.getFirstItem(appAttributes.get(EVALUATION_APPLICATION), serviceTypeName);
        final Subject appSubject = SubjectUtils.createSubject(appToken);
        final Application application = ApplicationManager.getApplication(appSubject, realm, applicationName);
        if (application == null) {
            throw new PolicyException(EntitlementException.RES_BUNDLE_NAME, String.valueOf(EntitlementException.APP_RETRIEVAL_ERROR), new Object[] { realm }, null);
        }
        final String applicationTypeName = application.getApplicationType().getName();
        final String key = realm + "-" + applicationTypeName + "-" + applicationName;
        if (!policyEvaluators.containsKey(key)) {
            synchronized (policyEvaluators) {
                if (!policyEvaluators.containsKey(key)) {
                    policyEvaluators.put(key, new PolicyEvaluator(realm, applicationTypeName, applicationName));
                }
            }
        }
        return policyEvaluators.get(key);
    } catch (SSOException | EntitlementException e) {
        throw new PolicyException(ResBundleUtils.rbName, "unable_to_get_an_evaluator", null, e);
    }
}
Also used : EntitlementException(com.sun.identity.entitlement.EntitlementException) PolicyEvaluator(com.sun.identity.policy.PolicyEvaluator) PolicyException(com.sun.identity.policy.PolicyException) SSOException(com.iplanet.sso.SSOException) Application(com.sun.identity.entitlement.Application) Subject(javax.security.auth.Subject)

Aggregations

PolicyEvaluator (com.sun.identity.policy.PolicyEvaluator)11 PolicyException (com.sun.identity.policy.PolicyException)6 PolicyDecision (com.sun.identity.policy.PolicyDecision)5 HashSet (java.util.HashSet)5 SSOException (com.iplanet.sso.SSOException)4 SSOToken (com.iplanet.sso.SSOToken)4 ResourceResult (com.sun.identity.policy.ResourceResult)4 Set (java.util.Set)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 EntitlementException (com.sun.identity.entitlement.EntitlementException)2 IdRepoException (com.sun.identity.idm.IdRepoException)2 ActionDecision (com.sun.identity.policy.ActionDecision)2 ArrayList (java.util.ArrayList)2 Iterator (java.util.Iterator)2 List (java.util.List)2 Cache (com.iplanet.am.util.Cache)1 ResponseSet (com.iplanet.services.comm.share.ResponseSet)1 SSOTokenManager (com.iplanet.sso.SSOTokenManager)1 AuthContext (com.sun.identity.authentication.AuthContext)1