Search in sources :

Example 31 with PolicyException

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

the class LDAPGroups method getValidValues.

/**
     * Returns a list of possible values for the <code>LDAPGroups
     * </code> that satisfy the given <code>pattern</code>.
     *
     * @param token the <code>SSOToken</code> that will be used
     * to determine the possible values
     * @param pattern search pattern that will be used to narrow
     * the list of valid names.
     *
     * @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 {
    if (!initialized) {
        throw new PolicyException(ResBundleUtils.rbName, "ldapgroups_subject_not_yet_initialized", null, null);
    }
    Set<String> validGroupDNs = new HashSet<>();
    String searchFilter;
    if (pattern != null && !pattern.trim().isEmpty()) {
        searchFilter = "(&" + groupSearchFilter + "(" + groupRDNAttrName + "=" + pattern + "))";
    } else {
        searchFilter = groupSearchFilter;
    }
    debug.message("LDAPGroups.getValidValues(): group search filter is: {}", searchFilter);
    String[] attrs = { groupRDNAttrName };
    Connection ld = null;
    int status = ValidValues.SUCCESS;
    try (Connection conn = connPool.getConnection()) {
        SearchRequest searchRequest = LDAPRequests.newSearchRequest(baseDN, groupSearchScope, searchFilter, attrs);
        ConnectionEntryReader reader = conn.search(searchRequest);
        while (reader.hasNext()) {
            if (reader.isReference()) {
                //Ignore
                reader.readReference();
            } else {
                SearchResultEntry entry = reader.readEntry();
                if (entry != null) {
                    validGroupDNs.add(entry.getName().toString());
                    debug.message("LDAPGroups.getValidValues(): found group name={}", entry.getName().toString());
                }
            }
        }
    } catch (LdapException lde) {
        ResultCode resultCode = lde.getResult().getResultCode();
        if (ResultCode.SIZE_LIMIT_EXCEEDED.equals(resultCode)) {
            debug.warning("LDAPGroups.getValidValues(): exceeded the size limit");
            return new ValidValues(ValidValues.SIZE_LIMIT_EXCEEDED, validGroupDNs);
        } else if (ResultCode.TIME_LIMIT_EXCEEDED.equals(resultCode)) {
            debug.warning("LDAPGroups.getValidValues(): exceeded the time limit");
            return new ValidValues(ValidValues.TIME_LIMIT_EXCEEDED, validGroupDNs);
        } else if (ResultCode.INVALID_CREDENTIALS.equals(resultCode)) {
            throw new PolicyException(ResBundleUtils.rbName, "ldap_invalid_password", null, null);
        } else if (ResultCode.NO_SUCH_OBJECT.equals(resultCode)) {
            String[] objs = { baseDN };
            throw new PolicyException(ResBundleUtils.rbName, "no_such_ldap_base_dn", objs, null);
        }
        String errorMsg = lde.getMessage();
        String additionalMsg = lde.getResult().getDiagnosticMessage();
        if (additionalMsg != null) {
            throw new PolicyException(errorMsg + ": " + additionalMsg);
        } else {
            throw new PolicyException(errorMsg);
        }
    } catch (Exception e) {
        throw new PolicyException(e);
    }
    return new ValidValues(status, validGroupDNs);
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) ValidValues(com.sun.identity.policy.ValidValues) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) NameNotFoundException(com.sun.identity.policy.NameNotFoundException) PolicyException(com.sun.identity.policy.PolicyException) InvalidNameException(com.sun.identity.policy.InvalidNameException) SSOException(com.iplanet.sso.SSOException) LocalizedIllegalArgumentException(org.forgerock.i18n.LocalizedIllegalArgumentException) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) PolicyException(com.sun.identity.policy.PolicyException) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) HashSet(java.util.HashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 32 with PolicyException

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

the class LDAPGroups method getUserDN.

/**
     * Get the full DN for the user using the RDN against the
     * LDAP server configured in the policy config service.
     */
