Search in sources :

Example 41 with SearchResultEntry

use of org.forgerock.opendj.ldap.responses.SearchResultEntry in project OpenAM by OpenRock.

the class SearchResults method next.

/**
     * Returns the next entry in the search results.
     * 
     * @throws UMSException
     *             No more entries in the search results.
     * @supported.api
     */
public PersistentObject next() throws UMSException {
    // TODO: define detailed exception list (eg. referral, ...)
    //
    SearchResultEntry ldapEntry;
    if (m_attrVals != null) {
        if (m_attrIndex < m_attrVals.length) {
            String dn = m_attrVals[m_attrIndex++];
            PersistentObject pO = new PersistentObject();
            pO.setGuid(new Guid(dn));
            pO.setPrincipal(m_principal);
            return pO;
        } else {
            throw new NoSuchElementException();
        }
    }
    if ((ldapEntry = currentEntry) != null) {
        String id = ldapEntry.getName().toString();
        Collection<Attribute> attributes = new ArrayList<>();
        for (Attribute attribute : ldapEntry.getAllAttributes()) {
            attributes.add(attribute);
        }
        AttrSet attrSet = new AttrSet(attributes);
        Class javaClass = TemplateManager.getTemplateManager().getJavaClassForEntry(id, attrSet);
        PersistentObject pO = null;
        try {
            pO = (PersistentObject) javaClass.newInstance();
        } catch (Exception e) {
            String[] args = new String[1];
            args[0] = e.toString();
            String msg = i18n.getString(IUMSConstants.NEW_INSTANCE_FAILED, args);
            throw new UMSException(msg);
        }
        // Make it a live object
        pO.setAttrSet(attrSet);
        pO.setGuid(new Guid(ldapEntry.getName().toString()));
        pO.setPrincipal(m_principal);
        return pO;
    }
    return null;
}
Also used : Attribute(org.forgerock.opendj.ldap.Attribute) ArrayList(java.util.ArrayList) NoSuchElementException(java.util.NoSuchElementException) LdapException(org.forgerock.opendj.ldap.LdapException) NoSuchElementException(java.util.NoSuchElementException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry) AttrSet(com.iplanet.services.ldap.AttrSet)

Example 42 with SearchResultEntry

use of org.forgerock.opendj.ldap.responses.SearchResultEntry in project OpenAM by OpenRock.

the class AMCRLStore method getCRLByLdapURI.

/**
     * It gets the new CRL from ldap server.
     * If it is ldap URI, the URI has to be a dn that can be accessed
     * with ldap anonymous bind.
     * (example : ldap://server:port/uid=ca,o=company.com)
     * This dn entry has to have CRL in attribute certificaterevocationlist
     * or certificaterevocationlist;binary.
     *
     * @param uri
     */
