Search in sources :

Example 6 with LDAPConnection

use of com.unboundid.ldap.sdk.LDAPConnection in project gitblit by gitblit.

the class LdapConnection method connect.

public boolean connect() {
    try {
        URI ldapUrl = new URI(settings.getRequiredString(Keys.realm.ldap.server));
        String ldapHost = ldapUrl.getHost();
        int ldapPort = ldapUrl.getPort();
        if (ldapUrl.getScheme().equalsIgnoreCase("ldaps")) {
            // SSL
            SSLUtil sslUtil = new SSLUtil(new TrustAllTrustManager());
            conn = new LDAPConnection(sslUtil.createSSLSocketFactory());
            if (ldapPort == -1) {
                ldapPort = 636;
            }
        } else if (ldapUrl.getScheme().equalsIgnoreCase("ldap") || ldapUrl.getScheme().equalsIgnoreCase("ldap+tls")) {
            // no encryption or StartTLS
            conn = new LDAPConnection();
            if (ldapPort == -1) {
                ldapPort = 389;
            }
        } else {
            logger.error("Unsupported LDAP URL scheme: " + ldapUrl.getScheme());
            return false;
        }
        conn.connect(ldapHost, ldapPort);
        if (ldapUrl.getScheme().equalsIgnoreCase("ldap+tls")) {
            SSLUtil sslUtil = new SSLUtil(new TrustAllTrustManager());
            ExtendedResult extendedResult = conn.processExtendedOperation(new StartTLSExtendedRequest(sslUtil.createSSLContext()));
            if (extendedResult.getResultCode() != ResultCode.SUCCESS) {
                throw new LDAPException(extendedResult.getResultCode());
            }
        }
        return true;
    } catch (URISyntaxException e) {
        logger.error("Bad LDAP URL, should be in the form: ldap(s|+tls)://<server>:<port>", e);
    } catch (GeneralSecurityException e) {
        logger.error("Unable to create SSL Connection", e);
    } catch (LDAPException e) {
        logger.error("Error Connecting to LDAP", e);
    }
    return false;
}
Also used : SSLUtil(com.unboundid.util.ssl.SSLUtil) LDAPException(com.unboundid.ldap.sdk.LDAPException) GeneralSecurityException(java.security.GeneralSecurityException) ExtendedResult(com.unboundid.ldap.sdk.ExtendedResult) TrustAllTrustManager(com.unboundid.util.ssl.TrustAllTrustManager) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) StartTLSExtendedRequest(com.unboundid.ldap.sdk.extensions.StartTLSExtendedRequest)

Example 7 with LDAPConnection

use of com.unboundid.ldap.sdk.LDAPConnection in project keywhiz by square.

the class LdapAuthenticator method rolesFromDN.

private Set<String> rolesFromDN(String userDN) throws LDAPException, GeneralSecurityException {
    SearchRequest searchRequest = new SearchRequest(config.getRoleBaseDN(), SearchScope.SUB, Filter.createEqualityFilter("uniqueMember", userDN));
    Set<String> roles = Sets.newLinkedHashSet();
    LDAPConnection connection = connectionFactory.getLDAPConnection();
    try {
        SearchResult sr = connection.search(searchRequest);
        for (SearchResultEntry sre : sr.getSearchEntries()) {
            X500Name x500Name = new X500Name(sre.getDN());
            RDN[] rdns = x500Name.getRDNs(BCStyle.CN);
            if (rdns.length == 0) {
                logger.error("Could not create X500 Name for role:" + sre.getDN());
            } else {
                String commonName = IETFUtils.valueToString(rdns[0].getFirst().getValue());
                roles.add(commonName);
            }
        }
    } finally {
        connection.close();
    }
    return roles;
}
Also used : SearchRequest(com.unboundid.ldap.sdk.SearchRequest) SearchResult(com.unboundid.ldap.sdk.SearchResult) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection) X500Name(org.bouncycastle.asn1.x500.X500Name) RDN(org.bouncycastle.asn1.x500.RDN) SearchResultEntry(com.unboundid.ldap.sdk.SearchResultEntry)

Example 8 with LDAPConnection

use of com.unboundid.ldap.sdk.LDAPConnection in project keywhiz by square.

the class LdapAuthenticator method authenticate.

@Override
public Optional<User> authenticate(BasicCredentials credentials) {
    User user = null;
    try {
        String username = credentials.getUsername();
        if (!User.isSanitizedUsername(username)) {
            logger.info("Username: {} must match pattern: {}", username, User.USERNAME_PATTERN);
            return Optional.empty();
        }
        String userDN = dnFromUsername(username);
        String password = credentials.getPassword();
        // Must have password for current config
        if (Strings.isNullOrEmpty(password)) {
            logger.info("No password for user provided");
            return Optional.empty();
        }
        LDAPConnection authenticatedConnection = connectionFactory.getLDAPConnection(userDN, password);
        authenticatedConnection.close();
        Set<String> requiredRoles = config.getRequiredRoles();
        if (!requiredRoles.isEmpty()) {
            Set<String> roles = rolesFromDN(userDN);
            boolean accessAllowed = false;
            for (String requiredRole : requiredRoles) {
                if (roles.contains(requiredRole)) {
                    accessAllowed = true;
                }
            }
            if (!accessAllowed) {
                logger.warn("User {} not in one of required LDAP roles: [{}].", username, requiredRoles);
                throw new ForbiddenException();
            }
        }
        user = User.named(username);
    } catch (LDAPException le) {
        // The INVALID_CREDENTIALS case is handled by returning an absent optional from this function
        if (le.getResultCode() != ResultCode.INVALID_CREDENTIALS) {
            logger.error("Error connecting to LDAP", le);
            throw Throwables.propagate(le);
        }
    } catch (GeneralSecurityException gse) {
        logger.error("TLS error connecting to LDAP", gse);
        throw Throwables.propagate(gse);
    }
    return Optional.ofNullable(user);
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) User(keywhiz.auth.User) LDAPException(com.unboundid.ldap.sdk.LDAPException) GeneralSecurityException(java.security.GeneralSecurityException) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection)

