Search in sources :

Example 56 with LdapName

use of javax.naming.ldap.LdapName in project Spark by igniterealtime.

the class CertificateModel method extractCommonName.

private String extractCommonName(String certName) throws InvalidNameException {
    String name = null;
    LdapName ldapDN = new LdapName(certName);
    for (Rdn rdn : ldapDN.getRdns()) {
        if (rdn.getType().equals("CN")) {
            name = rdn.getValue().toString();
        }
    }
    return name;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) Rdn(javax.naming.ldap.Rdn) LdapName(javax.naming.ldap.LdapName)

Example 57 with LdapName

use of javax.naming.ldap.LdapName in project certmgr by hdecarne.

the class CertOptionsTemplates method wrap.

public static Template wrap(UserCertStoreEntry storeEntry) {
    String dnInput = X500Names.toString(storeEntry.dn());
    String aliasInput = dnInput;
    try {
        LdapName dn = new LdapName(aliasInput);
        for (Rdn rdn : dn.getRdns()) {
            if (DN_ALIAS_KEY.equals(rdn.getType())) {
                aliasInput = String.valueOf(rdn.getValue());
                break;
            }
        }
    } catch (InvalidNameException e) {
        Exceptions.ignore(e);
    }
    CertOptionsPreset preset = new CertOptionsPreset(aliasInput, dnInput);
    try {
        if (storeEntry.hasCRT()) {
            X509Certificate crt = storeEntry.getCRT();
            PublicKey publicKey = crt.getPublicKey();
            preset.setKeyAlg(KeyHelper.getKeyAlg(publicKey));
            preset.setKeySize(KeyHelper.getKeySize(publicKey));
            Set<String> criticalExtensionOIDs = crt.getCriticalExtensionOIDs();
            if (criticalExtensionOIDs != null) {
                for (String criticalExtensionOID : criticalExtensionOIDs) {
                    if (!INVALID_PRESET_EXTENSIONS.contains(criticalExtensionOID)) {
                        X509ExtensionData criticalExtension = X509ExtensionData.decode(criticalExtensionOID, true, crt.getExtensionValue(criticalExtensionOID));
                        preset.addExtension(criticalExtension);
                    }
                }
            }
            Set<String> nonCriticalExtensionOIDs = crt.getNonCriticalExtensionOIDs();
            if (nonCriticalExtensionOIDs != null) {
                for (String nonCriticalExtensionOID : nonCriticalExtensionOIDs) {
                    if (!INVALID_PRESET_EXTENSIONS.contains(nonCriticalExtensionOID)) {
                        X509ExtensionData nonCriticalExtension = X509ExtensionData.decode(nonCriticalExtensionOID, false, crt.getExtensionValue(nonCriticalExtensionOID));
                        preset.addExtension(nonCriticalExtension);
                    }
                }
            }
        }
    } catch (IOException e) {
        Exceptions.warn(e);
    }
    return new Template(preset.aliasInput(), preset);
}
Also used : X509ExtensionData(de.carne.certmgr.certs.x509.X509ExtensionData) InvalidNameException(javax.naming.InvalidNameException) PublicKey(java.security.PublicKey) IOException(java.io.IOException) Rdn(javax.naming.ldap.Rdn) X509Certificate(java.security.cert.X509Certificate) LdapName(javax.naming.ldap.LdapName)

Example 58 with LdapName

use of javax.naming.ldap.LdapName in project certmgr by hdecarne.

the class DNEditorController method init.

/**
 * Initialize the DN editor's content.
 *
 * @param dnInput The current DN input.
 * @return This controller.
 */
public DNEditorController init(String dnInput) {
    try {
        LdapName dn = new LdapName(dnInput);
        this.ctlRdnEntries.getItems().addAll(dn.getRdns());
    } catch (InvalidNameException e) {
        Exceptions.ignore(e);
    }
    return this;
}
Also used : InvalidNameException(javax.naming.InvalidNameException) LdapName(javax.naming.ldap.LdapName)

Example 59 with LdapName

use of javax.naming.ldap.LdapName in project activemq-artemis by apache.

the class LDAPLoginModule method resolveDN.

