Search in sources :

Example 1 with SSLContextBuilder

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

the class LocalLdapAuthModule method authenticate.

private boolean authenticate(String dn, String passwd) throws LoginException {
    // LDAP connection used for authentication
    Connection localConn = null;
    String host;
    int port;
    Options ldapOptions = Options.defaultOptions();
    // Check if organization is present in options
    String orgUrl = (String) options.get(LoginContext.ORGNAME);
    if ((orgUrl == null) || (orgUrl.equals(LoginContext.LDAP_AUTH_URL)) || (orgUrl.equals(LoginContext.LDAPS_AUTH_URL)) || !(orgUrl.startsWith(LoginContext.LDAP_AUTH_URL) || orgUrl.startsWith(LoginContext.LDAPS_AUTH_URL))) {
        try {
            DSConfigMgr dscm = DSConfigMgr.getDSConfigMgr();
            // We need a handle on server instance so we can know the
            // Connection type. If it is SSL, the connection needs to be
            // accordingly created. Note: The user type does not make
            // a difference, as the connection type is Server group based,
            // so passing any user type for the second argument.
            ServerInstance si = dscm.getServerInstance(DSConfigMgr.DEFAULT, LDAPUser.Type.AUTH_BASIC);
            String hostName = dscm.getHostName(DSConfigMgr.DEFAULT);
            if (si.getConnectionType() == Server.Type.CONN_SSL) {
                try {
                    ldapOptions.set(LDAPConnectionFactory.SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
                } catch (GeneralSecurityException e) {
                    debug.error("getConnection.JSSESocketFactory", e);
                    throw new LDAPServiceException(AuthI18n.authI18n.getString(IUMSConstants.DSCFG_JSSSFFAIL));
                }
            }
            if (dn != null && passwd != null) {
                // The 389 port number passed is overridden by the
                // hostName:port
                // constructed by the getHostName method. So, this is not
                // a hardcoded port number.
                host = hostName;
                port = 389;
            } else {
                // Throw LoginException
                throw new LoginException(AuthI18n.authI18n.getString(IUMSConstants.DSCFG_CONNECTFAIL));
            }
        } catch (LDAPServiceException ex) {
            debug.error("Authenticate failed: " + ex);
            throw new LoginException(ex.getMessage());
        }
    } else {
        try {
            if (debug.messageEnabled()) {
                debug.message("authenticate(): orgUrl= " + orgUrl);
            }
            // Get hostname
            int start;
            boolean useSSL = false;
            if (orgUrl.startsWith(LoginContext.LDAPS_AUTH_URL)) {
                start = LoginContext.LDAPS_AUTH_URL.length();
                useSSL = true;
            } else {
                start = LoginContext.LDAP_AUTH_URL.length();
            }
            int end = orgUrl.indexOf(':', start);
            if (end == -1) {
                end = orgUrl.indexOf('/', start);
                if (end == -1)
                    end = orgUrl.length();
            }
            String hostName = orgUrl.substring(start, end);
            // Get port number
            String portNumber = "389";
            start = end + 1;
            if (start < orgUrl.length()) {
                end = orgUrl.indexOf('/', start);
                if (end == -1)
                    end = orgUrl.length();
                portNumber = orgUrl.substring(start, end);
            }
            if (useSSL) {
                try {
                    ldapOptions.set(LDAPConnectionFactory.SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
                } catch (GeneralSecurityException e) {
                    debug.error("authentication().JSSESocketFactory()", e);
                    throw (new LoginException(e.getMessage()));
                }
            }
            if (debug.messageEnabled()) {
                debug.message("before connect(), hostName=" + hostName + ",port=" + portNumber);
            }
            host = hostName;
            port = Integer.parseInt(portNumber);
        } catch (Exception e) {
            debug.error("authentication", e);
            throw (new LoginException(e.getMessage()));
        }
    }
    try (ConnectionFactory factory = LDAPUtils.createFailoverConnectionFactory(host, port, dn, passwd, ldapOptions);
        Connection conn = factory.getConnection()) {
        return true;
    } catch (LdapException e) {
        throw new LoginException(e.getMessage());
    }
}
Also used : Options(org.forgerock.util.Options) GeneralSecurityException(java.security.GeneralSecurityException) Connection(org.forgerock.opendj.ldap.Connection) DSConfigMgr(com.iplanet.services.ldap.DSConfigMgr) LoginException(javax.security.auth.login.LoginException) LDAPServiceException(com.iplanet.services.ldap.LDAPServiceException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) LdapException(org.forgerock.opendj.ldap.LdapException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) LoginException(javax.security.auth.login.LoginException) LDAPServiceException(com.iplanet.services.ldap.LDAPServiceException) ServerInstance(com.iplanet.services.ldap.ServerInstance) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder) LdapException(org.forgerock.opendj.ldap.LdapException)

Example 2 with SSLContextBuilder

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

the class IdRepoUtils method getLDAPConnection.

private static ConnectionFactory getLDAPConnection(Map attrValues) throws Exception {
    Options options = Options.defaultOptions().set(CONNECT_TIMEOUT, new Duration((long) 300, TimeUnit.MILLISECONDS));
    if (CollectionHelper.getBooleanMapAttr(attrValues, "sun-idrepo-ldapv3-config-ssl-enabled", false)) {
        options = options.set(SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
    }
    Set<LDAPURL> ldapUrls = getLDAPUrls(attrValues);
    if (CollectionUtils.isEmpty(ldapUrls)) {
        if (DEBUG.warningEnabled()) {
            DEBUG.warning("IdRepoUtils.getLDAPConnection: No LDAPURLs found");
        }
        throw new IdRepoException(IdRepoBundle.BUNDLE_NAME, IdRepoErrorCode.UNABLE_AUTHENTICATE_LDAP_SERVER, null);
    }
    LDAPURL ldapUrl = ldapUrls.iterator().next();
    if (org.forgerock.openam.utils.StringUtils.isEmpty(ldapUrl.getHost())) {
        if (DEBUG.warningEnabled()) {
            DEBUG.warning("IdRepoUtils.getLDAPConnection: No LDAP host found");
        }
        throw new IdRepoException(IdRepoBundle.BUNDLE_NAME, IdRepoErrorCode.UNABLE_AUTHENTICATE_LDAP_SERVER, null);
    }
    // All connections will use authentication
    String bindDn = CollectionHelper.getMapAttr(attrValues, "sun-idrepo-ldapv3-config-authid");
    if (org.forgerock.openam.utils.StringUtils.isBlank(bindDn)) {
        if (DEBUG.warningEnabled()) {
            DEBUG.warning("IdRepoUtils.getLDAPConnection: No LDAP bindDN found");
        }
        throw new IdRepoException(IdRepoBundle.BUNDLE_NAME, IdRepoErrorCode.UNABLE_AUTHENTICATE_LDAP_SERVER, null);
    }
    String bindPwd = CollectionHelper.getMapAttr(attrValues, "sun-idrepo-ldapv3-config-authpw");
    if (org.forgerock.openam.utils.StringUtils.isBlank(bindPwd)) {
        if (DEBUG.warningEnabled()) {
            DEBUG.warning("IdRepoUtils.getLDAPConnection: No LDAP bindPW found");
        }
        throw new IdRepoException(IdRepoBundle.BUNDLE_NAME, IdRepoErrorCode.UNABLE_AUTHENTICATE_LDAP_SERVER, null);
    }
    options = options.set(AUTHN_BIND_REQUEST, LDAPRequests.newSimpleBindRequest(bindDn, bindPwd.toCharArray()));
    return new LDAPConnectionFactory(ldapUrl.getHost(), ldapUrl.getPort(), options);
}
Also used : Options(org.forgerock.util.Options) LDAPURL(org.forgerock.openam.ldap.LDAPURL) IdRepoException(com.sun.identity.idm.IdRepoException) Duration(org.forgerock.util.time.Duration) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder)

Example 3 with SSLContextBuilder

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

the class LDAPUtils method newConnectionFactory.

/**
     * Creates a new connection factory based on the provided parameters.
     *
     * @param ldapurl The address of the LDAP server.
     * @param username The directory user's DN. May be null if this is an anonymous connection.
     * @param password The directory user's password.
     * @param heartBeatInterval The interval for sending out heartbeat requests.
     * @param heartBeatTimeUnit The timeunit for the heartbeat interval.
     * @param ldapOptions Additional LDAP settings used to create the connection factory.
     * @return An authenticated/anonymous connection factory, which may also send heartbeat requests.
     */
private static ConnectionFactory newConnectionFactory(LDAPURL ldapurl, String username, char[] password, int heartBeatInterval, String heartBeatTimeUnit, Options ldapOptions) {
    Boolean ssl = ldapurl.isSSL();
    int heartBeatTimeout = SystemPropertiesManager.getAsInt(Constants.LDAP_HEARTBEAT_TIMEOUT, DEFAULT_HEARTBEAT_TIMEOUT);
    if (ssl != null && ssl.booleanValue()) {
        try {
            //Creating a defensive copy of ldapOptions to handle the case when a mixture of SSL/non-SSL connections
            //needs to be established.
            ldapOptions = Options.copyOf(ldapOptions).set(LDAPConnectionFactory.SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
        } catch (GeneralSecurityException gse) {
            DEBUG.error("An error occurred while creating SSLContext", gse);
        }
    }
    // Enable heartbeat
    if (heartBeatInterval > 0 && heartBeatTimeUnit != null) {
        TimeUnit unit = TimeUnit.valueOf(heartBeatTimeUnit.toUpperCase());
        ldapOptions = ldapOptions.set(HEARTBEAT_ENABLED, true).set(HEARTBEAT_INTERVAL, new Duration(unit.toSeconds(heartBeatInterval), TimeUnit.SECONDS)).set(HEARTBEAT_TIMEOUT, new Duration(unit.toSeconds(heartBeatTimeout), TimeUnit.SECONDS));
    }
    // Enable Authenticated connection
    if (username != null) {
        ldapOptions = ldapOptions.set(AUTHN_BIND_REQUEST, LDAPRequests.newSimpleBindRequest(username, password));
    }
    return new LDAPConnectionFactory(ldapurl.getHost(), ldapurl.getPort(), ldapOptions);
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) TimeUnit(java.util.concurrent.TimeUnit) Duration(org.forgerock.util.time.Duration) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder)

Example 4 with SSLContextBuilder

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

the class LDAPConnectionPools method initConnectionPool.

/**
     * Create a Ldap Connection Pool for a ldap server
     * @param host the name of the LDAP server host and its port number.
     *        For example, dsame.sun.com:389
     *        Alternatively, this can be a space-delimited list of
     *        host names.
     * @param ssl if the connection is in ssl
     * @param minPoolSize minimal pool size
     * @param maxPoolSize maximum pool size
     */
static void initConnectionPool(String host, String authDN, String authPasswd, boolean ssl, int minPoolSize, int maxPoolSize, Options options) throws PolicyException {
    if (host.length() < 1) {
        debug.message("Invalid host name");
        throw new PolicyException(ResBundleUtils.rbName, "invalid_ldap_server_host", null, null);
    }
    try {
        synchronized (connectionPools) {
            if (connectionPools.get(host) == null) {
                if (debug.messageEnabled()) {
                    debug.message("Create LDAPConnectionPool: " + host);
                }
                if (ssl) {
                    options.set(LDAPConnectionFactory.SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
                }
                ConnectionFactory ldc = LDAPUtils.createFailoverConnectionFactory(host, DEFAULT_PORT, authDN, authPasswd, options);
                if (minPoolSize < 1) {
                    minPoolSize = MIN_CONNECTION_POOL_SIZE;
                }
                if (maxPoolSize < 1) {
                    maxPoolSize = MAX_CONNECTION_POOL_SIZE;
                }
                debug.message("LDAPConnectionPools.initConnectionPool(): minPoolSize={}, maxPoolSize={}", minPoolSize, maxPoolSize);
                ShutdownManager shutdownMan = com.sun.identity.common.ShutdownManager.getInstance();
                int idleTimeout = SystemProperties.getAsInt(Constants.LDAP_CONN_IDLE_TIME_IN_SECS, 0);
                if (idleTimeout == 0) {
                    debug.error("LDAPConnectionPools: Idle timeout could not be parsed, connection reaping is disabled");
                }
                final ConnectionFactory cPool = Connections.newCachedConnectionPool(ldc, minPoolSize, maxPoolSize, idleTimeout, TimeUnit.SECONDS);
                debug.message("LDAPConnectionPools.initConnectionPool(): host: {}", host);
                shutdownMan.addShutdownListener(new ShutdownListener() {

                    public void shutdown() {
                        cPool.close();
                    }
                });
                connectionPools.put(host, cPool);
            }
        }
    } catch (Exception e) {
        debug.message("Unable to create LDAPConnectionPool", e);
        throw new PolicyException(e.getMessage(), e);
    }
}
Also used : ShutdownListener(org.forgerock.util.thread.listener.ShutdownListener) ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) PolicyException(com.sun.identity.policy.PolicyException) ShutdownManager(org.forgerock.util.thread.listener.ShutdownManager) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder) PolicyException(com.sun.identity.policy.PolicyException)

