Search in sources :

Example 11 with ConnectionFactory

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

the class DataLayer method changePassword.

/**
     * Changes user password.
     * 
     * @param guid globally unique identifier for the entry.
     * @param attrName password attribute name
     * @param oldPassword old password
     * @param newPassword new password
     * @exception AccessRightsException if insufficient access
     * @exception EntryNotFoundException if the entry is not found.
     * @exception UMSException if failure
     *
     * @supported.api
     */
public void changePassword(Guid guid, String attrName, String oldPassword, String newPassword) throws UMSException {
    Modification modification = new Modification(ModificationType.REPLACE, Attributes.singletonAttribute(attrName, newPassword));
    String id = guid.getDn();
    try {
        DSConfigMgr dsCfg = DSConfigMgr.getDSConfigMgr();
        String hostAndPort = dsCfg.getHostName("default");
        // All connections will use authentication
        SimpleBindRequest bindRequest = LDAPRequests.newSimpleBindRequest(id, oldPassword.toCharArray());
        Options options = Options.defaultOptions().set(AUTHN_BIND_REQUEST, bindRequest);
        try (ConnectionFactory factory = new LDAPConnectionFactory(hostAndPort, 389, options)) {
            Connection ldc = factory.getConnection();
            ldc.modify(LDAPRequests.newModifyRequest(id).addModification(modification));
        } catch (LdapException ldex) {
            if (debug.warningEnabled()) {
                debug.warning("DataLayer.changePassword:", ldex);
            }
            ResultCode errorCode = ldex.getResult().getResultCode();
            if (ResultCode.NO_SUCH_OBJECT.equals(errorCode)) {
                throw new EntryNotFoundException(id, ldex);
            } else if (ResultCode.INSUFFICIENT_ACCESS_RIGHTS.equals(errorCode)) {
                throw new AccessRightsException(id, ldex);
            } else {
                throw new UMSException(id, ldex);
            }
        }
    } catch (LDAPServiceException ex) {
        debug.error("DataLayer.changePassword:", ex);
        throw new UMSException(id, ex);
    }
}
Also used : Modification(org.forgerock.opendj.ldap.Modification) Options(org.forgerock.util.Options) Connection(org.forgerock.opendj.ldap.Connection) DSConfigMgr(com.iplanet.services.ldap.DSConfigMgr) ByteString(org.forgerock.opendj.ldap.ByteString) SimpleBindRequest(org.forgerock.opendj.ldap.requests.SimpleBindRequest) ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) LDAPServiceException(com.iplanet.services.ldap.LDAPServiceException) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode)

Example 12 with ConnectionFactory

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

the class Bootstrap method getConfiguration.

/**
     * Returns System Property with an URL.
     *
     * @param bootstrapData an URL that contains information on how to
     *        fetch the server configuration properties.
     * @param reinit <code>true</code> to re initialize the system.
     * @throws Exception if properties cannot be loaded.
     */
