Search in sources :

Example 86 with PolicyException

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

the class SubOrgReferral method getValidValues.

/**Gets the valid values for this referral 
     * matching a pattern
     * @param token SSOToken
     * @param pattern a pattern to match against the value
     * @return <code>ValidValues</code> object
     * @exception SSOException if <code>SSOToken></code> is not valid
     * @exception PolicyException if unable to get the list of valid
     * names.
     */
public ValidValues getValidValues(SSOToken token, String pattern) throws SSOException, PolicyException {
    Set values = new HashSet();
    int status = ValidValues.SUCCESS;
    try {
        Set orgSet = (Set) _configurationMap.get(PolicyManager.ORGANIZATION_NAME);
        if ((orgSet == null) || (orgSet.isEmpty())) {
            OrgReferral.DEBUG.error("SubOrgReferral.getValidValues(): " + " Organization name not set");
            throw new PolicyException(ResBundleUtils.rbName, "org_name_not_set", null, null);
        }
        Iterator iter = orgSet.iterator();
        String orgName = (String) iter.next();
        OrganizationConfigManager orgConfigManager = new OrganizationConfigManager(token, orgName);
        Set subOrgNames = orgConfigManager.getSubOrganizationNames(pattern, //get only first level children
        false);
        if ((subOrgNames != null) && !subOrgNames.isEmpty()) {
            Iterator subOrgsIter = subOrgNames.iterator();
            while (subOrgsIter.hasNext()) {
                String subOrgName = (String) subOrgsIter.next();
                OrganizationConfigManager subOrgManager = orgConfigManager.getSubOrgConfigManager(subOrgName);
                if (subOrgManager != null) {
                    values.add(subOrgManager.getOrganizationName());
                }
            }
        }
        if (debug.messageEnabled()) {
            debug.message("SubOrgReferral.getValidValues():subOrgNames=" + subOrgNames);
        }
    } catch (SMSException smse) {
        OrgReferral.DEBUG.error("Can not get valid values for referral " + getReferralTypeName() + smse);
        String[] objs = { getReferralTypeName() };
        throw new PolicyException(ResBundleUtils.rbName, "can_not_get_values_for_referral", objs, smse);
    }
    return (new ValidValues(status, values));
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) PolicyException(com.sun.identity.policy.PolicyException) SMSException(com.sun.identity.sm.SMSException) ValidValues(com.sun.identity.policy.ValidValues) OrganizationConfigManager(com.sun.identity.sm.OrganizationConfigManager) Iterator(java.util.Iterator) HashSet(java.util.HashSet)

Example 87 with PolicyException

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

the class SubjectReferentialIntegrityPlugin method postProcessDelete.

/**
     * This implementation would visit all the subjects in policies
     * across all orgs/sub-orgs and remove the subject values
     * corresponding to the deleted entry DN. After removing an entry from a
     * subject, checks if that entry is the only one in the subject to
     * remove the subject as well.
     */