Example 5 with SSLContextBuilder

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

the class AMSetupDSConfig method getLDAPConnection.

/**
     * Helper method to return Ldap connection 
     *
     * @param ssl <code>true</code> if directory server is running SSL.
     * @return Ldap connection 
     */
private synchronized Connection getLDAPConnection(boolean ssl) {
    try {
        if (ld == null) {
            ShutdownManager shutdownMan = com.sun.identity.common.ShutdownManager.getInstance();
            // All connections will use authentication
            SimpleBindRequest request = LDAPRequests.newSimpleBindRequest(dsManager, dsAdminPwd.toCharArray());
            Options options = Options.defaultOptions().set(REQUEST_TIMEOUT, new Duration((long) 3, TimeUnit.SECONDS)).set(AUTHN_BIND_REQUEST, request);
            if (ssl) {
                options = options.set(SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
            }
            ld = new LDAPConnectionFactory(dsHostName, getPort(), options);
            shutdownMan.addShutdownListener(new ShutdownListener() {

                public void shutdown() {
                    disconnectDServer();
                }
            });
        }
        return ld.getConnection();
    } catch (LdapException e) {
        disconnectDServer();
        dsConfigInstance = null;
        ld = null;
    } catch (Exception e) {
        dsConfigInstance = null;
        ld = null;
    }
    return null;
}
Also used : ShutdownListener(org.forgerock.util.thread.listener.ShutdownListener) Options(org.forgerock.util.Options) SimpleBindRequest(org.forgerock.opendj.ldap.requests.SimpleBindRequest) ShutdownManager(org.forgerock.util.thread.listener.ShutdownManager) Duration(org.forgerock.util.time.Duration) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder) LdapException(org.forgerock.opendj.ldap.LdapException) LdapException(org.forgerock.opendj.ldap.LdapException) IOException(java.io.IOException)