private static Properties getConfiguration(BootstrapData bootstrapData, boolean reinit, boolean bStartDS) throws Exception {
    Properties properties = null;
    bootstrapData.initSMS(bStartDS);
    if (reinit) {
        AdminUtils.initialize();
        SMSAuthModule.initialize();
    }
    DSConfigMgr dsCfg = DSConfigMgr.getDSConfigMgr();
    ServerGroup sg = dsCfg.getServerGroup("sms");
    if (sg == null) {
        return null;
    }
    try (ConnectionFactory factory = dsCfg.getNewConnectionFactory("sms", LDAPUser.Type.AUTH_ADMIN);
        Connection conn = factory.getConnection()) {
    // Success case. Managed to get connection
    } catch (LDAPServiceException e) {
        // ignore, DS is down
        return null;
    }
    String dsbasedn = bootstrapData.getUserBaseDN();
    String pwd = bootstrapData.getDsameUserPassword();
    String dsameUser = "cn=dsameuser,ou=DSAME Users," + dsbasedn;
    String instanceName = bootstrapData.getInstanceName();
    SSOToken ssoToken = getSSOToken(dsbasedn, dsameUser, JCECrypt.decode(pwd));
    try {
        properties = ServerConfiguration.getServerInstance(ssoToken, instanceName);
        if (properties != null) {
            // set debug level to error because debug.message in
            // SMSEntry.initializedClass won't work and will print out
            // error message. Save the debug level and will be restored
            // after SMSEntry.initializedClass.
            String debugLevel = (String) properties.get(Constants.SERVICES_DEBUG_LEVEL);
            boolean debugSetAtDefault = false;
            if (debugLevel == null) {
                debugSetAtDefault = true;
            }
            properties.setProperty(Constants.SERVICES_DEBUG_LEVEL, Debug.STR_ERROR);
            SystemProperties.initializeProperties(properties, true, false);
            DebugPropertiesObserver debugPO = DebugPropertiesObserver.getInstance();
            String serverConfigXML = ServerConfiguration.getServerConfigXML(ssoToken, instanceName);
            Crypt.reinitialize();
            BootstrapData.loadServerConfigXML(serverConfigXML);
            SMSEntry.initializeClass();
            if (debugSetAtDefault) {
                properties.remove(Constants.SERVICES_DEBUG_LEVEL);
            } else {
                properties.setProperty(Constants.SERVICES_DEBUG_LEVEL, debugLevel);
            }
            SystemProperties.initializeProperties(properties, true, true);
            String defaultDebugLevel = SystemProperties.getProperties().getProperty(Constants.SERVICES_DEBUG_LEVEL);
            if (debugSetAtDefault) {
                properties.setProperty(Constants.SERVICES_DEBUG_LEVEL, defaultDebugLevel);
                SystemProperties.initializeProperties(properties, true, true);
            }
            AdminUtils.initialize();
            SMSAuthModule.initialize();
            debugPO.notifyChanges();
            SMSPropertiesObserver.getInstance().notifyChanges();
            SystemProperties.setServerInstanceName(instanceName);
        // ConfigurationObserver is already added when 
        // DebugPropertiesObserver.getInstance().notifyChanges();
        // is called. Adding again causes 2 notification events
        // to be sent.
        // ServiceConfigManager scm = new ServiceConfigManager(
        //    Constants.SVC_NAME_PLATFORM, (SSOToken)
        //        AccessController.doPrivileged(
        //        AdminTokenAction.getInstance()));
        // scm.addListener(ConfigurationObserver.getInstance());
        }
    } catch (SMSException e) {
        //ignore. product is not configured yet.
        System.out.println("Bootstrap.getConfiguration :" + e);
        properties = null;
    }
    return properties;
}
Also used : ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) ServerGroup(com.iplanet.services.ldap.ServerGroup) SSOToken(com.iplanet.sso.SSOToken) DebugPropertiesObserver(com.sun.identity.common.DebugPropertiesObserver) SMSException(com.sun.identity.sm.SMSException) Connection(org.forgerock.opendj.ldap.Connection) DSConfigMgr(com.iplanet.services.ldap.DSConfigMgr) LDAPServiceException(com.iplanet.services.ldap.LDAPServiceException) SystemProperties(com.iplanet.am.util.SystemProperties) Properties(java.util.Properties)

Example 13 with ConnectionFactory

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

the class LDAPAuthUtils method createConnectionPool.

private ConnectionFactory createConnectionPool(Map<String, ConnectionFactory> connectionPools, String bindingUser, char[] bindingPwd) throws LdapException, LDAPUtilException {
    ConnectionFactory connPool;
    try {
        String configName = servers.toString() + ":" + bindingUser;
        connPool = connectionPools.get(configName);
        if (connPool == null) {
            synchronized (connectionPools) {
                connPool = connectionPools.get(configName);
                Options options = Options.defaultOptions().set(REQUEST_TIMEOUT, new Duration((long) operationsTimeout, TimeUnit.MILLISECONDS));
                if (connPool == null) {
                    if (debug.messageEnabled()) {
                        debug.message("Create ConnectionPool for servers:\n" + servers);
                    }
                    // Since connection pool for search and authentication
                    // are different, each gets half the configured size
                    int min = minDefaultPoolSize / 2 + 1;
                    int max = maxDefaultPoolSize / 2;
                    if (min >= max) {
                        min = max - 1;
                    }
                    Set<LDAPURL> primaryUrls = convertToLDAPURLs(primaryServers);
                    Set<LDAPURL> secondaryUrls = convertToLDAPURLs(secondaryServers);
                    if (poolSize != null && !poolSize.isEmpty()) {
                        String tmpmin = null;
                        String tmpmax = null;
                        for (String val : poolSize) {
                            // host:port:min:max
                            StringTokenizer stz = new StringTokenizer(val, ":");
                            if (stz.countTokens() == 4) {
                                LDAPURL url = LDAPURL.valueOf(stz.nextToken() + ":" + stz.nextToken());
                                if (primaryUrls.contains(url) || secondaryUrls.contains(url)) {
                                    tmpmin = stz.nextToken();
                                    tmpmax = stz.nextToken();
                                    break;
                                }
                            }
                        }
                        if (tmpmin != null) {
                            try {
                                min = Integer.parseInt(tmpmin);
                                max = Integer.parseInt(tmpmax);
                                if (max < min) {
                                    debug.error("ldap connection pool max size is less than min size");
                                    min = minDefaultPoolSize;
                                    max = maxDefaultPoolSize;
                                }
                            } catch (NumberFormatException ex) {
                                debug.error("Invalid ldap connection pool size", ex);
                                min = minDefaultPoolSize;
                                max = maxDefaultPoolSize;
                            }
                        }
                    }
                    if (debug.messageEnabled()) {
                        debug.message("LDAPAuthUtils.LDAPAuthUtils: min=" + min + ", max=" + max);
                    }
                    if (isSecure) {
                        SSLContextBuilder builder = new SSLContextBuilder();
                        if (trustAll) {
                            builder.setTrustManager(TrustManagers.trustAll());
                        }
                        SSLContext sslContext = builder.getSSLContext();
                        options.set(SSL_CONTEXT, sslContext);
                        if (useStartTLS) {
                            options.set(SSL_USE_STARTTLS, true);
                        }
                    }
                    final ConnectionFactory connFactory;
                    ConnectionFactory primaryCf = newFailoverConnectionPool(primaryUrls, bindingUser, bindingPwd, max, heartBeatInterval, heartBeatTimeUnit, options);
                    if (secondaryServers.isEmpty()) {
                        connFactory = primaryCf;
                    } else {
                        ConnectionFactory secondaryCf = newFailoverConnectionPool(secondaryUrls, bindingUser, bindingPwd, max, heartBeatInterval, heartBeatTimeUnit, options);
                        connFactory = Connections.newFailoverLoadBalancer(asList(primaryCf, secondaryCf), options);
                    }
                    ShutdownManager shutdownMan = com.sun.identity.common.ShutdownManager.getInstance();
                    shutdownMan.addShutdownListener(new ShutdownListener() {

                        public void shutdown() {
                            connFactory.close();
                        }
                    });
                    connPool = connFactory;
                    connectionPools.put(configName, connPool);
                }
            }
        }
    } catch (GeneralSecurityException gse) {
        debug.error("Unable to create connection pool", gse);
        throw new LDAPUtilException(gse);
    }
    return connPool;
}
Also used : Options(org.forgerock.util.Options) DecodeOptions(org.forgerock.opendj.ldap.DecodeOptions) GeneralSecurityException(java.security.GeneralSecurityException) ShutdownManager(com.sun.identity.common.ShutdownManager) Duration(org.forgerock.util.time.Duration) ByteString(org.forgerock.opendj.ldap.ByteString) SSLContext(javax.net.ssl.SSLContext) ShutdownListener(org.forgerock.util.thread.listener.ShutdownListener) ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) StringTokenizer(java.util.StringTokenizer) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder)