private DN getUserDN(String userRDN) throws SSOException, PolicyException {
    DN userDN = null;
    if (userRDN != null) {
        Set<String> qualifiedUserDNs = new HashSet<>();
        String searchFilter = null;
        if ((userSearchFilter != null) && !(userSearchFilter.length() == 0)) {
            searchFilter = "(&" + userSearchFilter + userRDN + ")";
        } else {
            searchFilter = userRDN;
        }
        if (debug.messageEnabled()) {
            debug.message("LDAPGroups.getUserDN(): search filter is: " + searchFilter);
        }
        String[] attrs = { userRDNAttrName };
        try (Connection conn = connPool.getConnection()) {
            SearchRequest searchRequest = LDAPRequests.newSearchRequest(baseDN, userSearchScope, searchFilter, attrs);
            ConnectionEntryReader reader = conn.search(searchRequest);
            while (reader.hasNext()) {
                if (reader.isReference()) {
                    //Ignore
                    reader.readReference();
                } else {
                    SearchResultEntry entry = reader.readEntry();
                    if (entry != null) {
                        qualifiedUserDNs.add(entry.getName().toString());
                    }
                }
            }
        } catch (LdapException le) {
            ResultCode resultCode = le.getResult().getResultCode();
            if (ResultCode.SIZE_LIMIT_EXCEEDED.equals(resultCode)) {
                String[] objs = { orgName };
                debug.warning("LDAPGroups.isMember(): exceeded the size limit");
                throw new PolicyException(ResBundleUtils.rbName, "ldap_search_exceed_size_limit", objs, null);
            } else if (ResultCode.TIME_LIMIT_EXCEEDED.equals(resultCode)) {
                String[] objs = { orgName };
                debug.warning("LDAPGroups.isMember(): exceeded the time limit");
                throw new PolicyException(ResBundleUtils.rbName, "ldap_search_exceed_time_limit", objs, null);
            } else if (ResultCode.INVALID_CREDENTIALS.equals(resultCode)) {
                throw new PolicyException(ResBundleUtils.rbName, "ldap_invalid_password", null, null);
            } else if (ResultCode.NO_SUCH_OBJECT.equals(resultCode)) {
                String[] objs = { baseDN };
                throw new PolicyException(ResBundleUtils.rbName, "no_such_ldap_base_dn", objs, null);
            }
            String errorMsg = le.getMessage();
            String additionalMsg = le.getResult().getDiagnosticMessage();
            if (additionalMsg != null) {
                throw new PolicyException(errorMsg + ": " + additionalMsg);
            } else {
                throw new PolicyException(errorMsg);
            }
        } catch (Exception e) {
            throw new PolicyException(e);
        }
        // check if the user belongs to any of the selected groups
        if (qualifiedUserDNs.size() > 0) {
            debug.message("LDAPGroups.getUserDN(): qualified users={}", qualifiedUserDNs);
            Iterator<String> iter = qualifiedUserDNs.iterator();
            // we only take the first qualified DN if the DN
            userDN = DN.valueOf(iter.next());
        }
    }
    return userDN;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) Connection(org.forgerock.opendj.ldap.Connection) DN(org.forgerock.opendj.ldap.DN) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) NameNotFoundException(com.sun.identity.policy.NameNotFoundException) PolicyException(com.sun.identity.policy.PolicyException) InvalidNameException(com.sun.identity.policy.InvalidNameException) SSOException(com.iplanet.sso.SSOException) LocalizedIllegalArgumentException(org.forgerock.i18n.LocalizedIllegalArgumentException) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) PolicyException(com.sun.identity.policy.PolicyException) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) HashSet(java.util.HashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 33 with PolicyException

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

the class PeerOrgReferral 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;
    if (debug.messageEnabled()) {
        debug.message("PeerOrgReferral.getValidValues():entering");
    }
    try {
        Set orgSet = (Set) _configurationMap.get(PolicyManager.ORGANIZATION_NAME);
        if ((orgSet == null) || (orgSet.isEmpty())) {
            debug.error("PeerOrgReferral.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);
        String fullOrgName = orgConfigManager.getOrganizationName();
        if (debug.messageEnabled()) {
            debug.message("PeerOrgReferral.getValidValues():fullOrgName=" + fullOrgName);
        }
        OrganizationConfigManager parentOrgConfig = orgConfigManager.getParentOrgConfigManager();
        String fullParentOrgName = parentOrgConfig.getOrganizationName();
        Set subOrgNames = parentOrgConfig.getSubOrganizationNames(pattern, //get only first level children
        false);
        if (!fullOrgName.equals(fullParentOrgName) && (subOrgNames != null) && !subOrgNames.isEmpty()) {
            Iterator subOrgsIter = subOrgNames.iterator();
            while (subOrgsIter.hasNext()) {
                String subOrgName = (String) subOrgsIter.next();
                OrganizationConfigManager subOrgManager = parentOrgConfig.getSubOrgConfigManager(subOrgName);
                if (subOrgManager != null) {
                    String fullSubOrgName = subOrgManager.getOrganizationName();
                    if (!fullOrgName.equals(fullSubOrgName)) {
                        values.add(fullSubOrgName);
                    }
                }
            }
        }
        if (debug.messageEnabled()) {
            debug.message("PeerOrgReferral.getValidValues():returning=" + values);
        }
    } catch (SMSException smse) {
        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 34 with PolicyException

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

the class ResourceEnvIPCondition method getAdviceMessagesforRealm.

/** 
     * Returns advice messages for Authentication Realm condition.
     */
private Set getAdviceMessagesforRealm(String adviceValue, SSOToken token, Map env) throws PolicyException, SSOException {
    Set adviceMessages = new HashSet();
    Set requestAuthnRealms = new HashSet();
    if ((env != null) && (env.get(REQUEST_AUTHENTICATED_TO_REALMS) != null)) {
        try {
            requestAuthnRealms = (Set) env.get(REQUEST_AUTHENTICATED_TO_REALMS);
            if (DEBUG.messageEnabled()) {
                DEBUG.message("At ResourceEnvIPCondition." + "getAdviceMessagesforRealm(): " + "requestAuthnRealms, from request / env = " + requestAuthnRealms);
            }
        } catch (ClassCastException e) {
            String[] args = { REQUEST_AUTHENTICATED_TO_REALMS };
            throw new PolicyException(ResBundleUtils.rbName, "property_is_not_a_Set", args, e);
        }
    } else {
        if (token != null) {
            Set authenticatedRealms = AMAuthUtils.getAuthenticatedRealms(token);
            if (authenticatedRealms != null) {
                requestAuthnRealms.addAll(authenticatedRealms);
            }
            if (DEBUG.messageEnabled()) {
                DEBUG.message("At ResourceEnvIPCondition." + "getAdviceMessagesforRealm(): " + "requestAuthnRealms, from ssoToken = " + requestAuthnRealms);
            }
        }
    }
    String authRealm = adviceValue;
    if (!requestAuthnRealms.contains(authRealm)) {
        adviceMessages.add(authRealm);
        if (DEBUG.messageEnabled()) {
            DEBUG.message("At ResourceEnvIPCondition." + "getAdviceMessagesforRealm():" + "authenticateToRealm not satisfied = " + authRealm);
        }
    }
    if (DEBUG.messageEnabled()) {
        DEBUG.message("At ResourceEnvIPCondition." + "getAdviceMessagesforRealm():" + "authRealm = " + authRealm + "," + " requestAuthnRealms = " + requestAuthnRealms + ", " + " adviceMessages = " + adviceMessages);
    }
    return adviceMessages;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) PolicyException(com.sun.identity.policy.PolicyException) HashSet(java.util.HashSet)

Example 35 with PolicyException

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

the class ResourceEnvIPCondition method getAdviceStrForEnv.

/**
     * Returns the advice string that satisfies or matches for the client
     * environment parameter, including client's IP Address.
     */
private String getAdviceStrForEnv(Map env, SSOToken token) throws PolicyException, SSOException {
    String adviceStr = null;
    //Check if all the keys are valid
    for (int i = 0; i < envList.size(); i++) {
        String key = (String) envList.get(i);
        if (key != null) {
            if (key.contains("=")) {
                StringTokenizer st = new StringTokenizer(key, "=");
                int tokenCount = st.countTokens();
                if (tokenCount != 2) {
                    String[] args = { key };
                    throw new PolicyException(ResBundleUtils.rbName, "invalid_property_value", args, null);
                }
                String envParamName = st.nextToken().trim();
                String envParamValue = envParamName;
                if (tokenCount == 2) {
                    envParamValue = st.nextToken().trim();
                }
                Set envSet = (Set) env.get(envParamName);
                String strEnv = null;
                if ((envSet != null) && (!envSet.isEmpty())) {
                    Iterator names = envSet.iterator();
                    while (names.hasNext()) {
                        strEnv = (String) names.next();
                        if ((strEnv != null) && (strEnv.equalsIgnoreCase(envParamValue))) {
                            adviceStr = (String) adviceList.get(i);
                            break;
                        }
                    }
                } else {
                    String strIP = null;
                    Object object = env.get(REQUEST_IP);
                    if (object instanceof Set) {
                        Set ipSet = (Set) object;
                        if (ipSet.isEmpty()) {
                            if (token != null) {
                                strIP = token.getIPAddress().getHostAddress();
                            } else {
                                throw new PolicyException(ResBundleUtils.rbName, "client_ip_null", null, null);
                            }
                        } else {
                            Iterator names = ipSet.iterator();
                            strIP = (String) names.next();
                        }
                    } else if (object instanceof String) {
                        strIP = (String) object;
                        if (StringUtils.isBlank(strIP)) {
                            if (token != null) {
                                strIP = token.getIPAddress().getHostAddress();
                            } else {
                                throw new PolicyException(ResBundleUtils.rbName, "client_ip_null", null, null);
                            }
                        }
                    }
                    long requestIpV4 = 0;
                    IPv6Address requestIpV6 = null;
                    if (ValidateIPaddress.isIPv4(strIP)) {
                        requestIpV4 = stringToIp(strIP);
                    } else if (ValidateIPaddress.isIPv6(strIP)) {
                        requestIpV6 = IPv6Address.fromString(strIP);
                    } else {
                        if (DEBUG.messageEnabled()) {
                            DEBUG.message("ResourceEnvIPCondition:getAdviceStrForEnv invalid strIP : " + strIP);
                        }
                        continue;
                    }
                    int bIndex = envParamValue.indexOf("[");
                    int lIndex = envParamValue.indexOf("]");
                    String ipVal = envParamValue.substring(bIndex + 1, lIndex);
                    if (ipVal.contains("-")) {
                        StringTokenizer stIP = new StringTokenizer(ipVal, "-");
                        int tokenCnt = stIP.countTokens();
                        if (tokenCnt > 2) {
                            String[] args = { ipVal };
                            throw new PolicyException(ResBundleUtils.rbName, "invalid_property_value", args, null);
                        }
                        String startIp = stIP.nextToken();
                        String endIp = startIp;
                        if (tokenCnt == 2) {
                            endIp = stIP.nextToken();
                        }
                        if (ValidateIPaddress.isIPv4(strIP) && ValidateIPaddress.isIPv4(startIp) && ValidateIPaddress.isIPv4(endIp)) {
                            long lStartIP = stringToIp(startIp);
                            long lEndIP = stringToIp(endIp);
                            if ((requestIpV4 >= lStartIP) && (requestIpV4 <= lEndIP)) {
                                adviceStr = (String) adviceList.get(i);
                                break;
                            }
                        } else if (ValidateIPaddress.isIPv6(strIP) && ValidateIPaddress.isIPv6(startIp) && ValidateIPaddress.isIPv6(endIp)) {
                            IPv6AddressRange ipv6Range = IPv6AddressRange.fromFirstAndLast(IPv6Address.fromString(startIp), IPv6Address.fromString(endIp));
                            if (requestIpV6 != null && ipv6Range.contains(requestIpV6)) {
                                adviceStr = (String) adviceList.get(i);
                                break;
                            }
                        } else {
                            String[] args = { strIP };
                            throw new PolicyException(ResBundleUtils.rbName, "invalid_property_value", args, null);
                        }
                    } else if (requestIpV4 != 0 && ValidateIPaddress.isIPv4(ipVal)) {
                        long longIp = stringToIp(ipVal);
                        if (requestIpV4 == longIp) {
                            adviceStr = (String) adviceList.get(i);
                            break;
                        }
                    } else if (requestIpV6 != null && ValidateIPaddress.isIPv6(ipVal)) {
                        // treat as single ip address
                        IPv6Address iPv6AddressIpVal = IPv6Address.fromString(ipVal);
                        if (iPv6AddressIpVal.compareTo(requestIpV6) == 0) {
                            adviceStr = (String) adviceList.get(i);
                            break;
                        }
                    } else if (ipVal.contains("*")) {
                        adviceStr = (String) adviceList.get(i);
                        break;
                    } else {
                        String[] args = { ipVal };
                        throw new PolicyException(ResBundleUtils.rbName, "resource_env_not_known", args, null);
                    }
                }
            } else {
                String[] args = { key };
                throw new PolicyException(ResBundleUtils.rbName, "resource_env_not_known", args, null);
            }
        }
    }
    return adviceStr;
}
Also used : StringTokenizer(java.util.StringTokenizer) HashSet(java.util.HashSet) Set(java.util.Set) IPv6AddressRange(com.googlecode.ipv6.IPv6AddressRange) PolicyException(com.sun.identity.policy.PolicyException) Iterator(java.util.Iterator) IPv6Address(com.googlecode.ipv6.IPv6Address)

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