Example usage for javax.naming.ldap StartTlsResponse negotiate

List of usage examples for javax.naming.ldap StartTlsResponse negotiate

Introduction

In this page you can find the example usage for javax.naming.ldap StartTlsResponse negotiate.

Prototype

public abstract SSLSession negotiate() throws IOException;

Source Link

Document

Negotiates a TLS session using the default SSL socket factory.

Usage

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * retrieve home directory of given user.
 *
 * @param inBenutzer//from   w ww .  j  a v  a2 s .  com
 *            User object
 * @return path as string
 */
public String getUserHomeDirectory(User inBenutzer) {
    if (ConfigCore.getBooleanParameter("useLocalDirectory", false)) {
        return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
    }
    Hashtable<String, String> env = getLdapConnectionSettings();
    if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) {

        env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url"));
        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            // Authenticate via SASL EXTERNAL mechanism using client X.509
            // certificate contained in JVM keystore
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

            ctx.reconnect(null);

            Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
            Attribute la = attrs.get("homeDirectory");
            return (String) la.get(0);

            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);

            return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
        } catch (NamingException e) {

            logger.error("JNDI error:", e);

            return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e);
                }
            }
        }
    } else if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    } else {
        env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
        env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

    }
    DirContext ctx;
    String rueckgabe = "";
    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
        Attribute la = attrs.get("homeDirectory");
        rueckgabe = (String) la.get(0);
        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
    }
    return rueckgabe;
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * Check if connection with login and password possible.
 *
 * @param inBenutzer//from   w  w w . j  a v a2  s .c  o  m
 *            User object
 * @param inPasswort
 *            String
 * @return Login correct or not
 */
public boolean isUserPasswordCorrect(User inBenutzer, String inPasswort) {
    logger.debug("start login session with ldap");
    Hashtable<String, String> env = getLdapConnectionSettings();

    // Start TLS
    if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) {
        logger.debug("use TLS for auth");
        env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url"));
        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            // Authenticate via SASL EXTERNAL mechanism using client X.509
            // certificate contained in JVM keystore
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, getUserDN(inBenutzer));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inPasswort);
            ctx.reconnect(null);
            return true;
            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);
            return false;
        } catch (NamingException e) {
            logger.error("JNDI error:", e);
            return false;
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e);
                }
            }
        }
    } else {
        logger.debug("don't use TLS for auth");
        if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
            env.put(Context.SECURITY_AUTHENTICATION, "none");
            // TODO auf passwort testen
        } else {
            env.put(Context.SECURITY_PRINCIPAL, getUserDN(inBenutzer));
            env.put(Context.SECURITY_CREDENTIALS, inPasswort);
        }
        logger.debug("ldap environment set");

        try {
            if (logger.isDebugEnabled()) {
                logger.debug("start classic ldap authentification");
                logger.debug("user DN is " + getUserDN(inBenutzer));
            }

            if (ConfigCore.getParameter("ldap_AttributeToTest") == null) {
                logger.debug("ldap attribute to test is null");
                DirContext ctx = new InitialDirContext(env);
                ctx.close();
                return true;
            } else {
                logger.debug("ldap attribute to test is not null");
                DirContext ctx = new InitialDirContext(env);

                Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
                Attribute la = attrs.get(ConfigCore.getParameter("ldap_AttributeToTest"));
                logger.debug("ldap attributes set");
                String test = (String) la.get(0);
                if (test.equals(ConfigCore.getParameter("ldap_ValueOfAttribute"))) {
                    logger.debug("ldap ok");
                    ctx.close();
                    return true;
                } else {
                    logger.debug("ldap not ok");
                    ctx.close();
                    return false;
                }
            }
        } catch (NamingException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("login not allowed for " + inBenutzer.getLogin(), e);
            }
            return false;
        }
    }
}

From source file:org.apache.hadoop.security.authentication.server.LdapAuthenticationHandler.java

private void authenticateWithTlsExtension(String userDN, String password) throws AuthenticationException {
    LdapContext ctx = null;/*  ww w.  j ava  2s . c  om*/
    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, providerUrl);

    try {
        // Create initial context
        ctx = new InitialLdapContext(env, null);
        // Establish TLS session
        StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());

        if (disableHostNameVerification) {
            tls.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }

        tls.negotiate();

        // Initialize security credentials & perform read operation for
        // verification.
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        ctx.lookup(userDN);
        logger.debug("Authentication successful for {}", userDN);

    } catch (NamingException | IOException ex) {
        throw new AuthenticationException("Error validating LDAP user", ex);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) { /* Ignore. */
            }
        }
    }
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

