Search in sources :

Example 1 with LdapConnection

use of org.apache.directory.ldap.client.api.LdapConnection in project jackrabbit-oak by apache.

the class LdapIdentityProvider method getIdentity.

@Override
public ExternalIdentity getIdentity(@Nonnull ExternalIdentityRef ref) throws ExternalIdentityException {
    if (!isMyRef(ref)) {
        return null;
    }
    LdapConnection connection = connect();
    try {
        String userIdAttr = config.getUserConfig().getIdAttribute();
        String groupIdAttr = config.getGroupConfig().getIdAttribute();
        String[] ca = config.getCustomAttributes();
        Entry entry;
        if (ca.length == 0) {
            entry = connection.lookup(ref.getId(), SchemaConstants.ALL_USER_ATTRIBUTES);
        } else {
            List<String> attributes = new ArrayList<>(Arrays.asList(ca));
            attributes.add("objectClass");
            attributes.add(userIdAttr);
            attributes.add(groupIdAttr);
            String[] attributeArray = new String[attributes.size()];
            attributes.toArray(attributeArray);
            entry = connection.lookup(ref.getId(), attributeArray);
        }
        if (entry == null) {
            return null;
        } else if (entry.hasObjectClass(config.getUserConfig().getObjectClasses())) {
            return createUser(entry, null);
        } else if (entry.hasObjectClass(config.getGroupConfig().getObjectClasses())) {
            return createGroup(entry, null);
        } else {
            log.warn("referenced identity is neither user or group: {}", ref.getString());
            return null;
        }
    } catch (LdapException e) {
        throw lookupFailedException(e, null);
    } finally {
        disconnect(connection);
    }
}
Also used : Entry(org.apache.directory.api.ldap.model.entry.Entry) SearchResultEntry(org.apache.directory.api.ldap.model.message.SearchResultEntry) ArrayList(java.util.ArrayList) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) LdapConnection(org.apache.directory.ldap.client.api.LdapConnection)

Example 2 with LdapConnection

use of org.apache.directory.ldap.client.api.LdapConnection in project jackrabbit-oak by apache.

the class LdapIdentityProvider method authenticate.

@Override
public ExternalUser authenticate(@Nonnull Credentials credentials) throws ExternalIdentityException, LoginException {
    if (!(credentials instanceof SimpleCredentials)) {
        log.debug("LDAP IDP can only authenticate SimpleCredentials.");
        return null;
    }
    final SimpleCredentials creds = (SimpleCredentials) credentials;
    final ExternalUser user = getUser(creds.getUserID());
    if (user != null) {
        // see http://tools.ietf.org/html/rfc4513#section-5.1.1 for details.
        if (creds.getPassword().length == 0) {
            throw new LoginException("Refusing to authenticate against LDAP server: Empty passwords not allowed.");
        }
        // authenticate
        LdapConnection connection = null;
        try {
            DebugTimer timer = new DebugTimer();
            if (userPool == null) {
                connection = userConnectionFactory.makeObject();
            } else {
                connection = userPool.getConnection();
            }
            timer.mark("connect");
            connection.bind(user.getExternalId().getId(), new String(creds.getPassword()));
            timer.mark("bind");
            if (log.isDebugEnabled()) {
                log.debug("authenticate({}) {}", user.getId(), timer.getString());
            }
        } catch (LdapAuthenticationException e) {
            throw new LoginException("Unable to authenticate against LDAP server: " + e.getMessage());
        } catch (Exception e) {
            throw new ExternalIdentityException("Error while binding user credentials", e);
        } finally {
            if (connection != null) {
                try {
                    if (userPool == null) {
                        userConnectionFactory.destroyObject(connection);
                    } else {
                        userPool.releaseConnection(connection);
                    }
                } catch (Exception e) {
                // ignore
                }
            }
        }
    }
    return user;
}
Also used : DebugTimer(org.apache.jackrabbit.oak.commons.DebugTimer) SimpleCredentials(javax.jcr.SimpleCredentials) LdapAuthenticationException(org.apache.directory.api.ldap.model.exception.LdapAuthenticationException) ExternalUser(org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalUser) LoginException(javax.security.auth.login.LoginException) ExternalIdentityException(org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityException) LoginException(javax.security.auth.login.LoginException) LdapInvalidAttributeValueException(org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException) LdapAuthenticationException(org.apache.directory.api.ldap.model.exception.LdapAuthenticationException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) ExternalIdentityException(org.apache.jackrabbit.oak.spi.security.authentication.external.ExternalIdentityException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) LdapConnection(org.apache.directory.ldap.client.api.LdapConnection)

Example 3 with LdapConnection

use of org.apache.directory.ldap.client.api.LdapConnection in project karaf by apache.