private String resolveDN(String username, List<String> roles) throws FailedLoginException {
    String dn = null;
    MessageFormat userSearchMatchingFormat;
    boolean userSearchSubtreeBool;
    if (logger.isDebugEnabled()) {
        logger.debug("Create the LDAP initial context.");
    }
    try {
        openContext();
    } catch (Exception ne) {
        FailedLoginException ex = new FailedLoginException("Error opening LDAP connection");
        ex.initCause(ne);
        throw ex;
    }
    if (!isLoginPropertySet(USER_SEARCH_MATCHING))
        return dn;
    userSearchMatchingFormat = new MessageFormat(getLDAPPropertyValue(USER_SEARCH_MATCHING));
    userSearchSubtreeBool = Boolean.valueOf(getLDAPPropertyValue(USER_SEARCH_SUBTREE)).booleanValue();
    try {
        String filter = userSearchMatchingFormat.format(new String[] { doRFC2254Encoding(username) });
        SearchControls constraints = new SearchControls();
        if (userSearchSubtreeBool) {
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }
        // setup attributes
        List<String> list = new ArrayList<>();
        if (isLoginPropertySet(USER_ROLE_NAME)) {
            list.add(getLDAPPropertyValue(USER_ROLE_NAME));
        }
        String[] attribs = new String[list.size()];
        list.toArray(attribs);
        constraints.setReturningAttributes(attribs);
        if (logger.isDebugEnabled()) {
            logger.debug("Get the user DN.");
            logger.debug("Looking for the user in LDAP with ");
            logger.debug("  base DN: " + getLDAPPropertyValue(USER_BASE));
            logger.debug("  filter: " + filter);
        }
        NamingEnumeration<SearchResult> results = null;
        try {
            results = Subject.doAs(brokerGssapiIdentity, (PrivilegedExceptionAction<NamingEnumeration<SearchResult>>) () -> context.search(getLDAPPropertyValue(USER_BASE), filter, constraints));
        } catch (PrivilegedActionException e) {
            Exception cause = e.getException();
            FailedLoginException ex = new FailedLoginException("Error executing search query to resolve DN");
            ex.initCause(cause);
            throw ex;
        }
        if (results == null || !results.hasMore()) {
            throw new FailedLoginException("User " + username + " not found in LDAP.");
        }
        SearchResult result = results.next();
        if (results.hasMore()) {
        // ignore for now
        }
        if (result.isRelative()) {
            logger.debug("LDAP returned a relative name: " + result.getName());
            NameParser parser = context.getNameParser("");
            Name contextName = parser.parse(context.getNameInNamespace());
            Name baseName = parser.parse(getLDAPPropertyValue(USER_BASE));
            Name entryName = parser.parse(result.getName());
            Name name = contextName.addAll(baseName);
            name = name.addAll(entryName);
            dn = name.toString();
        } else {
            logger.debug("LDAP returned an absolute name: " + result.getName());
            try {
                URI uri = new URI(result.getName());
                String path = uri.getPath();
                if (path.startsWith("/")) {
                    dn = path.substring(1);
                } else {
                    dn = path;
                }
            } catch (URISyntaxException e) {
                closeContext();
                FailedLoginException ex = new FailedLoginException("Error parsing absolute name as URI.");
                ex.initCause(e);
                throw ex;
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Using DN [" + dn + "] for binding.");
        }
        Attributes attrs = result.getAttributes();
        if (attrs == null) {
            throw new FailedLoginException("User found, but LDAP entry malformed: " + username);
        }
        if (isLoginPropertySet(USER_ROLE_NAME)) {
            Attribute roleNames = attrs.get(getLDAPPropertyValue(USER_ROLE_NAME));
            if (roleNames != null) {
                NamingEnumeration<?> e = roleNames.getAll();
                while (e.hasMore()) {
                    String roleDnString = (String) e.next();
                    if (isRoleAttributeSet) {
                        // parse out the attribute from the group Dn
                        LdapName ldapRoleName = new LdapName(roleDnString);
                        for (int i = 0; i < ldapRoleName.size(); i++) {
                            Rdn candidate = ldapRoleName.getRdn(i);
                            if (roleAttributeName.equals(candidate.getType())) {
                                roles.add((String) candidate.getValue());
                            }
                        }
                    } else {
                        roles.add(roleDnString);
                    }
                }
            }
        }
    } catch (CommunicationException e) {
        closeContext();
        FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
        ex.initCause(e);
        throw ex;
    } catch (NamingException e) {
        closeContext();
        FailedLoginException ex = new FailedLoginException("Error contacting LDAP");
        ex.initCause(e);
        throw ex;
    }
    return dn;
}
Also used : Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) LdapName(javax.naming.ldap.LdapName) Name(javax.naming.Name) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException) Rdn(javax.naming.ldap.Rdn) MessageFormat(java.text.MessageFormat) CommunicationException(javax.naming.CommunicationException) PrivilegedActionException(java.security.PrivilegedActionException) SearchResult(javax.naming.directory.SearchResult) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) LoginException(javax.security.auth.login.LoginException) URISyntaxException(java.net.URISyntaxException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) NamingException(javax.naming.NamingException) AuthenticationException(javax.naming.AuthenticationException) FailedLoginException(javax.security.auth.login.FailedLoginException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) CommunicationException(javax.naming.CommunicationException) LdapName(javax.naming.ldap.LdapName) FailedLoginException(javax.security.auth.login.FailedLoginException) NameParser(javax.naming.NameParser)

