Search in sources :

Example 21 with AuthenticationException

use of org.exist.security.AuthenticationException in project exist by eXist-db.

the class AccountFunctions method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    final SecurityManager sm = context.getBroker().getBrokerPool().getSecurityManager();
    final LDAPRealm ldapRealm = getLdapRealm(sm);
    final String accountName = args[0].itemAt(0).getStringValue();
    final Account ldapAccount = sm.getAccount(accountName);
    if (ldapAccount == null)
        throw new XPathException("The Account '" + accountName + "' does not exist!");
    try {
        ldapRealm.refreshAccountFromLdap(ldapAccount);
    } catch (final PermissionDeniedException | AuthenticationException pde) {
        throw new XPathException(this, pde);
    }
    return Sequence.EMPTY_SEQUENCE;
}
Also used : Account(org.exist.security.Account) SecurityManager(org.exist.security.SecurityManager) LDAPRealm(org.exist.security.realm.ldap.LDAPRealm) XPathException(org.exist.xquery.XPathException) AuthenticationException(org.exist.security.AuthenticationException) PermissionDeniedException(org.exist.security.PermissionDeniedException)

Example 22 with AuthenticationException

use of org.exist.security.AuthenticationException in project exist by eXist-db.

the class LDAPRealm method getAccount.

private synchronized Account getAccount(final LdapContext ctx, String name) {
    name = ensureCase(name);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Get request for account '{}'.", name);
    }
    // first attempt to get the cached account
    final Account acct = super.getAccount(name);
    if (acct != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Cached used.");
        }
        // XXX: synchronize with LDAP
        return acct;
    } else {
        // if the account is not cached, we should try and find it in LDAP and cache it if it exists
        try {
            // do the lookup
            final SearchResult ldapUser = findAccountByAccountName(ctx, name);
            if (LOG.isDebugEnabled()) {
                LOG.debug("LDAP search return '{}'.", ldapUser);
            }
            if (ldapUser == null) {
                return null;
            } else {
                // found a user from ldap so cache them and return
                try {
                    final String primaryGroupSID = getPrimaryGroupSID(ldapUser);
                    final String primaryGroup = findGroupBySID(ctx, primaryGroupSID);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("LDAP search for primary group by SID '{}', found '{}'.", primaryGroupSID, primaryGroup);
                    }
                    if (primaryGroup == null) {
                        // or exception?
                        return null;
                    }
                    return createAccountInDatabase(ctx, name, ldapUser, ensureCase(primaryGroup));
                // registerAccount(acct); //TODO do we need this
                } catch (final AuthenticationException ae) {
                    LOG.error(ae.getMessage(), ae);
                    return null;
                }
            }
        } catch (final NamingException ne) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(ne.getMessage(), ne);
            }
            // LOG.error(new AuthenticationException(AuthenticationException.UNNOWN_EXCEPTION, ne.getMessage()));
            return null;
        }
    }
}
Also used : Account(org.exist.security.Account) AbstractAccount(org.exist.security.AbstractAccount) AuthenticationException(org.exist.security.AuthenticationException) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException)

Example 23 with AuthenticationException

use of org.exist.security.AuthenticationException in project exist by eXist-db.

the class LDAPRealm method findAllGroupMembers.

@Override
public List<String> findAllGroupMembers(final String groupName) {
    final String name = escapeSearchAttribute(ensureCase(groupName));
    final List<String> groupMembers = new ArrayList<>();
    if (!checkGroupRestrictionList(name)) {
        return groupMembers;
    }
    LdapContext ctx = null;
    try {
        ctx = getContext(getSecurityManager().getCurrentSubject());
        // find the dn of the group
        SearchResult searchResult = findGroupByGroupName(ctx, removeDomainPostfix(name));
        if (searchResult == null) {
            // no such group
            return groupMembers;
        }
        final LDAPSearchContext search = ensureContextFactory().getSearch();
        final String dnGroup = (String) searchResult.getAttributes().get(search.getSearchGroup().getSearchAttribute(LDAPSearchAttributeKey.DN)).get();
        // find all accounts that are a member of the group
        final SearchAttribute sa = new SearchAttribute(search.getSearchAccount().getSearchAttribute(LDAPSearchAttributeKey.MEMBER_OF), escapeSearchAttribute(dnGroup));
        final String searchFilter = buildSearchFilter(search.getSearchAccount().getSearchFilterPrefix(), sa);
        final SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchControls.setReturningAttributes(new String[] { search.getSearchAccount().getSearchAttribute(LDAPSearchAttributeKey.NAME) });
        final NamingEnumeration<SearchResult> results = ctx.search(search.getBase(), searchFilter, searchControls);
        while (results.hasMoreElements()) {
            searchResult = results.nextElement();
            final String member = ensureCase(addDomainPostfix((String) searchResult.getAttributes().get(search.getSearchAccount().getSearchAttribute(LDAPSearchAttributeKey.NAME)).get()));
            if (checkAccountRestrictionList(member)) {
                groupMembers.add(member);
            }
        }
    } catch (final NamingException ne) {
        LOG.error(new AuthenticationException(AuthenticationException.UNNOWN_EXCEPTION, ne.getMessage()));
    } finally {
        if (ctx != null) {
            LdapUtils.closeContext(ctx);
        }
    }
    return groupMembers;
}
Also used : AuthenticationException(org.exist.security.AuthenticationException) ArrayList(java.util.ArrayList) SearchResult(javax.naming.directory.SearchResult) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException) LdapContext(javax.naming.ldap.LdapContext)