the class LdapSpecialCharsInPasswordTest method changeAdminPassword.

@Before
public void changeAdminPassword() throws Exception {
    LdapConnection connection = new LdapNetworkConnection("localhost", getLdapServer().getPort());
    connection.bind("uid=admin,ou=system", "secret");
    Dn adminDn = new Dn("uid=admin,ou=system");
    ModifyRequest modReq = new ModifyRequestImpl();
    modReq.setName(adminDn);
    modReq.replace(SchemaConstants.USER_PASSWORD_AT, NEW_CONNECTION_PASSWORD);
    connection.modify(modReq);
    connection.close();
    // check that we actually changed the admin connection password
    connection = new LdapNetworkConnection("localhost", getLdapServer().getPort());
    connection.bind("uid=admin,ou=system", NEW_CONNECTION_PASSWORD);
    connection.close();
}
Also used : ModifyRequestImpl(org.apache.directory.api.ldap.model.message.ModifyRequestImpl) Dn(org.apache.directory.api.ldap.model.name.Dn) LdapNetworkConnection(org.apache.directory.ldap.client.api.LdapNetworkConnection) ModifyRequest(org.apache.directory.api.ldap.model.message.ModifyRequest) LdapConnection(org.apache.directory.ldap.client.api.LdapConnection) Before(org.junit.Before)

Example 4 with LdapConnection

use of org.apache.directory.ldap.client.api.LdapConnection in project mxisd by kamax-io.

the class LdapAuthProvider method authenticate.

@Override
public BackendAuthResult authenticate(_MatrixID mxid, String password) {
    log.info("Performing auth for {}", mxid);
    try (LdapConnection conn = getConn()) {
        bind(conn);
        String uidType = getAt().getUid().getType();
        String userFilterValue = StringUtils.equals(LdapBackend.UID, uidType) ? mxid.getLocalPart() : mxid.getId();
        if (StringUtils.isBlank(userFilterValue)) {
            log.warn("Username is empty, failing auth");
            return BackendAuthResult.failure();
        }
        String userFilter = "(" + getUidAtt() + "=" + userFilterValue + ")";
        userFilter = buildWithFilter(userFilter, getCfg().getAuth().getFilter());
        Set<String> attributes = new HashSet<>();
        attributes.add(getUidAtt());
        attributes.add(getAt().getName());
        getAt().getThreepid().forEach((k, v) -> attributes.addAll(v));
        String[] attArray = new String[attributes.size()];
        attributes.toArray(attArray);
        log.debug("Base DN: {}", getBaseDn());
        log.debug("Query: {}", userFilter);
        log.debug("Attributes: {}", GsonUtil.build().toJson(attArray));
        try (EntryCursor cursor = conn.search(getBaseDn(), userFilter, SearchScope.SUBTREE, attArray)) {
            while (cursor.next()) {
                Entry entry = cursor.get();
                String dn = entry.getDn().getName();
                log.info("Checking possible match, DN: {}", dn);
                if (!getAttribute(entry, getUidAtt()).isPresent()) {
                    continue;
                }
                log.info("Attempting authentication on LDAP for {}", dn);
                try {
                    conn.bind(entry.getDn(), password);
                } catch (LdapException e) {
                    log.info("Unable to bind using {} because {}", entry.getDn().getName(), e.getMessage());
                    return BackendAuthResult.failure();
                }
                Attribute nameAttribute = entry.get(getAt().getName());
                String name = nameAttribute != null ? nameAttribute.get().toString() : null;
                log.info("Authentication successful for {}", entry.getDn().getName());
                log.info("DN {} is a valid match", dn);
                // TODO should we canonicalize the MXID?
                BackendAuthResult result = BackendAuthResult.success(mxid.getId(), UserIdType.MatrixID, name);
                log.info("Processing 3PIDs for profile");
                getAt().getThreepid().forEach((k, v) -> {
                    log.info("Processing 3PID type {}", k);
                    v.forEach(attId -> {
                        List<String> values = getAttributes(entry, attId);
                        log.info("\tAttribute {} has {} value(s)", attId, values.size());
                        getAttributes(entry, attId).forEach(tpidValue -> {
                            if (ThreePidMedium.PhoneNumber.is(k)) {
                                tpidValue = getMsisdn(tpidValue).orElse(tpidValue);
                            }
                            result.withThreePid(new ThreePid(k, tpidValue));
                        });
                    });
                });
                log.info("Found {} 3PIDs", result.getProfile().getThreePids().size());
                return result;
            }
        } catch (CursorLdapReferralException e) {
            log.warn("Entity for {} is only available via referral, skipping", mxid);
        }
        log.info("No match were found for {}", mxid);
        return BackendAuthResult.failure();
    } catch (LdapException | IOException | CursorException e) {
        throw new RuntimeException(e);
    }
}
Also used : EntryCursor(org.apache.directory.api.ldap.model.cursor.EntryCursor) Attribute(org.apache.directory.api.ldap.model.entry.Attribute) IOException(java.io.IOException) BackendAuthResult(io.kamax.mxisd.auth.provider.BackendAuthResult) Entry(org.apache.directory.api.ldap.model.entry.Entry) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) CursorLdapReferralException(org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException) ThreePid(io.kamax.matrix.ThreePid) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) LdapConnection(org.apache.directory.ldap.client.api.LdapConnection) HashSet(java.util.HashSet)