private byte[] getCRLByLdapURI(String uri) {
    if (debug.messageEnabled()) {
        debug.message("AMCRLStore.getCRLByLdapURI: uri = " + uri);
    }
    LDAPUrl url;
    LDAPConnectionFactory factory;
    byte[] crl = null;
    try {
        url = LDAPUrl.valueOf(uri);
    } catch (LocalizedIllegalArgumentException e) {
        debug.error("AMCRLStore.getCRLByLdapURI(): Could not parse uri: {}", uri, e);
        return null;
    }
    debug.message("AMCRLStore.getCRLByLdapURI: url.dn = {}", url.getName());
    // Check ldap over SSL
    if (url.isSecure()) {
        try {
            factory = new LDAPConnectionFactory(url.getHost(), url.getPort(), Options.defaultOptions().set(LDAPConnectionFactory.SSL_CONTEXT, new SSLContextBuilder().getSSLContext()));
        } catch (GeneralSecurityException e) {
            debug.error("AMCRLStore.getCRLByLdapURI: Error getting SSL Context", e);
            return null;
        }
    } else {
        // non-ssl
        factory = new LDAPConnectionFactory(url.getHost(), url.getPort());
    }
    try (Connection ldc = factory.getConnection()) {
        ConnectionEntryReader results = ldc.search(url.asSearchRequest().addControl(TransactionIdControl.newControl(AuditRequestContext.createSubTransactionIdValue())));
        if (!results.hasNext()) {
            debug.error("verifyCertificate - No CRL distribution Point configured");
            return null;
        }
        if (results.isReference()) {
            debug.warning("Getting CRL but got LDAP reference: {}", results.readReference());
            return null;
        }
        SearchResultEntry entry = results.readEntry();
        /* 
            * Retrieve the certificate revocation list if available.
            */
        Attribute crlAttribute = entry.getAttribute(CERTIFICATE_REVOCATION_LIST);
        if (crlAttribute == null) {
            crlAttribute = entry.getAttribute(CERTIFICATE_REVOCATION_LIST_BINARY);
            if (crlAttribute == null) {
                debug.error("verifyCertificate - No CRL distribution Point configured");
                return null;
            }
        }
        crl = crlAttribute.firstValue().toByteArray();
    } catch (Exception e) {
        debug.error("getCRLByLdapURI : Error in getting CRL", e);
    }
    return crl;
}
Also used : ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) LDAPUrl(org.forgerock.opendj.ldap.LDAPUrl) Attribute(org.forgerock.opendj.ldap.Attribute) GeneralSecurityException(java.security.GeneralSecurityException) HttpURLConnection(java.net.HttpURLConnection) Connection(org.forgerock.opendj.ldap.Connection) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) LocalizedIllegalArgumentException(org.forgerock.i18n.LocalizedIllegalArgumentException) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder) LdapException(org.forgerock.opendj.ldap.LdapException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) LocalizedIllegalArgumentException(org.forgerock.i18n.LocalizedIllegalArgumentException) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 43 with SearchResultEntry

use of org.forgerock.opendj.ldap.responses.SearchResultEntry in project OpenAM by OpenRock.

the class LDAPRoles method getValidValues.

/**
     * Returns a list of possible values for the <code>LDAPRoles
     * </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, "ldaproles_subject_not_yet_initialized", null, null));
    }
    String searchFilter = null;
    if ((pattern != null) && !(pattern.trim().length() == 0)) {
        searchFilter = "(&" + roleSearchFilter + "(" + roleRDNAttrName + "=" + pattern + "))";
    } else {
        searchFilter = roleSearchFilter;
    }
    if (debug.messageEnabled()) {
        debug.message("LDAPRoles.getValidValues(): role search filter is: " + searchFilter);
    }
    String[] attrs = { roleRDNAttrName };
    Set<String> validRoleDNs = new HashSet<>();
    int status = ValidValues.SUCCESS;
    try (Connection conn = connPool.getConnection()) {
        SearchRequest searchRequest = LDAPRequests.newSearchRequest(baseDN, roleSearchScope, searchFilter, attrs);
        ConnectionEntryReader reader = conn.search(searchRequest);
        while (reader.hasNext()) {
            if (reader.isReference()) {
                //Ignore
                reader.readReference();
            } else {
                SearchResultEntry entry = reader.readEntry();
                if (entry != null) {
                    validRoleDNs.add(entry.getName().toString());
                    debug.message("LDAPRoles.getValidValues(): found role name={}", entry.getName().toString());
                }
            }
        }
    } catch (LdapException le) {
        ResultCode resultCode = le.getResult().getResultCode();
        if (ResultCode.SIZE_LIMIT_EXCEEDED.equals(resultCode)) {
            debug.warning("LDAPRoles.getValidValues(): exceeded the size limit");
            return new ValidValues(ValidValues.SIZE_LIMIT_EXCEEDED, validRoleDNs);
        } else if (ResultCode.TIME_LIMIT_EXCEEDED.equals(resultCode)) {
            debug.warning("LDAPRoles.getValidValues(): exceeded the time limit");
            return new ValidValues(ValidValues.TIME_LIMIT_EXCEEDED, validRoleDNs);
        } 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);
    }
    return new ValidValues(status, validRoleDNs);
}
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) 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 44 with SearchResultEntry

use of org.forgerock.opendj.ldap.responses.SearchResultEntry in project OpenAM by OpenRock.

the class LDAPGroups method findDynamicGroupMembersByUrl.

/**
     * Finds the dynamic group member DNs 
     * @param url the url to be used for the group member search
     * @return the set of group member DNs satisfied the search url
     */