protected StartTlsResponse startTls(InitialLdapContext ctx) throws NamingException, IOException {
    if (getTrustStore() != null && !getTrustStore().equals("")) {
        System.setProperty("javax.net.ssl.trustStore", getTrustStore());
    }//from w w  w .ja v a  2  s . c  o m
    if (getTrustStorePassword() != null && !getTrustStorePassword().equals("")) {
        System.setProperty("javax.net.ssl.trustStorePassword", getTrustStorePassword());
    }

    // Specify client's keyStore where client's certificate is located.
    // Note: Client's keyStore is optional for StartTLS negotiation and connection,
    // but it is required for implicit client indendity assertion
    // by SASL EXTERNAL where client ID is extracted from certificate subject.
    //System.setProperty("javax.net.ssl.keyStore", "myKey.pfx");
    //System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
    //System.setProperty("javax.net.ssl.keyStorePassword", "secret");

    StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
    tls.negotiate();
    return tls;
}

From source file:org.kitodo.production.services.data.LdapServerService.java

private URI getUserHomeDirectoryWithTLS(Hashtable<String, String> env, String userFolderBasePath, User user) {
    env.put("java.naming.ldap.version", "3");
    LdapContext ctx = null;/*from  w ww.ja va 2s  . c  o m*/
    StartTlsResponse tls = null;
    try {
        ctx = new InitialLdapContext(env, null);

        // Authentication must be performed over a secure channel
        tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        tls.negotiate();

        ctx.reconnect(null);

        Attributes attrs = ctx.getAttributes(buildUserDN(user));
        Attribute la = attrs.get("homeDirectory");
        return URI.create((String) la.get(0));
    } catch (IOException e) {
        logger.error("TLS negotiation error:", e);
        return Paths.get(userFolderBasePath, user.getLogin()).toUri();
    } catch (NamingException e) {
        logger.error("JNDI error:", e);
        return Paths.get(userFolderBasePath, user.getLogin()).toUri();
    } finally {
        closeConnections(ctx, tls);
    }
}

From source file:org.kitodo.production.services.data.LdapServerService.java

private boolean isPasswordCorrectForAuthWithTLS(Hashtable<String, String> env, User user, String password) {
    env.put("java.naming.ldap.version", "3");
    LdapContext ctx = null;/*from   ww  w .jav  a  2 s.c o  m*/
    StartTlsResponse tls = null;
    try {
        ctx = new InitialLdapContext(env, null);

        // Authentication must be performed over a secure channel
        tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        tls.negotiate();

        // Authenticate via SASL EXTERNAL mechanism using client X.509
        // certificate contained in JVM keystore
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, buildUserDN(user));
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        ctx.reconnect(null);
        return true;
        // perform search for privileged attributes under authenticated context
    } catch (IOException e) {
        logger.error("TLS negotiation error:", e);
        return false;
    } catch (NamingException e) {
        logger.error("JNDI error:", e);
        return false;
    } finally {
        closeConnections(ctx, tls);
    }
}

From source file:org.kitodo.services.data.LdapServerService.java

/**
 * Check if connection with login and password possible.
 *
 * @param user/*from  w  w w . j a  va2  s  .co  m*/
 *            User object
 * @param password
 *            String
 * @return Login correct or not
 */