Example 9 with LDAPConnection

use of com.unboundid.ldap.sdk.LDAPConnection in project keywhiz by square.

the class LdapConnectionFactory method getLDAPConnection.

public LDAPConnection getLDAPConnection(String userDN, String password) throws LDAPException, GeneralSecurityException {
    TrustStoreTrustManager trust = new TrustStoreTrustManager(trustStorePath, trustStorePassword.toCharArray(), trustStoreType, false);
    LDAPConnectionOptions options = new LDAPConnectionOptions();
    options.setSSLSocketVerifier(new HostNameSSLSocketVerifier(false));
    SSLUtil sslUtil = new SSLUtil(trust);
    SocketFactory factory = new EndpointIdentificationSocketFactory(sslUtil.createSSLSocketFactory("TLSv1.2"));
    LDAPConnection ldapConnection = new LDAPConnection(factory, options);
    // Connect, retrieve the DN of the user (if any)
    ldapConnection.connect(server, port);
    ldapConnection.bind(userDN, password);
    return ldapConnection;
}
Also used : LDAPConnectionOptions(com.unboundid.ldap.sdk.LDAPConnectionOptions) SSLUtil(com.unboundid.util.ssl.SSLUtil) HostNameSSLSocketVerifier(com.unboundid.util.ssl.HostNameSSLSocketVerifier) TrustStoreTrustManager(com.unboundid.util.ssl.TrustStoreTrustManager) SocketFactory(javax.net.SocketFactory) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection)

Example 10 with LDAPConnection

use of com.unboundid.ldap.sdk.LDAPConnection in project oxTrust by GluuFederation.

the class LdifService method importLdifFileInLdap.

public ResultCode importLdifFileInLdap(InputStream is) throws LDAPException {
    ResultCode result = ResultCode.UNAVAILABLE;
    LDAPConnection connection = ldapEntryManager.getLdapOperationService().getConnection();
    try {
        LdifDataUtility ldifDataUtility = LdifDataUtility.instance();
        LDIFReader importLdifReader = new LDIFReader(is);
        result = ldifDataUtility.importLdifFile(connection, importLdifReader);
        importLdifReader.close();
    } catch (Exception ex) {
        log.error("Failed to import ldif file: ", ex);
    } finally {
        ldapEntryManager.getLdapOperationService().releaseConnection(connection);
    }
    return result;
}
Also used : LDIFReader(com.unboundid.ldif.LDIFReader) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection) LdifDataUtility(org.gluu.site.ldap.persistence.LdifDataUtility) ResultCode(com.unboundid.ldap.sdk.ResultCode) IOException(java.io.IOException) LdapMappingException(org.gluu.site.ldap.persistence.exception.LdapMappingException) LDAPException(com.unboundid.ldap.sdk.LDAPException)

Aggregations

LDAPConnection (com.unboundid.ldap.sdk.LDAPConnection)11 LDAPException (com.unboundid.ldap.sdk.LDAPException)7 IOException (java.io.IOException)3 ExtendedResult (com.unboundid.ldap.sdk.ExtendedResult)2 SearchRequest (com.unboundid.ldap.sdk.SearchRequest)2 SearchResult (com.unboundid.ldap.sdk.SearchResult)2 SearchResultEntry (com.unboundid.ldap.sdk.SearchResultEntry)2 StartTLSExtendedRequest (com.unboundid.ldap.sdk.extensions.StartTLSExtendedRequest)2 SSLUtil (com.unboundid.util.ssl.SSLUtil)2 GeneralSecurityException (java.security.GeneralSecurityException)2 LdifDataUtility (org.gluu.site.ldap.persistence.LdifDataUtility)2 LdapMappingException (org.gluu.site.ldap.persistence.exception.LdapMappingException)2 BindResult (com.unboundid.ldap.sdk.BindResult)1 LDAPConnectionOptions (com.unboundid.ldap.sdk.LDAPConnectionOptions)1 ResultCode (com.unboundid.ldap.sdk.ResultCode)1 LDIFReader (com.unboundid.ldif.LDIFReader)1 LDIFWriter (com.unboundid.ldif.LDIFWriter)1 HostNameSSLSocketVerifier (com.unboundid.util.ssl.HostNameSSLSocketVerifier)1 TrustAllTrustManager (com.unboundid.util.ssl.TrustAllTrustManager)1 TrustStoreTrustManager (com.unboundid.util.ssl.TrustStoreTrustManager)1