Example 24 with AuthenticationException

use of org.exist.security.AuthenticationException in project exist by eXist-db.

the class LDAPRealm method findGroupnamesForUserDistinguishedName.

private List<String> findGroupnamesForUserDistinguishedName(final LdapContext ctx, final String userDistinguishedName) {
    final List<String> groupnames = new ArrayList<>();
    try {
        final LDAPSearchContext search = ensureContextFactory().getSearch();
        final SearchAttribute sa = new SearchAttribute(search.getSearchGroup().getSearchAttribute(LDAPSearchAttributeKey.MEMBER), escapeSearchAttribute(userDistinguishedName));
        final String searchFilter = buildSearchFilter(search.getSearchGroup().getSearchFilterPrefix(), sa);
        final SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchControls.setReturningAttributes(new String[] { search.getSearchGroup().getSearchAttribute(LDAPSearchAttributeKey.NAME) });
        final NamingEnumeration<SearchResult> results = ctx.search(search.getAbsoluteBase(), searchFilter, searchControls);
        while (results.hasMoreElements()) {
            final SearchResult searchResult = results.nextElement();
            final String groupname = ensureCase(addDomainPostfix((String) searchResult.getAttributes().get(search.getSearchGroup().getSearchAttribute(LDAPSearchAttributeKey.NAME)).get()));
            if (checkGroupRestrictionList(groupname)) {
                groupnames.add(groupname);
            }
        }
    } catch (final NamingException ne) {
        LOG.error(new AuthenticationException(AuthenticationException.UNNOWN_EXCEPTION, ne.getMessage()));
    }
    return groupnames;
}
Also used : AuthenticationException(org.exist.security.AuthenticationException) ArrayList(java.util.ArrayList) SearchControls(javax.naming.directory.SearchControls) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException)

Example 25 with AuthenticationException

use of org.exist.security.AuthenticationException in project exist by eXist-db.

the class LDAPRealm method refreshAccountFromLdap.

