Search in sources :

Example 1 with CursorLdapReferralException

use of org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException 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 2 with CursorLdapReferralException

use of org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException 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)

Example 3 with CursorLdapReferralException

use of org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException in project openmeetings by apache.

the class LdapLoginManager method login.

/**
 * Ldap Login
 *
 * Connection Data is retrieved from ConfigurationFile
 *
 * @param _login - user login
 * @param passwd - user password
 * @param domainId - user domain id
 * @return - {@link User} with this credentials or <code>null</code>
 * @throws OmException - in case of any error
 */
public User login(String _login, String passwd, Long domainId) throws OmException {
    log.debug("LdapLoginmanager.doLdapLogin");
    if (!userDao.validLogin(_login)) {
        log.error("Invalid login provided");
        return null;
    }
    User u = null;
    try (LdapWorker w = new LdapWorker(domainId)) {
        String login = w.options.useLowerCase ? _login.toLowerCase() : _login;
        boolean authenticated = true;
        Dn userDn = null;
        Entry entry = null;
        switch(w.options.type) {
            case SEARCHANDBIND:
                {
                    bindAdmin(w.conn, w.options);
                    Dn baseDn = new Dn(w.options.searchBase);
                    String searchQ = String.format(w.options.searchQuery, login);
                    try (EntryCursor cursor = new EntryCursorImpl(w.conn.search(new SearchRequestImpl().setBase(baseDn).setFilter(searchQ).setScope(w.options.scope).addAttributes("*").setDerefAliases(w.options.derefMode)))) {
                        while (cursor.next()) {
                            try {
                                Entry e = cursor.get();
                                if (userDn != null) {
                                    log.error("more than 1 user found in LDAP");
                                    throw UNKNOWN;
                                }
                                userDn = e.getDn();
                                if (w.options.useAdminForAttrs) {
                                    entry = e;
                                }
                            } catch (CursorLdapReferralException cle) {
                                log.warn("Referral LDAP entry found, ignore it");
                            }
                        }
                    }
                    if (userDn == null) {
                        log.error("NONE users found in LDAP");
                        throw BAD_CREDENTIALS;
                    }
                    w.conn.bind(userDn, passwd);
                }
                break;
            case SIMPLEBIND:
                userDn = new Dn(String.format(w.options.userDn, login));
                w.conn.bind(userDn, passwd);
                break;
            case NONE:
            default:
                authenticated = false;
                break;
        }
        u = authenticated ? userDao.getByLogin(login, Type.ldap, domainId) : userDao.login(login, passwd);
        log.debug("getByLogin:: authenticated ? {}, login = '{}', domain = {}, user = {}", authenticated, login, domainId, u);
        if (u == null && Provisionning.AUTOCREATE != w.options.prov) {
            log.error("User not found in OM DB and Provisionning.AUTOCREATE was not set");
            throw BAD_CREDENTIALS;
        }
        if (authenticated && entry == null) {
            if (w.options.useAdminForAttrs) {
                bindAdmin(w.conn, w.options);
            }
            entry = w.conn.lookup(userDn);
        }
        switch(w.options.prov) {
            case AUTOUPDATE:
            case AUTOCREATE:
                u = w.getUser(entry, u);
                if (w.options.syncPasswd) {
                    u.updatePassword(cfgDao, passwd);
                }
                u = userDao.update(u, null);
                break;
            case NONE:
            default:
                break;
        }
    } catch (LdapAuthenticationException ae) {
        log.error("Not authenticated.", ae);
        throw BAD_CREDENTIALS;
    } catch (OmException e) {
        throw e;
    } catch (Exception e) {
        log.error("Unexpected exception.", e);
        throw new OmException(e);
    }
    return u;
}
Also used : EntryCursor(org.apache.directory.api.ldap.model.cursor.EntryCursor) EntryCursorImpl(org.apache.directory.ldap.client.api.EntryCursorImpl) User(org.apache.openmeetings.db.entity.user.User) GroupUser(org.apache.openmeetings.db.entity.user.GroupUser) SearchRequestImpl(org.apache.directory.api.ldap.model.message.SearchRequestImpl) Dn(org.apache.directory.api.ldap.model.name.Dn) OmException(org.apache.openmeetings.util.OmException) LdapInvalidAttributeValueException(org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException) CursorLdapReferralException(org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException) LdapAuthenticationException(org.apache.directory.api.ldap.model.exception.LdapAuthenticationException) OmException(org.apache.openmeetings.util.OmException) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) IOException(java.io.IOException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) Entry(org.apache.directory.api.ldap.model.entry.Entry) LdapAuthenticationException(org.apache.directory.api.ldap.model.exception.LdapAuthenticationException) CursorLdapReferralException(org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException)

Example 4 with CursorLdapReferralException

use of org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException in project mxisd by kamax-io.

the class LdapThreePidProvider method lookup.