public boolean isUserPasswordCorrect(User user, String password) {
    logger.debug("start login session with ldap");
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());

    // Start TLS
    if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) {
        logger.debug("use TLS for auth");
        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            // Authenticate via SASL EXTERNAL mechanism using client X.509
            // certificate contained in JVM keystore
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, buildUserDN(user));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
            ctx.reconnect(null);
            return true;
            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);
            return false;
        } catch (NamingException e) {
            logger.error("JNDI error:", e);
            return false;
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    } else {
        logger.debug("don't use TLS for auth");
        if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
            env.put(Context.SECURITY_AUTHENTICATION, "none");
            // TODO auf passwort testen
        } else {
            env.put(Context.SECURITY_PRINCIPAL, buildUserDN(user));
            env.put(Context.SECURITY_CREDENTIALS, password);
        }
        logger.debug("ldap environment set");

        try {
            logger.debug("start classic ldap authentication");
            logger.debug("user DN is {}", buildUserDN(user));

            if (ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST) == null) {
                logger.debug("ldap attribute to test is null");
                DirContext ctx = new InitialDirContext(env);
                ctx.close();
                return true;
            } else {
                logger.debug("ldap attribute to test is not null");
                DirContext ctx = new InitialDirContext(env);

                Attributes attrs = ctx.getAttributes(buildUserDN(user));
                Attribute la = attrs.get(ConfigCore.getParameter(Parameters.LDAP_ATTRIBUTE_TO_TEST));
                logger.debug("ldap attributes set");
                String test = (String) la.get(0);
                if (test.equals(ConfigCore.getParameter(Parameters.LDAP_VALUE_OF_ATTRIBUTE))) {
                    logger.debug("ldap ok");
                    ctx.close();
                    return true;
                } else {
                    logger.debug("ldap not ok");
                    ctx.close();
                    return false;
                }
            }
        } catch (NamingException e) {
            logger.debug("login not allowed for {}. Exception: {}", user.getLogin(), e);
            return false;
        }
    }
}

From source file:org.kitodo.services.data.LdapServerService.java

/**
 * Retrieve home directory of given user.
 *
 * @param user//from ww  w . j ava  2  s .com
 *            User object
 * @return path as URI
 */
public URI getUserHomeDirectory(User user) {

    URI userFolderBasePath = URI.create("file:///" + ConfigCore.getParameter(Parameters.DIR_USERS));

    if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_LOCAL_DIRECTORY)) {
        return userFolderBasePath.resolve(user.getLogin());
    }
    Hashtable<String, String> env = initializeWithLdapConnectionSettings(user.getLdapGroup().getLdapServer());
    if (ConfigCore.getBooleanParameter(Parameters.LDAP_USE_TLS)) {

        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            ctx.reconnect(null);

            Attributes attrs = ctx.getAttributes(buildUserDN(user));
            Attribute la = attrs.get("homeDirectory");
            return URI.create((String) la.get(0));

            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);

            return userFolderBasePath.resolve(user.getLogin());
        } catch (NamingException e) {

            logger.error("JNDI error:", e);

            return userFolderBasePath.resolve(user.getLogin());
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }
    if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx;
    URI userFolderPath = null;
    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(buildUserDN(user));
        Attribute ldapAttribute = attrs.get("homeDirectory");
        userFolderPath = URI.create((String) ldapAttribute.get(0));
        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }

    if (userFolderPath != null && !userFolderPath.isAbsolute()) {
        if (userFolderPath.getPath().startsWith("/")) {
            userFolderPath = serviceManager.getFileService().deleteFirstSlashFromPath(userFolderPath);
        }
        return userFolderBasePath.resolve(userFolderPath);
    } else {
        return userFolderPath;
    }
}

From source file:org.sonar.plugins.ldap.LdapContextFactory.java

private InitialDirContext createInitialDirContext(String principal, String credentials, boolean pooling)
        throws NamingException {
    final InitialLdapContext ctx;
    if (startTLS) {
        // Note that pooling is not enabled for such connections, because "Stop TLS" is not performed.
        Properties env = new Properties();
        env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
        env.put(Context.PROVIDER_URL, providerUrl);
        env.put(Context.REFERRAL, DEFAULT_REFERRAL);
        // At this point env should not contain properties SECURITY_AUTHENTICATION, SECURITY_PRINCIPAL and SECURITY_CREDENTIALS to avoid "bind" operation prior to StartTLS:
        ctx = new InitialLdapContext(env, null);
        // http://docs.oracle.com/javase/jndi/tutorial/ldap/ext/starttls.html
        StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
        try {//from   w ww.  ja v a 2 s.  com
            tls.negotiate();
        } catch (IOException e) {
            NamingException ex = new NamingException("StartTLS failed");
            ex.initCause(e);
            throw ex;
        }
        // Explicitly initiate "bind" operation:
        ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, authentication);
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
        ctx.reconnect(null);
    } else {
        ctx = new InitialLdapContext(getEnvironment(principal, credentials, pooling), null);
    }
    return ctx;
}