public Account refreshAccountFromLdap(final Account account) throws PermissionDeniedException, AuthenticationException {
    final int UPDATE_NONE = 0;
    final int UPDATE_GROUP = 1;
    final int UPDATE_METADATA = 2;
    final Subject invokingUser = getSecurityManager().getCurrentSubject();
    if (!invokingUser.hasDbaRole() && invokingUser.getId() != account.getId()) {
        throw new PermissionDeniedException("You do not have permission to modify the account");
    }
    LdapContext ctx = null;
    try {
        ctx = getContext(invokingUser);
        final SearchResult ldapUser = findAccountByAccountName(ctx, account.getName());
        if (ldapUser == null) {
            throw new AuthenticationException(AuthenticationException.ACCOUNT_NOT_FOUND, "Could not find the account in the LDAP");
        }
        return executeAsSystemUser(ctx, (ctx2, broker) -> {
            int update = UPDATE_NONE;
            // 1) get the ldap group membership
            final List<Group> memberOf_groups = getGroupMembershipForLdapUser(ctx2, broker, ldapUser);
            // 2) get the ldap primary group
            final String primaryGroup = findGroupBySID(ctx2, getPrimaryGroupSID(ldapUser));
            // append the ldap primaryGroup to the head of the ldap group list, and compare
            // to the account group list
            memberOf_groups.add(0, getGroup(ctx2, broker, primaryGroup));
            final String[] accountGroups = account.getGroups();
            if (!accountGroups[0].equals(ensureCase(primaryGroup))) {
                update |= UPDATE_GROUP;
            } else {
                if (accountGroups.length != memberOf_groups.size()) {
                    update |= UPDATE_GROUP;
                } else {
                    for (final String accountGroup : accountGroups) {
                        boolean found = false;
                        for (final Group memberOf_group : memberOf_groups) {
                            if (accountGroup.equals(ensureCase(memberOf_group.getName()))) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            update |= UPDATE_GROUP;
                            break;
                        }
                    }
                }
            }
            // 3) check metadata
            final List<SimpleEntry<AXSchemaType, String>> ldapMetadatas = getMetadataForLdapUser(ldapUser);
            final Set<SchemaType> accountMetadataKeys = account.getMetadataKeys();
            if (accountMetadataKeys.size() != ldapMetadatas.size()) {
                update |= UPDATE_METADATA;
            } else {
                for (SchemaType accountMetadataKey : accountMetadataKeys) {
                    final String accountMetadataValue = account.getMetadataValue(accountMetadataKey);
                    boolean found = false;
                    for (SimpleEntry<AXSchemaType, String> ldapMetadata : ldapMetadatas) {
                        if (accountMetadataKey.equals(ldapMetadata.getKey()) && accountMetadataValue.equals(ldapMetadata.getValue())) {
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        update |= UPDATE_METADATA;
                        break;
                    }
                }
            }
            // update the groups?
            if ((update & UPDATE_GROUP) == UPDATE_GROUP) {
                try {
                    final Field fld = account.getClass().getSuperclass().getDeclaredField("groups");
                    fld.setAccessible(true);
                    fld.set(account, memberOf_groups);
                } catch (final NoSuchFieldException | IllegalAccessException nsfe) {
                    throw new EXistException(nsfe.getMessage(), nsfe);
                }
            }
            // update the metdata?
            if ((update & UPDATE_METADATA) == UPDATE_METADATA) {
                account.clearMetadata();
                for (final SimpleEntry<AXSchemaType, String> ldapMetadata : ldapMetadatas) {
                    account.setMetadataValue(ldapMetadata.getKey(), ldapMetadata.getValue());
                }
            }
            if (update != UPDATE_NONE) {
                final boolean updated = getSecurityManager().updateAccount(account);
                if (!updated) {
                    LOG.error("Could not update account");
                }
            }
            return account;
        });
    } catch (final NamingException | EXistException ne) {
        throw new AuthenticationException(AuthenticationException.UNNOWN_EXCEPTION, ne.getMessage(), ne);
    } finally {
        LdapUtils.closeContext(ctx);
    }
}
Also used : Group(org.exist.security.Group) AuthenticationException(org.exist.security.AuthenticationException) SimpleEntry(java.util.AbstractMap.SimpleEntry) SearchResult(javax.naming.directory.SearchResult) EXistException(org.exist.EXistException) Subject(org.exist.security.Subject) SchemaType(org.exist.security.SchemaType) AXSchemaType(org.exist.security.AXSchemaType) Field(java.lang.reflect.Field) PermissionDeniedException(org.exist.security.PermissionDeniedException) NamingException(javax.naming.NamingException) LdapContext(javax.naming.ldap.LdapContext) AXSchemaType(org.exist.security.AXSchemaType)

Aggregations

AuthenticationException (org.exist.security.AuthenticationException)33 NamingException (javax.naming.NamingException)16 Subject (org.exist.security.Subject)13 SearchResult (javax.naming.directory.SearchResult)12 LdapContext (javax.naming.ldap.LdapContext)12 SearchControls (javax.naming.directory.SearchControls)9 ArrayList (java.util.ArrayList)8 EXistException (org.exist.EXistException)8 SecurityManager (org.exist.security.SecurityManager)8 AbstractAccount (org.exist.security.AbstractAccount)6 Account (org.exist.security.Account)6 PermissionDeniedException (org.exist.security.PermissionDeniedException)5 Group (org.exist.security.Group)4 DBBroker (org.exist.storage.DBBroker)4 HttpSession (javax.servlet.http.HttpSession)3 IOException (java.io.IOException)2 PrintWriter (java.io.PrintWriter)2 URISyntaxException (java.net.URISyntaxException)2 Properties (java.util.Properties)2 ServletException (javax.servlet.ServletException)2