Search in sources :

Example 71 with LdapException

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

the class Step4 method validateUMHost.

public boolean validateUMHost() {
    Context ctx = getContext();
    String strSSL = (String) ctx.getSessionAttribute(SessionAttributeNames.USER_STORE_SSL);
    boolean ssl = (strSSL != null) && (strSSL.equals("SSL"));
    String host = (String) ctx.getSessionAttribute(SessionAttributeNames.USER_STORE_HOST);
    String strPort = (String) ctx.getSessionAttribute(SessionAttributeNames.USER_STORE_PORT);
    int port = Integer.parseInt(strPort);
    String bindDN = (String) ctx.getSessionAttribute(SessionAttributeNames.USER_STORE_LOGIN_ID);
    String rootSuffix = (String) ctx.getSessionAttribute(SessionAttributeNames.USER_STORE_ROOT_SUFFIX);
    String bindPwd = (String) ctx.getSessionAttribute(SessionAttributeNames.USER_STORE_LOGIN_PWD);
    try (Connection conn = getConnection(host, port, bindDN, bindPwd.toCharArray(), 5, ssl)) {
        //String filter = "cn=" + "\"" + rootSuffix + "\"";    // NOT SURE Why "cn" is specified. would never work.
        String[] attrs = { "" };
        conn.search(LDAPRequests.newSearchRequest(rootSuffix, SearchScope.BASE_OBJECT, ObjectClassFilter, attrs));
        writeToResponse("ok");
    } catch (LdapException lex) {
        ResultCode resultCode = lex.getResult().getResultCode();
        if (!writeErrorToResponse(resultCode)) {
            writeToResponse(getLocalizedString("cannot.connect.to.SM.datastore"));
        }
    } catch (Exception e) {
        writeToResponse(getLocalizedString("cannot.connect.to.SM.datastore"));
    }
    setPath(null);
    return false;
}
Also used : DirContext(javax.naming.directory.DirContext) InitialDirContext(javax.naming.directory.InitialDirContext) Context(org.apache.click.Context) Connection(org.forgerock.opendj.ldap.Connection) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode) LdapException(org.forgerock.opendj.ldap.LdapException) IOException(java.io.IOException) NamingException(javax.naming.NamingException)

Example 72 with LdapException

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

the class DJLDAPv3Repo method create.

/**
     * Creates a new identity using the passed in attributes. The following steps will be performed with the passed in
     * data:
     * <ul>
     *  <li>The password will be encoded in case we are dealing with AD.</li>
     *  <li>If the attribute map contains the default status attribute, then it will be converted to the status values
     *      specified in the configuration.</li>
     *  <li>Performing creation attribute mapping, so certain attributes can have default values (coming from other
     *      attributes, or from the identity name if there is no mapping for the attribute).</li>
     *  <li>Removes all attributes that are not defined in the configuration.</li>
     * </ul>
     * If the default group member setting is being used and a new group identity is being created, the newly created
     * group will also have the default group member assigned.
     *
     * @param token Not used.
     * @param type The type of the identity.
     * @param name The name of the identity.
     * @param attrMap The attributes of the new identity, that needs to be stored.
     * @return The DN of the newly created identity
     * @throws IdRepoException If there is an error while creating the new identity, or if it's a group and there is a
     * problem while adding the default group member.
     */
@Override
public String create(SSOToken token, IdType type, String name, Map<String, Set<String>> attrMap) throws IdRepoException {
    if (DEBUG.messageEnabled()) {
        DEBUG.message("Create invoked on " + type + ": " + name + " attrMap = " + IdRepoUtils.getAttrMapWithoutPasswordAttrs(attrMap, null));
    }
    String dn = generateDN(type, name);
    Set<String> objectClasses = getObjectClasses(type);
    //First we should make sure that we wrap the attributes with a case insensitive hashmap.
    attrMap = new CaseInsensitiveHashMap(attrMap);
    byte[] encodedPwd = helper.encodePassword(type, attrMap.get(AD_UNICODE_PWD_ATTR));
    //Let's set the userstatus as it is configured in the datastore.
    mapUserStatus(type, attrMap);
    //In case some attributes are missing use the create attribute mapping to get those values.
    mapCreationAttributes(type, name, attrMap);
    //and lastly we should make sure that we get rid of the attributes that are not known by the datastore.
    attrMap = removeUndefinedAttributes(type, attrMap);
    Set<String> ocs = attrMap.get(OBJECT_CLASS_ATTR);
    if (ocs != null) {
        ocs.addAll(objectClasses);
    } else {
        attrMap.put(OBJECT_CLASS_ATTR, objectClasses);
    }
    attrMap.put(getSearchAttribute(type), asSet(name));
    Entry entry = new LinkedHashMapEntry(dn);
    Set<String> attributeValue;
    for (Map.Entry<String, Set<String>> attr : attrMap.entrySet()) {
        // Add only attributes whose values are not empty or null
        attributeValue = attr.getValue();
        if (attributeValue != null && !attributeValue.isEmpty()) {
            entry.addAttribute(attr.getKey(), attributeValue.toArray());
        }
    }
    if (type.equals(IdType.GROUP) && defaultGroupMember != null) {
        entry.addAttribute(uniqueMemberAttr, defaultGroupMember);
    }
    if (encodedPwd != null) {
        entry.replaceAttribute(AD_UNICODE_PWD_ATTR, encodedPwd);
    }
    Connection conn = null;
    try {
        conn = connectionFactory.getConnection();
        conn.add(LDAPRequests.newAddRequest(entry));
        if (type.equals(IdType.GROUP) && defaultGroupMember != null) {
            if (memberOfAttr != null) {
                ModifyRequest modifyRequest = LDAPRequests.newModifyRequest(defaultGroupMember);
                modifyRequest.addModification(ModificationType.ADD, memberOfAttr, dn);
                conn.modify(modifyRequest);
            }
        }
    } catch (LdapException ere) {
        DEBUG.error("Unable to add a new entry: " + name + " attrMap: " + IdRepoUtils.getAttrMapWithoutPasswordAttrs(attrMap, null), ere);
        if (ResultCode.ENTRY_ALREADY_EXISTS.equals(ere.getResult().getResultCode())) {
            throw IdRepoDuplicateObjectException.nameAlreadyExists(name);
        } else {
            handleErrorResult(ere);
        }
    } finally {
        IOUtils.closeIfNotNull(conn);
    }
    return dn;
}
Also used : SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry) LinkedHashMapEntry(org.forgerock.opendj.ldap.LinkedHashMapEntry) Entry(org.forgerock.opendj.ldap.Entry) Set(java.util.Set) CaseInsensitiveHashSet(com.sun.identity.common.CaseInsensitiveHashSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) CollectionUtils.asSet(org.forgerock.openam.utils.CollectionUtils.asSet) LinkedHashMapEntry(org.forgerock.opendj.ldap.LinkedHashMapEntry) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) ModifyRequest(org.forgerock.opendj.ldap.requests.ModifyRequest) Map(java.util.Map) HashMap(java.util.HashMap) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap) LdapException(org.forgerock.opendj.ldap.LdapException) CaseInsensitiveHashMap(com.sun.identity.common.CaseInsensitiveHashMap)