private Optional<String> lookup(LdapConnection conn, String medium, String value) {
    Optional<String> tPidQueryOpt = getCfg().getIdentity().getQuery(medium);
    if (!tPidQueryOpt.isPresent()) {
        log.warn("{} is not a configured 3PID type for LDAP lookup", medium);
        return Optional.empty();
    }
    // we merge 3PID specific query with global/specific filter, if one exists.
    String tPidQuery = tPidQueryOpt.get().replaceAll(getCfg().getIdentity().getToken(), value);
    String searchQuery = buildWithFilter(tPidQuery, getCfg().getIdentity().getFilter());
    log.debug("Base DN: {}", getBaseDn());
    log.debug("Query: {}", searchQuery);
    log.debug("Attributes: {}", GsonUtil.build().toJson(getUidAtt()));
    try (EntryCursor cursor = conn.search(getBaseDn(), searchQuery, SearchScope.SUBTREE, getUidAtt())) {
        while (cursor.next()) {
            Entry entry = cursor.get();
            log.info("Found possible match, DN: {}", entry.getDn().getName());
            Optional<String> data = getAttribute(entry, getUidAtt());
            if (!data.isPresent()) {
                continue;
            }
            log.info("DN {} is a valid match", entry.getDn().getName());
            return Optional.of(buildMatrixIdFromUid(data.get()));
        }
    } catch (CursorLdapReferralException e) {
        log.warn("3PID {} is only available via referral, skipping", value);
    } catch (IOException | LdapException | CursorException e) {
        throw new InternalServerError(e);
    }
    return Optional.empty();
}
Also used : EntryCursor(org.apache.directory.api.ldap.model.cursor.EntryCursor) 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) IOException(java.io.IOException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) InternalServerError(io.kamax.mxisd.exception.InternalServerError)

Example 5 with CursorLdapReferralException

use of org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException in project openmeetings by apache.

the class LdapLoginManager method importUsers.

public void importUsers(Long domainId, boolean print) throws OmException {
    try (LdapWorker w = new LdapWorker(domainId)) {
        bindAdmin(w.conn, w.options);
        Dn baseDn = new Dn(w.options.searchBase);
        try (EntryCursor cursor = new EntryCursorImpl(w.conn.search(new SearchRequestImpl().setBase(baseDn).setFilter(w.options.importQuery).setScope(w.options.scope).addAttributes("*").setDerefAliases(w.options.derefMode)))) {
            while (cursor.next()) {
                try {
                    Entry e = cursor.get();
                    User u = userDao.getByLogin(getLogin(w.config, e), Type.ldap, domainId);
                    u = w.getUser(e, u);
                    if (print) {
                        log.info("Going to import user: {}", u);
                    } else {
                        userDao.update(u, null);
                        log.info("User {}, was imported", u);
                    }
                } catch (CursorLdapReferralException cle) {
                    log.warn("Referral LDAP entry found, ignore it");
                }
            }
        }
    } catch (LdapAuthenticationException ae) {
        log.error("Not authenticated.", ae);
        throw BAD_CREDENTIALS;
    } catch (OmException e) {
        throw e;
    } catch (Exception e) {
        log.error("Unexpected exception.", e);
        throw new OmException(e);
    }
}
Also used : EntryCursor(org.apache.directory.api.ldap.model.cursor.EntryCursor) EntryCursorImpl(org.apache.directory.ldap.client.api.EntryCursorImpl) Entry(org.apache.directory.api.ldap.model.entry.Entry) User(org.apache.openmeetings.db.entity.user.User) GroupUser(org.apache.openmeetings.db.entity.user.GroupUser) LdapAuthenticationException(org.apache.directory.api.ldap.model.exception.LdapAuthenticationException) CursorLdapReferralException(org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException) SearchRequestImpl(org.apache.directory.api.ldap.model.message.SearchRequestImpl) Dn(org.apache.directory.api.ldap.model.name.Dn) OmException(org.apache.openmeetings.util.OmException) LdapInvalidAttributeValueException(org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException) CursorLdapReferralException(org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException) LdapAuthenticationException(org.apache.directory.api.ldap.model.exception.LdapAuthenticationException) OmException(org.apache.openmeetings.util.OmException) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) IOException(java.io.IOException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException)

Aggregations

IOException (java.io.IOException)6 CursorLdapReferralException (org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException)6 Entry (org.apache.directory.api.ldap.model.entry.Entry)6 CursorException (org.apache.directory.api.ldap.model.cursor.CursorException)5 EntryCursor (org.apache.directory.api.ldap.model.cursor.EntryCursor)5 LdapException (org.apache.directory.api.ldap.model.exception.LdapException)5 Dn (org.apache.directory.api.ldap.model.name.Dn)3 InternalServerError (io.kamax.mxisd.exception.InternalServerError)2 LdapAuthenticationException (org.apache.directory.api.ldap.model.exception.LdapAuthenticationException)2 LdapInvalidAttributeValueException (org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException)2 SearchRequestImpl (org.apache.directory.api.ldap.model.message.SearchRequestImpl)2 EntryCursorImpl (org.apache.directory.ldap.client.api.EntryCursorImpl)2 LdapConnection (org.apache.directory.ldap.client.api.LdapConnection)2 GroupUser (org.apache.openmeetings.db.entity.user.GroupUser)2 User (org.apache.openmeetings.db.entity.user.User)2 OmException (org.apache.openmeetings.util.OmException)2 ThreePid (io.kamax.matrix.ThreePid)1 BackendAuthResult (io.kamax.mxisd.auth.provider.BackendAuthResult)1 LdapConfig (io.kamax.mxisd.config.ldap.LdapConfig)1 UserDirectorySearchResult (io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchResult)1