Example 14 with ConnectionFactory

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

the class ServiceBase method getLDAPConnection.

/**
     * Returns a LDAP connection to the directory host.
     *
     * @param dsHostName name of the sever where DS is installed
     * @param dsPort port at which the directory server is listening
     * @param dsProtocol protocol used by directory server
     * @param dsManager admin user name for directory server
     * @param dsAdminPwd  admin password used by admin user name
     * @return LDAP connection
     */
protected static Connection getLDAPConnection(String dsHostName, int dsPort, String dsProtocol, String dsManager, String dsAdminPwd) {
    try {
        // All connections will use authentication
        Options options = Options.defaultOptions().set(CONNECT_TIMEOUT, new Duration((long) 3, TimeUnit.SECONDS)).set(AUTHN_BIND_REQUEST, LDAPRequests.newSimpleBindRequest(dsManager, dsAdminPwd.toCharArray()));
        if (dsProtocol.equalsIgnoreCase("ldaps")) {
            options = options.set(SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
        }
        ConnectionFactory factory = new LDAPConnectionFactory(dsHostName, dsPort, options);
        return factory.getConnection();
    } catch (Exception ignored) {
        return null;
    }
}
Also used : Options(org.forgerock.util.Options) ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) Duration(org.forgerock.util.time.Duration) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder) LdapException(org.forgerock.opendj.ldap.LdapException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

ConnectionFactory (org.forgerock.opendj.ldap.ConnectionFactory)14 LDAPConnectionFactory (org.forgerock.opendj.ldap.LDAPConnectionFactory)12 Connection (org.forgerock.opendj.ldap.Connection)6 SSLContextBuilder (org.forgerock.opendj.ldap.SSLContextBuilder)5 Options (org.forgerock.util.Options)5 DSConfigMgr (com.iplanet.services.ldap.DSConfigMgr)4 LDAPServiceException (com.iplanet.services.ldap.LDAPServiceException)4 ByteString (org.forgerock.opendj.ldap.ByteString)4 ArrayList (java.util.ArrayList)3 LdapException (org.forgerock.opendj.ldap.LdapException)3 ShutdownListener (org.forgerock.util.thread.listener.ShutdownListener)3 Duration (org.forgerock.util.time.Duration)3 ServerGroup (com.iplanet.services.ldap.ServerGroup)2 ServerInstance (com.iplanet.services.ldap.ServerInstance)2 SMSException (com.sun.identity.sm.SMSException)2 IOException (java.io.IOException)2 GeneralSecurityException (java.security.GeneralSecurityException)2 StringTokenizer (java.util.StringTokenizer)2 ShutdownManager (org.forgerock.util.thread.listener.ShutdownManager)2 SystemProperties (com.iplanet.am.util.SystemProperties)1