private Set findDynamicGroupMembersByUrl(LDAPUrl url, String userRDN) throws PolicyException {
    Connection ld = null;
    Set<String> groupMemberDNs = new HashSet<>();
    try (Connection conn = connPool.getConnection()) {
        // Need to pass the user dn in the filter
        StringBuilder filter = new StringBuilder(25);
        filter.append("(&").append(userRDN);
        String groupFilter = url.getFilter().toString();
        int index = groupFilter.indexOf("(");
        if (index != 0) {
            filter.append("(").append(groupFilter).append("))");
        } else {
            filter.append(groupFilter).append(")");
        }
        debug.message("search filter in LDAPGroups : {}", filter);
        String[] attrs = { userRDNAttrName };
        SearchRequest searchRequest = LDAPRequests.newSearchRequest(url.getName(), url.getScope(), Filter.valueOf(filter.toString()), attrs);
        ConnectionEntryReader reader = conn.search(searchRequest);
        while (reader.hasNext()) {
            if (reader.isReference()) {
                //Ignore
                reader.readReference();
            } else {
                SearchResultEntry entry = reader.readEntry();
                if (entry != null) {
                    groupMemberDNs.add(entry.getName().toString());
                }
            }
        }
    } catch (LdapException le) {
        String[] objs = { orgName };
        ResultCode resultCode = le.getResult().getResultCode();
        if (ResultCode.SIZE_LIMIT_EXCEEDED.equals(resultCode)) {
            debug.warning("LDAPGroups.findDynamicGroupMembersByUrl(): exceeded the size limit");
            throw new PolicyException(ResBundleUtils.rbName, "ldap_search_exceed_size_limit", objs, null);
        } else if (ResultCode.TIME_LIMIT_EXCEEDED.equals(resultCode)) {
            debug.warning("LDAPGroups.findDynamicGroupMembersByUrl(): exceeded the time limit");
            throw new PolicyException(ResBundleUtils.rbName, "ldap_search_exceed_time_limit", objs, null);
        } else {
            throw new PolicyException(le);
        }
    } catch (Exception e) {
        throw new PolicyException(e);
    }
    return groupMemberDNs;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) 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 45 with SearchResultEntry

use of org.forgerock.opendj.ldap.responses.SearchResultEntry in project OpenAM by OpenRock.

the class LDAPGroups method isMemberOfGroup.

/**
     * Find out if a user belongs to a particular group
     * @param groupName the ldap DN of the group
     * @param userDN the ldap DN of the user
     * @return <code>true</code> if the user is member of the group;
     * <code>false</code> otherwise.
     */