Example 60 with LdapName

use of javax.naming.ldap.LdapName in project activemq-artemis by apache.

the class LegacyLDAPSecuritySettingPlugin method objectRemoved.

/**
 * Handler for removed policy entries in the directory.
 *
 * @param namingEvent the removed entry event that occurred
 */
public void objectRemoved(NamingEvent namingEvent) {
    try {
        LdapName ldapName = new LdapName(namingEvent.getOldBinding().getName());
        String match = null;
        for (Rdn rdn : ldapName.getRdns()) {
            if (rdn.getType().equals("uid")) {
                match = rdn.getValue().toString();
            }
        }
        Set<Role> roles = securityRepository.getMatch(match);
        List<Role> rolesToRemove = new ArrayList<>();
        for (Rdn rdn : ldapName.getRdns()) {
            if (rdn.getValue().equals(writePermissionValue)) {
                logger.debug("Removing write permission");
                for (Role role : roles) {
                    if (role.isSend()) {
                        rolesToRemove.add(role);
                    }
                }
            } else if (rdn.getValue().equals(readPermissionValue)) {
                logger.debug("Removing read permission");
                for (Role role : roles) {
                    if (role.isConsume()) {
                        rolesToRemove.add(role);
                    }
                }
            } else if (rdn.getValue().equals(adminPermissionValue)) {
                logger.debug("Removing admin permission");
                for (Role role : roles) {
                    if (role.isCreateDurableQueue() || role.isCreateNonDurableQueue() || role.isDeleteDurableQueue() || role.isDeleteNonDurableQueue()) {
                        rolesToRemove.add(role);
                    }
                }
            }
            for (Role roleToRemove : rolesToRemove) {
                roles.remove(roleToRemove);
            }
        }
    } catch (NamingException e) {
        ActiveMQServerLogger.LOGGER.failedToProcessEvent(e);
    }
}
Also used : Role(org.apache.activemq.artemis.core.security.Role) ArrayList(java.util.ArrayList) NamingException(javax.naming.NamingException) Rdn(javax.naming.ldap.Rdn) LdapName(javax.naming.ldap.LdapName)

Aggregations

LdapName (javax.naming.ldap.LdapName)88 Rdn (javax.naming.ldap.Rdn)44 InvalidNameException (javax.naming.InvalidNameException)27 Attribute (javax.naming.directory.Attribute)18 NamingException (javax.naming.NamingException)17 Attributes (javax.naming.directory.Attributes)12 SearchResult (javax.naming.directory.SearchResult)10 Test (org.junit.Test)10 ArrayList (java.util.ArrayList)8 X509Certificate (java.security.cert.X509Certificate)6 HashMap (java.util.HashMap)6 IOException (java.io.IOException)5 Test (org.junit.jupiter.api.Test)5 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)4 HashSet (java.util.HashSet)4 List (java.util.List)4 NoSuchElementException (java.util.NoSuchElementException)4 TreeSet (java.util.TreeSet)4 SearchControls (javax.naming.directory.SearchControls)4 SSLException (javax.net.ssl.SSLException)4