Search in sources :

Example 1 with ByteString

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

the class UmaLabelsStore method read.

/**
     * Reads a label from the underlying database.
     * @param realm The current realm.
     * @param username The user that owns the label.
     * @param id The id of the label.
     * @return The retrieved label details.
     * @throws ResourceException Thrown if the label cannot be read.
     */
public ResourceSetLabel read(String realm, String username, String id) throws ResourceException {
    try (Connection connection = getConnection()) {
        SearchResultEntry entry = connection.searchSingleEntry(LDAPRequests.newSingleEntrySearchRequest(getLabelDn(realm, username, id)));
        Set<String> resourceSets = new HashSet<>();
        final Attribute resourceSetAttribute = entry.getAttribute(RESOURCE_SET_ATTR);
        if (resourceSetAttribute != null) {
            for (ByteString resourceSetId : resourceSetAttribute) {
                resourceSets.add(resourceSetId.toString());
            }
        }
        return getResourceSetLabel(entry, resourceSets);
    } catch (LdapException e) {
        final ResultCode resultCode = e.getResult().getResultCode();
        if (resultCode.equals(ResultCode.NO_SUCH_OBJECT)) {
            throw new NotFoundException();
        }
        throw new InternalServerErrorException("Could not read", e);
    }
}
Also used : Attribute(org.forgerock.opendj.ldap.Attribute) ByteString(org.forgerock.opendj.ldap.ByteString) Connection(org.forgerock.opendj.ldap.Connection) NotFoundException(org.forgerock.json.resource.NotFoundException) InternalServerErrorException(org.forgerock.json.resource.InternalServerErrorException) ByteString(org.forgerock.opendj.ldap.ByteString) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry) HashSet(java.util.HashSet)

Example 2 with ByteString

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

the class DirectoryServerVendor method query.

/**
     * Returns the vendor of Directory Server.
     * @param conn LDAP connection to the server.
     * @return the vendor of Directory Server.
     * @throws LdapException if unable to get the vendor information.
     * @throws SearchResultReferenceIOException if unable to get the vendor information
     */
public Vendor query(Connection conn) throws LdapException, SearchResultReferenceIOException {
    String result = null;
    ConnectionEntryReader res = conn.search(LDAPRequests.newSearchRequest("", SearchScope.BASE_OBJECT, "(objectclass=*)", attrs));
    while (res.hasNext()) {
        if (res.isReference()) {
            //ignore
            res.readReference();
        } else {
            SearchResultEntry findEntry = res.readEntry();
            /* Get the attributes of the root DSE. */
            for (Attribute attribute : findEntry.getAllAttributes()) {
                String attrName = attribute.getAttributeDescriptionAsString();
                if ("vendorversion".equalsIgnoreCase(attrName)) {
                    for (ByteString value : attribute) {
                        result = value.toString();
                        break;
                    }
                }
            }
        }
    }
    Vendor vendor = unknownVendor;
    if (result != null) {
        if (result.startsWith(VENDOR_OPENDJ)) {
            String version = result.substring(VENDOR_OPENDJ.length());
            vendor = new Vendor(OPENDJ, version);
        } else if (result.startsWith(VENDOR_OPENDS)) {
            String version = result.substring(VENDOR_OPENDS.length());
            vendor = new Vendor(OPENDS, version);
        } else if (result.startsWith(VENDOR_SUNDS_5)) {
            String version = result.substring(VENDOR_SUNDS_5.length());
            vendor = new Vendor(ODSEE, version);
        } else if (result.startsWith(VENDOR_SUNDS_6)) {
            String version = result.substring(VENDOR_SUNDS_6.length());
            vendor = new Vendor(ODSEE, version);
        } else if (result.startsWith(VENDOR_SUNDS_7)) {
            String version = result.substring(VENDOR_SUNDS_7.length());
            vendor = new Vendor(ODSEE, version);
        } else if (result.startsWith(VENDOR_ODSEE_11)) {
            String version = result.substring(VENDOR_ODSEE_11.length());
            vendor = new Vendor(ODSEE, version);
        }
    }
    return vendor;
}
Also used : ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Attribute(org.forgerock.opendj.ldap.Attribute) ByteString(org.forgerock.opendj.ldap.ByteString) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 3 with ByteString

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

the class LDAPAuthUtils method updateADPassword.

private ByteString updateADPassword(String password) {
    String quotedPassword = "\"" + password + "\"";
    byte[] newUnicodePassword = quotedPassword.getBytes(Charset.forName("UTF-16LE"));
    return ByteString.wrap(newUnicodePassword);
}
Also used : ByteString(org.forgerock.opendj.ldap.ByteString)

Example 4 with ByteString

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

the class LDAPAuthUtils method searchForUser.

/**
     * Searches and returns user for a specified attribute using parameters
     * specified in constructor and/or by setting properties.
     *
     * @throws LDAPUtilException
     */
