javax.naming.ldap.StartTlsRequest Java Examples

The following examples show how to use javax.naming.ldap.StartTlsRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LdapContextWrapper.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize the LDAP context with secured connection by applying StartTLS extended operation.
 *
 * @param environment        environment used to create the initial Context.
 * @param connectionControls connection request controls for the initial context.
 * @return secured ldap connection context.
 * @throws NamingException    if a naming exception is encountered.
 * @throws UserStoreException if a user store related exception is encountered.
 */
public static LdapContext startTLS(Hashtable<?, ?> environment, Control[] connectionControls)
        throws NamingException, UserStoreException {

    Hashtable<String, Object> tempEnv = getEnvironmentForSecuredLdapInitialization(environment);
    LdapContext ldapContext = new InitialLdapContext(tempEnv, connectionControls);
    try {
        StartTlsResponse startTlsResponse = (StartTlsResponse) ldapContext.extendedOperation(new StartTlsRequest());
        startTlsResponse.negotiate();
        if (log.isDebugEnabled()) {
            log.debug("StartTLS connection established successfully with LDAP server");
        }
        LdapContextWrapper ldapContextWrapper = new LdapContextWrapper(ldapContext, startTlsResponse);
        ldapContextWrapper.performAuthenticationIfProvided(environment);
        return ldapContextWrapper;
    } catch (IOException e) {
        throw new UserStoreException("Unable to establish the StartTLS connection", e);
    }
}
 
Example #2
Source File: LdapUserGroupBuilder.java    From ranger with Apache License 2.0 5 votes vote down vote up
private void createLdapContext() throws Throwable {
	Properties env = new Properties();
	env.put(Context.INITIAL_CONTEXT_FACTORY,
			"com.sun.jndi.ldap.LdapCtxFactory");
	env.put(Context.PROVIDER_URL, ldapUrl);
	if (ldapUrl.startsWith("ldaps") && (config.getSSLTrustStorePath() != null && !config.getSSLTrustStorePath().trim().isEmpty())) {
		env.put("java.naming.ldap.factory.socket", "org.apache.ranger.ldapusersync.process.CustomSSLSocketFactory");
	}

	ldapContext = new InitialLdapContext(env, null);
	if (!ldapUrl.startsWith("ldaps")) {
		if (config.isStartTlsEnabled()) {
			tls = (StartTlsResponse) ldapContext.extendedOperation(new StartTlsRequest());
			if (config.getSSLTrustStorePath() != null && !config.getSSLTrustStorePath().trim().isEmpty()) {
				tls.negotiate(CustomSSLSocketFactory.getDefault());
			} else {
				tls.negotiate();
			}
			LOG.info("Starting TLS session...");
		}
	}

	ldapContext.addToEnvironment(Context.SECURITY_PRINCIPAL, ldapBindDn);
	ldapContext.addToEnvironment(Context.SECURITY_CREDENTIALS, ldapBindPassword);
	ldapContext.addToEnvironment(Context.SECURITY_AUTHENTICATION, ldapAuthenticationMechanism);
	ldapContext.addToEnvironment(Context.REFERRAL, ldapReferral);
}
 
Example #3
Source File: LdapUserDAO.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected InitialLdapContext getDirContext() throws NamingException, CommunicationException, ConnectException {
    InitialLdapContext dirCtx = null;
    try {
        if (this.isTlsSecurityConnection()) {
            dirCtx = new InitialLdapContext(this.getParams(true), null);
            StartTlsResponse tls = (StartTlsResponse) dirCtx.extendedOperation(new StartTlsRequest());
            if (this.isTlsFreeSecurityConnection()) {
                // Set the (our) HostVerifier
                tls.setHostnameVerifier(new MyTLSHostnameVerifier());
                SSLSocketFactory sslsf = null;
                try {
                    TrustManager[] tm = new TrustManager[]{new MyX509TrustManager()};
                    SSLContext sslC = SSLContext.getInstance("TLSv1.2");
                    sslC.init(null, tm, null);
                    sslsf = sslC.getSocketFactory();
                } catch (NoSuchAlgorithmException nSAE) {
                    logger.error("error Hier: {}", nSAE.getMessage(), nSAE);
                } catch (KeyManagementException kME) {
                    logger.error("error Hier: {}", kME.getMessage(), kME);
                }
                tls.negotiate(sslsf);
            } else {
                tls.negotiate();
            }
            if (null != this.getSecurityPrincipal() && null != this.getSecurityCredentials()) {
                dirCtx.addToEnvironment(Context.SECURITY_PRINCIPAL, this.getSecurityPrincipal());
                dirCtx.addToEnvironment(Context.SECURITY_CREDENTIALS, this.getSecurityCredentials());
                dirCtx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            }
        } else {
            dirCtx = new InitialLdapContext(this.getParams(false), null);
        }
    } catch (IOException ex) {
        logger.error("error in getDirContext", ex);
    } catch (NamingException e) {
        throw e;
    }
    return dirCtx;
}
 
Example #4
Source File: AbstractTlsDirContextAuthenticationStrategy.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
public final DirContext processContextAfterCreation(DirContext ctx, String userDn, String password)
		throws NamingException {

	if (ctx instanceof LdapContext) {
		final LdapContext ldapCtx = (LdapContext) ctx;
		final StartTlsResponse tlsResponse = (StartTlsResponse) ldapCtx.extendedOperation(new StartTlsRequest());
		try {
			if (hostnameVerifier != null) {
				tlsResponse.setHostnameVerifier(hostnameVerifier);
			}
			tlsResponse.negotiate(sslSocketFactory); // If null, the default SSL socket factory is used
			applyAuthentication(ldapCtx, userDn, password);

			if (shutdownTlsGracefully) {
				// Wrap the target context in a proxy to intercept any calls
				// to 'close', so that we can shut down the TLS connection
				// gracefully first.
				return (DirContext) Proxy.newProxyInstance(DirContextProxy.class.getClassLoader(), new Class<?>[] {
						LdapContext.class, DirContextProxy.class }, new TlsAwareDirContextProxy(ldapCtx,
						tlsResponse));
			}
			else {
				return ctx;
			}
		}
		catch (IOException e) {
			LdapUtils.closeContext(ctx);
			throw new UncategorizedLdapException("Failed to negotiate TLS session", e);
		}
	}
	else {
		throw new IllegalArgumentException(
				"Processed Context must be an LDAPv3 context, i.e. an LdapContext implementation");
	}

}
 
Example #5
Source File: LdapTlsProtocolIT.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws NamingException {
  mockLogChannelInterface = mock( LogChannelInterface.class );
  mockVariableSpace = mock( VariableSpace.class );
  mockLdapMeta = mock( LdapMeta.class );
  mockInitialLdapContext = mock( InitialLdapContext.class );
  mockStartTlsResponse = mock( StartTlsResponse.class );
  when( mockInitialLdapContext.extendedOperation( any( StartTlsRequest.class ) ) ).thenReturn(
    mockStartTlsResponse );
}