Example 5 with LdapConnection

use of org.apache.directory.ldap.client.api.LdapConnection in project mxisd by kamax-io.

the class LdapDirectoryProvider method search.

protected UserDirectorySearchResult search(String query, List<String> attributes) {
    UserDirectorySearchResult result = new UserDirectorySearchResult();
    result.setLimited(false);
    try (LdapConnection conn = getConn()) {
        bind(conn);
        LdapConfig.Attribute atCfg = getCfg().getAttribute();
        attributes = new ArrayList<>(attributes);
        attributes.add(getUidAtt());
        String[] attArray = new String[attributes.size()];
        attributes.toArray(attArray);
        String searchQuery = buildOrQueryWithFilter(getCfg().getDirectory().getFilter(), "*" + query + "*", attArray);
        log.debug("Base DN: {}", getBaseDn());
        log.debug("Query: {}", searchQuery);
        log.debug("Attributes: {}", GsonUtil.build().toJson(attArray));
        try (EntryCursor cursor = conn.search(getBaseDn(), searchQuery, SearchScope.SUBTREE, attArray)) {
            while (cursor.next()) {
                Entry entry = cursor.get();
                log.info("Found possible match, DN: {}", entry.getDn().getName());
                getAttribute(entry, getUidAtt()).ifPresent(uid -> {
                    log.info("DN {} is a valid match", entry.getDn().getName());
                    try {
                        UserDirectorySearchResult.Result entryResult = new UserDirectorySearchResult.Result();
                        entryResult.setUserId(buildMatrixIdFromUid(uid));
                        getAttribute(entry, atCfg.getName()).ifPresent(entryResult::setDisplayName);
                        result.addResult(entryResult);
                    } catch (IllegalArgumentException e) {
                        log.warn("Bind was found but type {} is not supported", atCfg.getUid().getType());
                    }
                });
            }
        }
    } catch (CursorLdapReferralException e) {
        log.warn("An entry is only available via referral, skipping");
    } catch (IOException | LdapException | CursorException e) {
        throw new InternalServerError(e);
    }
    return result;
}
Also used : EntryCursor(org.apache.directory.api.ldap.model.cursor.EntryCursor) IOException(java.io.IOException) InternalServerError(io.kamax.mxisd.exception.InternalServerError) UserDirectorySearchResult(io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchResult) LdapConfig(io.kamax.mxisd.config.ldap.LdapConfig) Entry(org.apache.directory.api.ldap.model.entry.Entry) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) CursorLdapReferralException(org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) UserDirectorySearchResult(io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchResult) LdapConnection(org.apache.directory.ldap.client.api.LdapConnection)

Aggregations

LdapConnection (org.apache.directory.ldap.client.api.LdapConnection)178 LdapException (org.apache.directory.api.ldap.model.exception.LdapException)164 ArrayList (java.util.ArrayList)89 FinderException (org.apache.directory.fortress.core.FinderException)73 CursorException (org.apache.directory.api.ldap.model.cursor.CursorException)63 Entry (org.apache.directory.api.ldap.model.entry.Entry)50 SearchCursor (org.apache.directory.api.ldap.model.cursor.SearchCursor)49 Modification (org.apache.directory.api.ldap.model.entry.Modification)43 DefaultModification (org.apache.directory.api.ldap.model.entry.DefaultModification)41 UpdateException (org.apache.directory.fortress.core.UpdateException)41 DefaultEntry (org.apache.directory.api.ldap.model.entry.DefaultEntry)37 LdapNoSuchObjectException (org.apache.directory.api.ldap.model.exception.LdapNoSuchObjectException)20 CreateException (org.apache.directory.fortress.core.CreateException)17 RemoveException (org.apache.directory.fortress.core.RemoveException)17 LdapNetworkConnection (org.apache.directory.ldap.client.api.LdapNetworkConnection)14 IOException (java.io.IOException)12 Permission (org.apache.directory.fortress.core.model.Permission)9 Dn (org.apache.directory.api.ldap.model.name.Dn)7 LdapInvalidAttributeValueException (org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException)6 SecurityException (org.apache.directory.fortress.core.SecurityException)6