use of javax.naming.ldap.StartTlsRequest in project tomcat by apache.
the class JNDIRealm method createTlsDirContext.
/**
* Create a tls enabled LdapContext and set the StartTlsResponse tls
* instance variable.
*
* @param env
* Environment to use for context creation
* @return configured {@link LdapContext}
* @throws NamingException
* when something goes wrong while negotiating the connection
*/
private DirContext createTlsDirContext(Hashtable<String, String> env) throws NamingException {
Map<String, Object> savedEnv = new HashMap<>();
for (String key : Arrays.asList(Context.SECURITY_AUTHENTICATION, Context.SECURITY_CREDENTIALS, Context.SECURITY_PRINCIPAL, Context.SECURITY_PROTOCOL)) {
Object entry = env.remove(key);
if (entry != null) {
savedEnv.put(key, entry);
}
}
LdapContext result = null;
try {
result = new InitialLdapContext(env, null);
tls = (StartTlsResponse) result.extendedOperation(new StartTlsRequest());
if (getHostnameVerifier() != null) {
tls.setHostnameVerifier(getHostnameVerifier());
}
if (getCipherSuitesArray() != null) {
tls.setEnabledCipherSuites(getCipherSuitesArray());
}
try {
SSLSession negotiate = tls.negotiate(getSSLSocketFactory());
containerLog.debug(sm.getString("jndiRealm.negotiatedTls", negotiate.getProtocol()));
} catch (IOException e) {
throw new NamingException(e.getMessage());
}
} finally {
if (result != null) {
for (Map.Entry<String, Object> savedEntry : savedEnv.entrySet()) {
result.addToEnvironment(savedEntry.getKey(), savedEntry.getValue());
}
}
}
return result;
}
use of javax.naming.ldap.StartTlsRequest in project neo4j by neo4j.
the class LdapRealm method getLdapContextUsingStartTls.
private LdapContext getLdapContextUsingStartTls(LdapContextFactory ldapContextFactory, Object principal, Object credentials) throws NamingException {
JndiLdapContextFactory jndiLdapContextFactory = (JndiLdapContextFactory) ldapContextFactory;
Hashtable<String, Object> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, jndiLdapContextFactory.getContextFactoryClassName());
env.put(Context.PROVIDER_URL, jndiLdapContextFactory.getUrl());
LdapContext ctx = null;
try {
ctx = new InitialLdapContext(env, null);
StartTlsRequest startTlsRequest = new StartTlsRequest();
StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(startTlsRequest);
tls.negotiate();
ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, jndiLdapContextFactory.getAuthenticationMechanism());
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, principal);
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials);
ctx.reconnect(ctx.getConnectControls());
return ctx;
} catch (IOException e) {
LdapUtils.closeContext(ctx);
securityLog.error(withRealm("Failed to negotiate TLS connection with '%s': ", server(jndiLdapContextFactory), e));
throw new CommunicationException(e.getMessage());
} catch (Throwable t) {
LdapUtils.closeContext(ctx);
securityLog.error(withRealm("Unexpected failure to negotiate TLS connection with '%s': ", server(jndiLdapContextFactory), t));
throw t;
}
}
use of javax.naming.ldap.StartTlsRequest in project Openfire by igniterealtime.
the class LdapManager method getContext.
/**
* Returns a DirContext for the LDAP server that can be used to perform
* lookups and searches using the specified base DN. The context uses the
* admin login that is defined by <tt>adminDN</tt> and <tt>adminPassword</tt>.
*
* @param baseDN the base DN to use for the context.
* @return a connection to the LDAP server.
* @throws NamingException if there is an error making the LDAP connection.
*/
public LdapContext getContext(String baseDN) throws NamingException {
boolean debug = Log.isDebugEnabled();
if (debug) {
Log.debug("LdapManager: Creating a DirContext in LdapManager.getContext()...");
if (!sslEnabled && !startTlsEnabled) {
Log.debug("LdapManager: Warning: Using unencrypted connection to LDAP service!");
}
}
// Set up the environment for creating the initial context
Hashtable<String, Object> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
env.put(Context.PROVIDER_URL, getProviderURL(baseDN));
// SSL
if (sslEnabled) {
env.put("java.naming.ldap.factory.socket", "org.jivesoftware.util.SimpleSSLSocketFactory");
env.put(Context.SECURITY_PROTOCOL, "ssl");
}
// Use simple authentication to connect as the admin.
if (adminDN != null) {
/* If startTLS is requested we MUST NOT bind() before
* the secure connection has been established. */
if (!(startTlsEnabled && !sslEnabled)) {
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, adminDN);
if (adminPassword != null) {
env.put(Context.SECURITY_CREDENTIALS, adminPassword);
}
}
} else // No login information so attempt to use anonymous login.
{
env.put(Context.SECURITY_AUTHENTICATION, "none");
}
if (ldapDebugEnabled) {
env.put("com.sun.jndi.ldap.trace.ber", System.err);
}
if (connectionPoolEnabled) {
if (!startTlsEnabled) {
env.put("com.sun.jndi.ldap.connect.pool", "true");
System.setProperty("com.sun.jndi.ldap.connect.pool.protocol", "plain ssl");
} else {
if (debug) {
// See http://java.sun.com/products/jndi/tutorial/ldap/connect/pool.html
// "When Not to Use Pooling"
Log.debug("LdapManager: connection pooling was requested but has been disabled because of StartTLS.");
}
env.put("com.sun.jndi.ldap.connect.pool", "false");
}
} else {
env.put("com.sun.jndi.ldap.connect.pool", "false");
}
if (connTimeout > 0) {
env.put("com.sun.jndi.ldap.connect.timeout", String.valueOf(connTimeout));
} else {
env.put("com.sun.jndi.ldap.connect.timeout", "10000");
}
if (readTimeout > 0) {
env.put("com.sun.jndi.ldap.read.timeout", String.valueOf(readTimeout));
}
if (followReferrals) {
env.put(Context.REFERRAL, "follow");
}
if (!followAliasReferrals) {
env.put("java.naming.ldap.derefAliases", "never");
}
if (debug) {
Log.debug("LdapManager: Created hashtable with context values, attempting to create context...");
}
// Create new initial context
JiveInitialLdapContext context = new JiveInitialLdapContext(env, null);
// TLS http://www.ietf.org/rfc/rfc2830.txt ("1.3.6.1.4.1.1466.20037")
if (startTlsEnabled && !sslEnabled) {
if (debug) {
Log.debug("LdapManager: ... StartTlsRequest");
}
if (followReferrals) {
Log.warn("\tConnections to referrals are unencrypted! If you do not want this, please turn off ldap.autoFollowReferrals");
}
// Perform a StartTLS extended operation
StartTlsResponse tls = (StartTlsResponse) context.extendedOperation(new StartTlsRequest());
/* Open a TLS connection (over the existing LDAP association) and
get details of the negotiated TLS session: cipher suite,
peer certificate, etc. */
try {
SSLSession session = tls.negotiate(new org.jivesoftware.util.SimpleSSLSocketFactory());
context.setTlsResponse(tls);
context.setSslSession(session);
if (debug) {
Log.debug("LdapManager: ... peer host: " + session.getPeerHost() + ", CipherSuite: " + session.getCipherSuite());
}
/* Set login credentials only if SSL session has been
* negotiated successfully - otherwise user/password
* could be transmitted in clear text. */
if (adminDN != null) {
context.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
context.addToEnvironment(Context.SECURITY_PRINCIPAL, adminDN);
if (adminPassword != null) {
context.addToEnvironment(Context.SECURITY_CREDENTIALS, adminPassword);
}
}
} catch (java.io.IOException ex) {
Log.error(ex.getMessage(), ex);
}
}
if (debug) {
Log.debug("LdapManager: ... context created successfully, returning.");
}
return context;
}
use of javax.naming.ldap.StartTlsRequest in project Openfire by igniterealtime.
the class LdapManager method checkAuthentication.
/**
* Returns true if the user is able to successfully authenticate against
* the LDAP server. The "simple" authentication protocol is used.
*
* @param userDN the user's dn to authenticate (relative to <tt>baseDN</tt>).
* @param password the user's password.
* @return true if the user successfully authenticates.
*/
public boolean checkAuthentication(String userDN, String password) {
boolean debug = Log.isDebugEnabled();
if (debug) {
Log.debug("LdapManager: In LdapManager.checkAuthentication(userDN, password), userDN is: " + userDN + "...");
if (!sslEnabled && !startTlsEnabled) {
Log.debug("LdapManager: Warning: Using unencrypted connection to LDAP service!");
}
}
JiveInitialLdapContext ctx = null;
try {
// See if the user authenticates.
Hashtable<String, Object> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
env.put(Context.PROVIDER_URL, getProviderURL(baseDN));
if (sslEnabled) {
env.put("java.naming.ldap.factory.socket", "org.jivesoftware.util.SimpleSSLSocketFactory");
env.put(Context.SECURITY_PROTOCOL, "ssl");
}
/* If startTLS is requested we MUST NOT bind() before
* the secure connection has been established. */
if (!(startTlsEnabled && !sslEnabled)) {
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, userDN + "," + baseDN);
env.put(Context.SECURITY_CREDENTIALS, password);
} else {
if (followReferrals) {
Log.warn("\tConnections to referrals are unencrypted! If you do not want this, please turn off ldap.autoFollowReferrals");
}
}
if (connTimeout > 0) {
env.put("com.sun.jndi.ldap.connect.timeout", String.valueOf(connTimeout));
} else {
env.put("com.sun.jndi.ldap.connect.timeout", "10000");
}
if (readTimeout > 0) {
env.put("com.sun.jndi.ldap.read.timeout", String.valueOf(readTimeout));
}
if (ldapDebugEnabled) {
env.put("com.sun.jndi.ldap.trace.ber", System.err);
}
if (followReferrals) {
env.put(Context.REFERRAL, "follow");
}
if (!followAliasReferrals) {
env.put("java.naming.ldap.derefAliases", "never");
}
if (debug) {
Log.debug("LdapManager: Created context values, attempting to create context...");
}
ctx = new JiveInitialLdapContext(env, null);
if (startTlsEnabled && !sslEnabled) {
if (debug) {
Log.debug("LdapManager: ... StartTlsRequest");
}
// Perform a StartTLS extended operation
StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
/* Open a TLS connection (over the existing LDAP association) and
get details of the negotiated TLS session: cipher suite,
peer certificate, etc. */
try {
SSLSession session = tls.negotiate(new org.jivesoftware.util.SimpleSSLSocketFactory());
ctx.setTlsResponse(tls);
ctx.setSslSession(session);
if (debug) {
Log.debug("LdapManager: ... peer host: " + session.getPeerHost() + ", CipherSuite: " + session.getCipherSuite());
}
ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN + "," + baseDN);
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
} catch (java.io.IOException ex) {
Log.error(ex.getMessage(), ex);
}
// make at least one lookup to check authorization
lookupExistence(ctx, userDN + "," + baseDN, new String[] { usernameField });
}
if (debug) {
Log.debug("LdapManager: ... context created successfully, returning.");
}
} catch (NamingException ne) {
// If an alt baseDN is defined, attempt a lookup there.
if (alternateBaseDN != null) {
try {
if (ctx != null) {
ctx.close();
}
} catch (Exception e) {
Log.error(e.getMessage(), e);
}
try {
// See if the user authenticates.
Hashtable<String, Object> env = new Hashtable<>();
// Use a custom initial context factory if specified. Otherwise, use the default.
env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactory);
env.put(Context.PROVIDER_URL, getProviderURL(alternateBaseDN));
if (sslEnabled) {
env.put("java.naming.ldap.factory.socket", "org.jivesoftware.util.SimpleSSLSocketFactory");
env.put(Context.SECURITY_PROTOCOL, "ssl");
}
/* If startTLS is requested we MUST NOT bind() before
* the secure connection has been established. */
if (!(startTlsEnabled && !sslEnabled)) {
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, userDN + "," + alternateBaseDN);
env.put(Context.SECURITY_CREDENTIALS, password);
}
env.put("com.sun.jndi.ldap.connect.timeout", "10000");
if (ldapDebugEnabled) {
env.put("com.sun.jndi.ldap.trace.ber", System.err);
}
if (followReferrals) {
env.put(Context.REFERRAL, "follow");
}
if (!followAliasReferrals) {
env.put("java.naming.ldap.derefAliases", "never");
}
if (debug) {
Log.debug("LdapManager: Created context values, attempting to create context...");
}
ctx = new JiveInitialLdapContext(env, null);
if (startTlsEnabled && !sslEnabled) {
if (debug) {
Log.debug("LdapManager: ... StartTlsRequest");
}
// Perform a StartTLS extended operation
StartTlsResponse tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
/* Open a TLS connection (over the existing LDAP association) and
get details of the negotiated TLS session: cipher suite,
peer certificate, etc. */
try {
SSLSession session = tls.negotiate(new org.jivesoftware.util.SimpleSSLSocketFactory());
ctx.setTlsResponse(tls);
ctx.setSslSession(session);
if (debug) {
Log.debug("LdapManager: ... peer host: " + session.getPeerHost() + ", CipherSuite: " + session.getCipherSuite());
}
ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN + "," + alternateBaseDN);
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
} catch (java.io.IOException ex) {
Log.error(ex.getMessage(), ex);
}
// make at least one lookup to check user authorization
lookupExistence(ctx, userDN + "," + alternateBaseDN, new String[] { usernameField });
}
} catch (NamingException e) {
if (debug) {
Log.debug("LdapManager: Caught a naming exception when creating InitialContext", ne);
}
return false;
}
} else {
if (debug) {
Log.debug("LdapManager: Caught a naming exception when creating InitialContext", ne);
}
return false;
}
} finally {
try {
if (ctx != null) {
ctx.close();
}
} catch (Exception e) {
Log.error(e.getMessage(), e);
}
}
return true;
}
use of javax.naming.ldap.StartTlsRequest in project hadoop by apache.
the class LdapAuthenticationHandler method authenticateWithTlsExtension.
private void authenticateWithTlsExtension(String userDN, String password) throws AuthenticationException {
LdapContext ctx = null;
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. */
}
}
}
}
Aggregations