public void searchForUser() throws LDAPUtilException {
    // assume that there is only one user attribute
    if (searchScope == SearchScope.BASE_OBJECT) {
        if (userSearchAttrs.size() == 1) {
            StringBuilder dnBuffer = new StringBuilder();
            dnBuffer.append((String) userSearchAttrs.iterator().next());
            dnBuffer.append("=");
            dnBuffer.append(userId);
            dnBuffer.append(",");
            dnBuffer.append(baseDN);
            userDN = dnBuffer.toString();
            if (debug.messageEnabled()) {
                debug.message("searchForUser, searchScope = BASE," + "userDN =" + userDN);
            }
            if (!isDynamicUserEnabled && userSearchAttrs.contains(userNamingAttr)) {
                return;
            } else if (isDynamicUserEnabled && (userAttributes == null || userAttributes.isEmpty())) {
                debug.message("user creation attribute list is empty ");
                return;
            }
            baseDN = userDN;
        } else {
            if (debug.messageEnabled()) {
                debug.message("cannot find user entry using scope=0" + "setting scope=1");
            }
            searchScope = SearchScope.SINGLE_LEVEL;
        }
    }
    if (searchFilter == null || searchFilter.length() == 0) {
        searchFilter = buildUserFilter();
    } else {
        StringBuilder bindFilter = new StringBuilder(200);
        if (userId != null) {
            bindFilter.append("(&");
            bindFilter.append(buildUserFilter());
            bindFilter.append(searchFilter);
            bindFilter.append(")");
        } else {
            bindFilter.append(searchFilter);
        }
        searchFilter = bindFilter.toString();
    }
    userDN = null;
    Connection conn = null;
    try {
        if (debug.messageEnabled()) {
            debug.message("Connecting to " + servers + "\nSearching " + baseDN + " for " + searchFilter + "\nscope = " + searchScope);
        }
        // Search
        int userAttrSize = 0;
        if (attrs == null) {
            if ((userAttributes == null) || (userAttributes.isEmpty())) {
                userAttrSize = 2;
                attrs = new String[userAttrSize];
                attrs[0] = "dn";
                attrs[1] = userNamingAttr;
            } else {
                userAttrSize = userAttributes.size();
                attrs = new String[userAttrSize + 2];
                attrs[0] = "dn";
                attrs[1] = userNamingAttr;
                Iterator attrItr = userAttributes.iterator();
                for (int i = 2; i < userAttrSize + 2; i++) {
                    attrs[i] = (String) attrItr.next();
                }
            }
        }
        if (debug.messageEnabled()) {
            debug.message("userAttrSize is : " + userAttrSize);
        }
        ConnectionEntryReader results;
        SearchRequest searchForUser = LDAPRequests.newSearchRequest(baseDN, searchScope, searchFilter, attrs);
        int userMatches = 0;
        SearchResultEntry entry;
        boolean userNamingValueSet = false;
        try {
            conn = getAdminConnection();
            results = conn.search(searchForUser);
            while (results.hasNext()) {
                if (results.isEntry()) {
                    entry = results.readEntry();
                    userDN = entry.getName().toString();
                    userMatches++;
                    if (attrs != null && attrs.length > 1) {
                        userNamingValueSet = true;
                        Attribute attr = entry.getAttribute(userNamingAttr);
                        if (attr != null) {
                            userNamingValue = attr.firstValueAsString();
                        }
                        if (isDynamicUserEnabled && (attrs.length > 2)) {
                            for (int i = 2; i < userAttrSize + 2; i++) {
                                attr = entry.getAttribute(attrs[i]);
                                if (attr != null) {
                                    Set<String> s = new HashSet<String>();
                                    Iterator<ByteString> values = attr.iterator();
                                    while (values.hasNext()) {
                                        s.add(values.next().toString());
                                    }
                                    userAttributeValues.put(attrs[i], s);
                                }
                            }
                        }
                    }
                } else {
                    //read and ignore references
                    results.readReference();
                }
            }
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
        if (userNamingValueSet && (userDN == null || userNamingValue == null)) {
            if (debug.messageEnabled()) {
                debug.message("Cannot find entries for " + searchFilter);
            }
            setState(ModuleState.USER_NOT_FOUND);
            return;
        } else {
            if (userDN == null) {
                if (debug.messageEnabled()) {
                    debug.message("Cannot find entries for " + searchFilter);
                }
                setState(ModuleState.USER_NOT_FOUND);
                return;
            } else {
                setState(ModuleState.USER_FOUND);
            }
        }
        if (userMatches > 1) {
            // multiple user matches found
            debug.error("searchForUser : Multiple matches found for user '" + userId + "'. Please modify search start DN/filter/scope " + "to make sure unique match returned. Contact your " + "administrator to fix the problem");
            throw new LDAPUtilException("multipleUserMatchFound", (Object[]) null);
        }
    } catch (LdapException ere) {
        if (debug.warningEnabled()) {
            debug.warning("Search for User error: ", ere);
            debug.warning("resultCode: " + ere.getResult().getResultCode());
        }
        if (ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_CONNECT_ERROR) || ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_SERVER_DOWN) || ere.getResult().getResultCode().equals(ResultCode.UNAVAILABLE) || ere.getResult().getResultCode().equals(ResultCode.CLIENT_SIDE_TIMEOUT)) {
            if (debug.warningEnabled()) {
                debug.warning("Cannot connect to " + servers, ere);
            }
            setState(ModuleState.SERVER_DOWN);
        } else if (ere.getResult().getResultCode().equals(ResultCode.INVALID_CREDENTIALS)) {
            if (debug.warningEnabled()) {
                debug.warning("Cannot authenticate ");
            }
            throw new LDAPUtilException("FConnect", ResultCode.INVALID_CREDENTIALS, null);
        } else if (ere.getResult().getResultCode().equals(ResultCode.UNWILLING_TO_PERFORM)) {
            if (debug.warningEnabled()) {
                debug.message("Account Inactivated or Locked ");
            }
            throw new LDAPUtilException("FConnect", ResultCode.UNWILLING_TO_PERFORM, null);
        } else if (ere.getResult().getResultCode().equals(ResultCode.NO_SUCH_OBJECT)) {
            throw new LDAPUtilException("noUserMatchFound", ResultCode.NO_SUCH_OBJECT, null);
        } else {
            if (debug.warningEnabled()) {
                debug.warning("Exception while searching", ere);
            }
            setState(ModuleState.USER_NOT_FOUND);
        }
    } catch (SearchResultReferenceIOException srrio) {
        debug.error("Unable to complete search for user: " + userId, srrio);
        throw new LDAPUtilException(srrio);
    }
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) Attribute(org.forgerock.opendj.ldap.Attribute) ByteString(org.forgerock.opendj.ldap.ByteString) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Iterator(java.util.Iterator) LdapException(org.forgerock.opendj.ldap.LdapException) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 5 with ByteString

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