public void postProcessDelete(SSOToken token, String entryDN, Map attributes, boolean softDeleteEnabled, int objectType) throws AMPostCallBackException {
    try {
        if (debug.messageEnabled()) {
            debug.message("ReferentialIntegrityPlugin.postProcessDelete()");
        }
        // check the subject types
        Set objectTypes = new HashSet();
        objectTypes.add(new Integer(AMObject.USER));
        objectTypes.add(new Integer(AMObject.ROLE));
        objectTypes.add(new Integer(AMObject.ORGANIZATION));
        objectTypes.add(new Integer(AMObject.GROUP));
        objectTypes.add(new Integer(AMObject.ASSIGNABLE_DYNAMIC_GROUP));
        objectTypes.add(new Integer(AMObject.DYNAMIC_GROUP));
        objectTypes.add(new Integer(AMObject.FILTERED_ROLE));
        if (objectTypes.contains(new Integer(objectType))) {
            String subOrg, policyName, subjectName;
            Policy policy;
            Subject subject;
            Iterator policyIter, subjectIter;
            // create a DN for the entry to be deleted
            DN entryDName = DN.valueOf(entryDN);
            //a connection to the Identity Server data store.
            AMStoreConnection dpStore = new AMStoreConnection(token);
            DN rootDN = DN.valueOf(SMSEntry.getRootSuffix());
            if (debug.messageEnabled()) {
                debug.message("Searching for all policies from root DN: " + rootDN.toString());
            }
            PolicyManager pm = new PolicyManager(token, rootDN.toString());
            String org = pm.getOrganizationName();
            /**
                 *  find out from org policy config that is the directory
                 *  specified is the local directory
                 */
            Map configParams = PolicyConfig.getPolicyConfig(org);
            String ldapServer = ((String) configParams.get(PolicyConfig.LDAP_SERVER)).toLowerCase();
            boolean localDS = PolicyUtils.isLocalDS(ldapServer);
            /** 
                 * process IdentityServer Role irrespective of local or 
                 * non-local DS
                 */
            if (objectType == AMObject.ROLE) {
                localDS = true;
            }
            if (localDS) {
                AMOrganization rootOrg = (AMOrganization) dpStore.getOrganization(org);
                Set subOrgs = null;
                //all orgs/sub-orgs
                subOrgs = rootOrg.searchSubOrganizations("*", AMConstants.SCOPE_SUB);
                Iterator orgIter = subOrgs.iterator();
                while (orgIter.hasNext()) {
                    subOrg = (String) orgIter.next();
                    if (debug.messageEnabled()) {
                        debug.message("Visiting suborg: " + subOrg);
                    }
                    PolicyManager pmSubOrg = new PolicyManager(token, subOrg);
                    // all policies
                    Set policies = pmSubOrg.getPolicyNames();
                    policyIter = policies.iterator();
                    while (policyIter.hasNext()) {
                        policyName = (String) policyIter.next();
                        if (debug.messageEnabled()) {
                            debug.message("policyName: " + policyName);
                        }
                        policy = pmSubOrg.getPolicy(policyName);
                        // referral policies don't have subjects defined
                        if (!policy.isReferralPolicy()) {
                            // all subjects
                            boolean replacePolicy = false;
                            Set subjectsInPolicy = policy.getSubjectNames();
                            Set subjects = new HashSet();
                            subjects.addAll(subjectsInPolicy);
                            subjectIter = subjects.iterator();
                            while (subjectIter.hasNext()) {
                                subjectName = (String) subjectIter.next();
                                if (debug.messageEnabled()) {
                                    debug.message("subjectName: " + subjectName);
                                }
                                subject = policy.getSubject(subjectName);
                                Set set = subject.getValues();
                                Iterator ite = set.iterator();
                                String str = null;
                                DN strDN = null;
                                while (ite.hasNext()) {
                                    str = (String) ite.next();
                                    strDN = DN.valueOf(str);
                                    if (entryDName.equals(strDN)) {
                                        replacePolicy = true;
                                        if (debug.messageEnabled()) {
                                            debug.message("DNs match, str:" + str + "entryDN:" + entryDN);
                                        }
                                        set.remove(str);
                                        if (set.isEmpty()) {
                                            policy.removeSubject(subjectName);
                                            if (debug.messageEnabled()) {
                                                debug.message("subjectDeleted:" + subjectName);
                                            }
                                        } else {
                                            subject.setValues(set);
                                        }
                                        break;
                                    }
                                // match DNs
                                }
                            // all subject values in the subject
                            }
                            // all subjects in the policy
                            if (replacePolicy) {
                                pmSubOrg.replacePolicy(policy);
                            }
                        }
                    // for referral policies
                    }
                // all policies
                }
            // all orgs
            }
        // localDS check
        }
    // objectType check
    } catch (PolicyException pe) {
        debug.error("ReferentialIntegrityPlugin.postProcessDelete():", pe);
    } catch (SSOException sse) {
        debug.error("ReferentialIntegrityPlugin.postProcessDelete():", sse);
    } catch (Exception e) {
        debug.error("ReferentialIntegrityPlugin.postProcessDelete():", e);
    }
}
Also used : Policy(com.sun.identity.policy.Policy) PolicyManager(com.sun.identity.policy.PolicyManager) Set(java.util.Set) HashSet(java.util.HashSet) DN(org.forgerock.opendj.ldap.DN) SSOException(com.iplanet.sso.SSOException) Subject(com.sun.identity.policy.interfaces.Subject) AMPostCallBackException(com.iplanet.am.sdk.AMPostCallBackException) SSOException(com.iplanet.sso.SSOException) PolicyException(com.sun.identity.policy.PolicyException) AMStoreConnection(com.iplanet.am.sdk.AMStoreConnection) PolicyException(com.sun.identity.policy.PolicyException) AMOrganization(com.iplanet.am.sdk.AMOrganization) Iterator(java.util.Iterator) Map(java.util.Map) HashSet(java.util.HashSet)