private boolean isMemberOfGroup(String groupName, DN userDN, String userRDN, SSOToken token) throws SSOException, PolicyException {
    if (debug.messageEnabled()) {
        debug.message("LDAPGroups.isMemberOfGroup():" + " entering with groupName = " + groupName + ",userDN = " + userDN);
    }
    if ((groupName == null) || (groupName.length() == 0) || (userDN == null)) {
        return false;
    }
    String tokenID = token.getTokenID().toString();
    boolean groupMatch = false;
    SearchResultEntry entry;
    try (Connection conn = connPool.getConnection()) {
        entry = conn.searchSingleEntry(LDAPRequests.newSingleEntrySearchRequest(groupName));
    } catch (Exception e) {
        debug.warning("LDAPGroups: invalid group name {} specified in the policy definition.", groupName);
        return false;
    }
    debug.message("LDAPGroups.isMemberOfGroup(): get {} group attribute", STATIC_GROUP_MEMBER_ATTR);
    Attribute attribute = entry.getAttribute(STATIC_GROUP_MEMBER_ATTR);
    if (attribute != null) {
        for (ByteString memberDNStr : attribute) {
            debug.message("LDAPGroups.isMemberOfGroup(): memberDNStr = ", memberDNStr);
            DN memberDN = DN.valueOf(memberDNStr.toString());
            if (userDN.equals(memberDN)) {
                groupMatch = true;
                break;
            }
        }
    }
    if (!groupMatch) {
        debug.message("LDAPGroups.isMemberOfGroup(): get {} group attribute", STATIC_GROUP_MEMBER_ALT_ATTR);
        attribute = entry.getAttribute(STATIC_GROUP_MEMBER_ALT_ATTR);
        if (attribute != null) {
            for (ByteString memberDNStr : attribute) {
                debug.message("LDAPGroups.isMemberOfGroup(): memberDNStr = ", memberDNStr);
                DN memberDN = DN.valueOf(memberDNStr.toString());
                if (userDN.equals(memberDN)) {
                    groupMatch = true;
                    break;
                }
            }
        }
    }
    if (!groupMatch) {
        attribute = entry.getAttribute(DYNAMIC_GROUP_MEMBER_URL);
        if (attribute != null) {
            for (ByteString memberUrl : attribute) {
                try {
                    LDAPUrl ldapUrl = LDAPUrl.valueOf(memberUrl.toString());
                    Set members = findDynamicGroupMembersByUrl(ldapUrl, userRDN);
                    Iterator iter = members.iterator();
                    while (iter.hasNext()) {
                        String memberDNStr = (String) iter.next();
                        DN memberDN = DN.valueOf(memberDNStr);
                        if (userDN.equals(memberDN)) {
                            groupMatch = true;
                            break;
                        }
                    }
                } catch (LocalizedIllegalArgumentException e) {
                    throw new PolicyException(e);
                }
            }
        }
    }
    debug.message("LDAPGroups.isMemberOfGroup():adding entry {} {} {} {} in subject evaluation cache.", tokenID, ldapServer, groupName, groupMatch);
    SubjectEvaluationCache.addEntry(tokenID, ldapServer, groupName, groupMatch);
    return groupMatch;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) Attribute(org.forgerock.opendj.ldap.Attribute) ByteString(org.forgerock.opendj.ldap.ByteString) Connection(org.forgerock.opendj.ldap.Connection) DN(org.forgerock.opendj.ldap.DN) ByteString(org.forgerock.opendj.ldap.ByteString) LocalizedIllegalArgumentException(org.forgerock.i18n.LocalizedIllegalArgumentException) 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) LDAPUrl(org.forgerock.opendj.ldap.LDAPUrl) PolicyException(com.sun.identity.policy.PolicyException) Iterator(java.util.Iterator) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Aggregations

SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)62 LdapException (org.forgerock.opendj.ldap.LdapException)46 ByteString (org.forgerock.opendj.ldap.ByteString)43 Connection (org.forgerock.opendj.ldap.Connection)43 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)43 Attribute (org.forgerock.opendj.ldap.Attribute)30 HashSet (java.util.HashSet)25 SearchResultReferenceIOException (org.forgerock.opendj.ldap.SearchResultReferenceIOException)24 SearchRequest (org.forgerock.opendj.ldap.requests.SearchRequest)19 IOException (java.io.IOException)18 PolicyException (com.sun.identity.policy.PolicyException)15 ResultCode (org.forgerock.opendj.ldap.ResultCode)15 SSOException (com.iplanet.sso.SSOException)14 DN (org.forgerock.opendj.ldap.DN)11 InvalidNameException (com.sun.identity.policy.InvalidNameException)10 NameNotFoundException (com.sun.identity.policy.NameNotFoundException)10 LinkedAttribute (org.forgerock.opendj.ldap.LinkedAttribute)10 ArrayList (java.util.ArrayList)9 BindResult (org.forgerock.opendj.ldap.responses.BindResult)8 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)7