Example 73 with LdapException

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

the class AMCertStore method getConnection.

/**
     * Return ldap connection for ldap certificate store, or null if an error occured when connecting.
     */
synchronized Connection getConnection() {
    if (ldapconn == null) {
        /*
             * Setup the LDAP certificate directory service context for
             * use in verification of the users certificates.
             */
        String serverName = storeParam.getServerName();
        int port = storeParam.getPort();
        LDAPConnectionFactory factory;
        // Regardless of SSL on connection, we will use authentication
        SimpleBindRequest authenticatedRequest = LDAPRequests.newSimpleBindRequest(storeParam.getUser(), storeParam.getPassword().toCharArray());
        Options options = Options.defaultOptions().set(AUTHN_BIND_REQUEST, authenticatedRequest);
        if (storeParam.isSecure()) {
            debug.message("AMCertStore.getConnection: initial connection factory using ssl.");
            try {
                options = options.set(SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
                ldapconn = new LDAPConnectionFactory(serverName, port, options);
                debug.message("AMCertStore.getConnection: SSLSocketFactory called");
            } catch (GeneralSecurityException e) {
                debug.error("AMCertStore.getConnection: Error getting SSL Context", e);
                return null;
            }
        } else {
            // non-ssl
            ldapconn = new LDAPConnectionFactory(serverName, port, options);
        }
    }
    try {
        return ldapconn.getConnection();
    } catch (LdapException e) {
        debug.error("AMCertStore.getConnection: Exception in connection to LDAP server", e);
        return null;
    }
}
Also used : Options(org.forgerock.util.Options) SimpleBindRequest(org.forgerock.opendj.ldap.requests.SimpleBindRequest) GeneralSecurityException(java.security.GeneralSecurityException) ByteString(org.forgerock.opendj.ldap.ByteString) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder) LdapException(org.forgerock.opendj.ldap.LdapException)

Example 74 with LdapException

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

the class AMCRLStore method updateCRL.

/**
     * It replaces attribute value under the DN.
     * It is used to replace old CRL with new one.
     *
     * @param ldc
     * @param dn
     * @param crls
     */
private void updateCRL(Connection ldc, String dn, byte[] crls) {
    try {
        ModifyRequest modifyRequest = LDAPRequests.newModifyRequest(dn).addModification(ModificationType.REPLACE, mCrlAttrName, crls);
        ldc.modify(modifyRequest);
    } catch (LdapException e) {
        debug.error("Error updating CRL Cache : ", e);
    }
}
Also used : ModifyRequest(org.forgerock.opendj.ldap.requests.ModifyRequest) LdapException(org.forgerock.opendj.ldap.LdapException)

Example 75 with LdapException

use of org.forgerock.opendj.ldap.LdapException 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)

Aggregations

LdapException (org.forgerock.opendj.ldap.LdapException)88 Connection (org.forgerock.opendj.ldap.Connection)62 ByteString (org.forgerock.opendj.ldap.ByteString)41 ResultCode (org.forgerock.opendj.ldap.ResultCode)37 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)35 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)34 SearchRequest (org.forgerock.opendj.ldap.requests.SearchRequest)23 HashSet (java.util.HashSet)22 SearchResultReferenceIOException (org.forgerock.opendj.ldap.SearchResultReferenceIOException)22 Attribute (org.forgerock.opendj.ldap.Attribute)17 PolicyException (com.sun.identity.policy.PolicyException)13 SMSException (com.sun.identity.sm.SMSException)12 ModifyRequest (org.forgerock.opendj.ldap.requests.ModifyRequest)12 SSOException (com.iplanet.sso.SSOException)11 LinkedHashSet (java.util.LinkedHashSet)11 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)10 IOException (java.io.IOException)10 DN (org.forgerock.opendj.ldap.DN)10 InvalidNameException (com.sun.identity.policy.InvalidNameException)9 NameNotFoundException (com.sun.identity.policy.NameNotFoundException)9