Example 88 with PolicyException

use of com.sun.identity.policy.PolicyException 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 89 with PolicyException

use of com.sun.identity.policy.PolicyException 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)

Example 90 with PolicyException

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

the class PolicyRequestHandler method processPolicyRequest.

/**
     * Processes a policy request and return a policy response.
     *
     * @param req a policy request
     * @return its corresponding policy response
     */
private PolicyResponse processPolicyRequest(PolicyRequest req, PLLAuditor auditor) throws PolicyEvaluationException {
    if (debug.messageEnabled()) {
        debug.message("PolicyRequestHandler.processPolicyRequest(): " + " req received:\n" + req.toXMLString());
    }
    PolicyResponse policyRes = new PolicyResponse();
    String requestId = req.getRequestId();
    policyRes.setRequestId(requestId);
    String appSSOTokenIDStr = req.getAppSSOToken();
    SSOToken appToken = null;
    Map<String, Set<String>> appAttributes;
    try {
        appToken = getSSOToken(appSSOTokenIDStr, null);
        appAttributes = IdUtils.getIdentity(appToken).getAttributes();
    } catch (IdRepoException | SSOException | PolicyException pe) {
        if (debug.warningEnabled()) {
            debug.warning("PolicyRequestHandler: Invalid app sso token, " + appSSOTokenIDStr);
        }
        throw new PolicyEvaluationException(PolicyResponse.APP_SSO_TOKEN_INVALID, requestId);
    }
    // set the app token into the ThreadLocal
    AppTokenHandler.set(appToken);
    auditor.setMethod(req.getMethodName());
    auditor.setSsoToken(appToken);
    auditor.setRealm(getFirstItem(appAttributes.get(EVALUATION_REALM), NO_REALM));
    auditor.auditAccessAttempt();
    if (req.getMethodID() == PolicyRequest.POLICY_REQUEST_ADD_POLICY_LISTENER) {
        PolicyListenerRequest plReq = req.getPolicyListenerRequest();
        boolean addListener = addPolicyListener(appToken, plReq, appAttributes);
        if (addListener) {
            policyRes.setMethodID(PolicyResponse.POLICY_ADD_LISTENER_RESPONSE);
            auditor.auditAccessSuccess();
        } else {
            String[] objs = { plReq.getNotificationURL() };
            String message = ResBundleUtils.getString("failed.add.policy.listener", objs);
            policyRes.setExceptionMsg(message);
            policyRes.setMethodID(PolicyResponse.POLICY_EXCEPTION);
            auditor.auditAccessFailure(message);
        }
        return policyRes;
    }
    if (req.getMethodID() == PolicyRequest.POLICY_REQUEST_REMOVE_POLICY_LISTENER) {
        RemoveListenerRequest rmReq = req.getRemoveListenerRequest();
        boolean removeListener = removePolicyListener(appToken, rmReq, appAttributes);
        if (removeListener) {
            policyRes.setMethodID(PolicyResponse.POLICY_REMOVE_LISTENER_RESPONSE);
            auditor.auditAccessSuccess();
        } else {
            String[] objs = { rmReq.getNotificationURL() };
            String message = ResBundleUtils.getString("failed.remove.policy.listener", objs);
            policyRes.setExceptionMsg(message);
            policyRes.setMethodID(PolicyResponse.POLICY_EXCEPTION);
            auditor.auditAccessFailure(message);
        }
        return policyRes;
    }
    if (req.getMethodID() == PolicyRequest.POLICY_REQUEST_ADVICES_HANDLEABLE_BY_AM_REQUEST) {
        if (debug.messageEnabled()) {
            debug.message("PolicyRequestHandler: request to get  " + " advicesHandleableByAM");
        }
        try {
            Set advices = PolicyConfig.getAdvicesHandleableByAM();
            policyRes.setAdvicesHandleableByAMResponse(new AdvicesHandleableByAMResponse(advices));
            policyRes.setMethodID(PolicyResponse.POLICY_ADVICES_HANDLEABLE_BY_AM_RESPONSE);
            auditor.auditAccessSuccess();
        } catch (PolicyException pe) {
            if (debug.warningEnabled()) {
                debug.warning("PolicyRequestHandler: could not get " + " advicesHandleableByAM", pe);
            }
            throw new PolicyEvaluationException(ResBundleUtils.rbName, "could_not_get_advices_handleable_by_am", null, pe, requestId);
        }
        if (debug.messageEnabled()) {
            debug.message("PolicyRequestHandler: returning  " + " advicesHandleableByAM policy response");
        }
        return policyRes;
    }
    if (req.getMethodID() == PolicyRequest.POLICY_REQUEST_GET_RESOURCE_RESULTS) {
        ResourceResultRequest resourceResultReq = req.getResourceResultRequest();
        // Get the user's SSO token id string from the request
        String userSSOTokenIDStr = resourceResultReq.getUserSSOToken();
        SSOToken userToken = null;
        if ((userSSOTokenIDStr != null) && !userSSOTokenIDStr.equals(PolicyUtils.EMPTY_STRING) && !userSSOTokenIDStr.equals(PolicyUtils.NULL_STRING)) {
            try {
                userToken = getSSOToken(userSSOTokenIDStr, appToken);
            } catch (PolicyException pe) {
                if (debug.warningEnabled()) {
                    debug.warning("PolicyRequestHandler: Invalid user sso token, " + userSSOTokenIDStr, pe);
                }
                throw new PolicyEvaluationException(ResBundleUtils.rbName, "user_sso_token_invalid", null, null, requestId);
            }
        }
        Set resourceResults = new HashSet();
        ResourceResults resourceRst = null;
        // check if the request contains user response attributes
        Set respAttrs = resourceResultReq.getResponseAttributes();
        if (debug.messageEnabled()) {
            debug.message("PolicyRequestHandler.processPolicyRequest(): " + "respAttrs=\n" + respAttrs);
        }
        Map respDecisions = null;
        if ((respAttrs != null) && (userToken != null)) {
            // get the response decisions wrt the attributes  
            respDecisions = getResponseDecisions(userToken, respAttrs);
        }
        // Get the service name and resource name of the request
        String serviceName = resourceResultReq.getServiceName();
        String resourceName = resourceResultReq.getResourceName();
        // Get the resource scope of the request
        String resourceScope = resourceResultReq.getResourceScope();
        if ((resourceScope != null) && resourceScope.equals(ResourceResultRequest.RESPONSE_ATTRIBUTES_ONLY)) {
            // need not to evaluate policies, do attributes only
            ResourceResult resResult = new ResourceResult(resourceName, new PolicyDecision());
            Set results = new HashSet();
            results.add(resResult);
            resourceRst = new ResourceResults(results);
        } else {
            // Get the environment parameters of the request
            Map envParameters = resourceResultReq.getEnvParms();
            try {
                convertEnvParams(envParameters);
            } catch (PolicyException pe) {
                debug.error("PolicyRequestHandler: Invalid env parameters", pe);
                throw new PolicyEvaluationException(ResBundleUtils.rbName, "invalid_env_parameters", null, pe, requestId);
            }
            PolicyEvaluator policyEvaluator = null;
            try {
                // Get an instance of the policy evaluator
                policyEvaluator = getPolicyEvaluator(appToken, serviceName, appAttributes);
                // Get the resource result from the policy evaluator
                resourceRst = new ResourceResults(policyEvaluator.getResourceResults(userToken, resourceName, resourceScope, envParameters));
                if (debug.messageEnabled()) {
                    debug.message("PolicyRequestHandler.processPolicyRequest():" + " resource result:\n" + resourceRst.toXML());
                }
            } catch (Exception se) {
                debug.error("PolicyRequestHandler: Evaluation error", se);
                throw new PolicyEvaluationException(ResBundleUtils.rbName, "evaluation_error", null, se, requestId);
            }
        }
        resourceRst.setResponseDecisions(respDecisions);
        resourceResults.addAll(resourceRst.getResourceResults());
        policyRes.setResourceResults(resourceResults);
        policyRes.setMethodID(PolicyResponse.POLICY_RESPONSE_RESOURCE_RESULT);
        auditor.auditAccessSuccess();
        return policyRes;
    }
    debug.error("PolicyRequestHandler: Invalid policy request format");
    throw new PolicyEvaluationException(ResBundleUtils.rbName, "invalid_policy_request_format", null, null);
}
Also used : PolicyDecision(com.sun.identity.policy.PolicyDecision) SSOToken(com.iplanet.sso.SSOToken) ResponseSet(com.iplanet.services.comm.share.ResponseSet) HashSet(java.util.HashSet) Set(java.util.Set) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) IdRepoException(com.sun.identity.idm.IdRepoException) EntitlementException(com.sun.identity.entitlement.EntitlementException) PolicyException(com.sun.identity.policy.PolicyException) SMSException(com.sun.identity.sm.SMSException) SSOException(com.iplanet.sso.SSOException) ResourceResult(com.sun.identity.policy.ResourceResult) PolicyEvaluator(com.sun.identity.policy.PolicyEvaluator) PolicyException(com.sun.identity.policy.PolicyException) HashMap(java.util.HashMap) Map(java.util.Map) ResourceResults(com.sun.identity.policy.ResourceResults) HashSet(java.util.HashSet)

Aggregations

PolicyException (com.sun.identity.policy.PolicyException)151 SSOException (com.iplanet.sso.SSOException)64 HashSet (java.util.HashSet)63 Set (java.util.Set)57 Iterator (java.util.Iterator)50 PolicyManager (com.sun.identity.policy.PolicyManager)35 NameNotFoundException (com.sun.identity.policy.NameNotFoundException)32 HashMap (java.util.HashMap)28 Map (java.util.Map)27 AMConsoleException (com.sun.identity.console.base.model.AMConsoleException)26 ByteString (org.forgerock.opendj.ldap.ByteString)16 EntitlementException (com.sun.identity.entitlement.EntitlementException)14 LdapException (org.forgerock.opendj.ldap.LdapException)13 ResultCode (org.forgerock.opendj.ldap.ResultCode)13 Connection (org.forgerock.opendj.ldap.Connection)12 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)12 InvalidNameException (com.sun.identity.policy.InvalidNameException)11 ValidValues (com.sun.identity.policy.ValidValues)11 IOException (java.io.IOException)11 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)11