Aggregations

LDAPConnectionFactory (org.forgerock.opendj.ldap.LDAPConnectionFactory)11 SSLContextBuilder (org.forgerock.opendj.ldap.SSLContextBuilder)11 Options (org.forgerock.util.Options)8 Duration (org.forgerock.util.time.Duration)7 GeneralSecurityException (java.security.GeneralSecurityException)5 ConnectionFactory (org.forgerock.opendj.ldap.ConnectionFactory)5 LdapException (org.forgerock.opendj.ldap.LdapException)5 IOException (java.io.IOException)4 ShutdownListener (org.forgerock.util.thread.listener.ShutdownListener)3 ByteString (org.forgerock.opendj.ldap.ByteString)2 Connection (org.forgerock.opendj.ldap.Connection)2 SimpleBindRequest (org.forgerock.opendj.ldap.requests.SimpleBindRequest)2 ShutdownManager (org.forgerock.util.thread.listener.ShutdownManager)2 DSConfigMgr (com.iplanet.services.ldap.DSConfigMgr)1 LDAPServiceException (com.iplanet.services.ldap.LDAPServiceException)1 ServerInstance (com.iplanet.services.ldap.ServerInstance)1 ShutdownManager (com.sun.identity.common.ShutdownManager)1 IdRepoException (com.sun.identity.idm.IdRepoException)1 PolicyException (com.sun.identity.policy.PolicyException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1