the class DJLDAPv3Repo method getFilteredRoleMembers.

/**
     * Returns the DNs of the members of this filtered role. To do that this will execute a read on the filtered role
     * entry to get the values of the nsRoleFilter attribute, and then it will perform searches using the retrieved
     * filters.
     *
     * @param dn The DN of the filtered role to query.
     * @return The DNs of the members.
     * @throws IdRepoException If there is an error while trying to retrieve the filtered role members.
     */
private Set<String> getFilteredRoleMembers(String dn) throws IdRepoException {
    Set<String> results = new HashSet<String>();
    Connection conn = null;
    try {
        conn = connectionFactory.getConnection();
        SearchResultEntry entry = conn.searchSingleEntry(LDAPRequests.newSingleEntrySearchRequest(dn, roleFilterAttr));
        Attribute filterAttr = entry.getAttribute(roleFilterAttr);
        if (filterAttr != null) {
            for (ByteString byteString : filterAttr) {
                Filter filter = Filter.valueOf(byteString.toString());
                //TODO: would it make sense to OR these filters and run a single search?
                SearchRequest searchRequest = LDAPRequests.newSearchRequest(rootSuffix, defaultScope, filter.toString(), DN_ATTR);
                searchRequest.setTimeLimit(defaultTimeLimit);
                searchRequest.setSizeLimit(defaultSizeLimit);
                ConnectionEntryReader reader = conn.search(searchRequest);
                while (reader.hasNext()) {
                    if (reader.isEntry()) {
                        results.add(reader.readEntry().getName().toString());
                    } else {
                        //ignore search result references
                        reader.readReference();
                    }
                }
            }
        }
    } catch (LdapException ere) {
        DEBUG.error("An error occurred while trying to retrieve filtered role members for " + dn, ere);
        handleErrorResult(ere);
    } catch (SearchResultReferenceIOException srrioe) {
        //should never ever happen...
        DEBUG.error("Got reference instead of entry", srrioe);
        throw newIdRepoException(IdRepoErrorCode.SEARCH_FAILED, CLASS_NAME);
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
    return results;
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Attribute(org.forgerock.opendj.ldap.Attribute) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) Filter(org.forgerock.opendj.ldap.Filter) ByteString(org.forgerock.opendj.ldap.ByteString) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) LdapException(org.forgerock.opendj.ldap.LdapException) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Aggregations

ByteString (org.forgerock.opendj.ldap.ByteString)27 Attribute (org.forgerock.opendj.ldap.Attribute)22 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)16 LdapException (org.forgerock.opendj.ldap.LdapException)14 Connection (org.forgerock.opendj.ldap.Connection)12 HashSet (java.util.HashSet)11 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)11 SearchResultReferenceIOException (org.forgerock.opendj.ldap.SearchResultReferenceIOException)8 IOException (java.io.IOException)6 Set (java.util.Set)5 Principal (java.security.Principal)4 ArrayList (java.util.ArrayList)4 BindRequest (org.forgerock.opendj.ldap.requests.BindRequest)4 SearchRequest (org.forgerock.opendj.ldap.requests.SearchRequest)4 BindResult (org.forgerock.opendj.ldap.responses.BindResult)4 AndFilter (org.springframework.ldap.filter.AndFilter)4 EqualsFilter (org.springframework.ldap.filter.EqualsFilter)4 LinkedHashSet (java.util.LinkedHashSet)3 SSOException (com.iplanet.sso.SSOException)2 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)2