Search in sources :

Example 51 with LdapName

use of javax.naming.ldap.LdapName in project airlift by airlift.

the class TestPemReader method assertX509Certificate.

private static void assertX509Certificate(X509Certificate x509Certificate) throws InvalidNameException {
    LdapName ldapName = new LdapName(x509Certificate.getSubjectX500Principal().getName());
    String cn = ldapName.getRdns().stream().filter(rdn -> rdn.getType().equals("CN")).map(Rdn::getValue).findFirst().map(String.class::cast).orElseThrow(() -> new AssertionError("Certificate subject name does not contain a CN"));
    assertEquals(cn, "Test User");
}
Also used : LdapName(javax.naming.ldap.LdapName)

Example 52 with LdapName

use of javax.naming.ldap.LdapName in project ranger by apache.

the class ServiceUtil method isValidateHttpsAuthentication.

public boolean isValidateHttpsAuthentication(String serviceName, HttpServletRequest request) {
    boolean isValidAuthentication = false;
    boolean httpEnabled = PropertiesUtil.getBooleanProperty("ranger.service.http.enabled", true);
    X509Certificate[] certchain = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
    String ipAddress = request.getHeader("X-FORWARDED-FOR");
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }
    boolean isSecure = request.isSecure();
    if (serviceName == null || serviceName.isEmpty()) {
        LOG.error("ServiceName not provided");
        throw restErrorUtil.createRESTException("Unauthorized access.", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
    }
    RangerService service = null;
    try {
        service = svcStore.getServiceByName(serviceName);
    } catch (Exception e) {
        LOG.error("Requested Service not found. serviceName=" + serviceName);
        throw restErrorUtil.createRESTException("Service:" + serviceName + " not found", MessageEnums.DATA_NOT_FOUND);
    }
    if (service == null) {
        LOG.error("Requested Service not found. serviceName=" + serviceName);
        throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, RangerServiceNotFoundException.buildExceptionMsg(serviceName), false);
    }
    if (!service.getIsEnabled()) {
        LOG.error("Requested Service is disabled. serviceName=" + serviceName);
        throw restErrorUtil.createRESTException("Unauthorized access.", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE);
    }
    if (!httpEnabled) {
        if (!isSecure) {
            LOG.error("Unauthorized access. Only https is allowed. serviceName=" + serviceName);
            throw restErrorUtil.createRESTException("Unauthorized access -" + " only https allowed", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }
        if (certchain == null || certchain.length == 0) {
            LOG.error("Unauthorized access. Unable to get client certificate. serviceName=" + serviceName);
            throw restErrorUtil.createRESTException("Unauthorized access -" + " unable to get client certificate", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }
        // Check if common name is found in service config
        Map<String, String> configMap = service.getConfigs();
        String cnFromConfig = configMap.get("commonNameForCertificate");
        if (cnFromConfig == null || "".equals(cnFromConfig.trim())) {
            LOG.error("Unauthorized access. No common name for certificate set. Please check your service config");
            throw restErrorUtil.createRESTException("Unauthorized access. No common name for certificate set. Please check your service config", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }
        String cnFromConfigForTest = cnFromConfig;
        boolean isRegEx = cnFromConfig.toLowerCase().startsWith(REGEX_PREFIX_STR);
        if (isRegEx) {
            cnFromConfigForTest = cnFromConfig.substring(REGEX_PREFIX_STR_LENGTH);
        }
        // Perform SAN validation
        try {
            Collection<List<?>> subjectAltNames = certchain[0].getSubjectAlternativeNames();
            if (subjectAltNames != null) {
                for (List<?> sanItem : subjectAltNames) {
                    if (sanItem.size() == 2) {
                        Integer sanType = (Integer) sanItem.get(0);
                        String sanValue = (String) sanItem.get(1);
                        if ((sanType == 2 || sanType == 7) && (matchNames(sanValue, cnFromConfigForTest, isRegEx))) {
                            if (LOG.isDebugEnabled())
                                LOG.debug("Client Cert verification successful, matched SAN:" + sanValue);
                            isValidAuthentication = true;
                            break;
                        }
                    }
                }
            }
        } catch (Throwable e) {
            LOG.error("Unauthorized access. Error getting SAN from certificate", e);
            throw restErrorUtil.createRESTException("Unauthorized access - Error getting SAN from client certificate", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }
        // Perform common name validation only if SAN validation did not succeed
        if (!isValidAuthentication) {
            String commonName = null;
            if (certchain != null) {
                X509Certificate clientCert = certchain[0];
                String dn = clientCert.getSubjectX500Principal().getName();
                try {
                    LdapName ln = new LdapName(dn);
                    for (Rdn rdn : ln.getRdns()) {
                        if ("CN".equalsIgnoreCase(rdn.getType())) {
                            commonName = rdn.getValue() + "";
                            break;
                        }
                    }
                    if (commonName == null) {
                        LOG.error("Unauthorized access. CName is null. serviceName=" + serviceName);
                        throw restErrorUtil.createRESTException("Unauthorized access - Unable to find Common Name from [" + dn + "]", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
                    }
                } catch (InvalidNameException e) {
                    LOG.error("Invalid Common Name. CName=" + commonName + ", serviceName=" + serviceName, e);
                    throw restErrorUtil.createRESTException("Unauthorized access - Invalid Common Name", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
                }
            }
            if (commonName != null) {
                if (matchNames(commonName, cnFromConfigForTest, isRegEx)) {
                    if (LOG.isDebugEnabled())
                        LOG.debug("Client Cert verification successful, matched CN " + commonName + " with " + cnFromConfigForTest + ", wildcard match = " + isRegEx);
                    isValidAuthentication = true;
                }
                if (!isValidAuthentication) {
                    LOG.error("Unauthorized access. expected [" + cnFromConfigForTest + "], found [" + commonName + "], serviceName=" + serviceName);
                    throw restErrorUtil.createRESTException("Unauthorized access. expected [" + cnFromConfigForTest + "], found [" + commonName + "]", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
                }
            }
        }
    } else {
        isValidAuthentication = true;
    }
    return isValidAuthentication;
}
Also used : X509Certificate(java.security.cert.X509Certificate) RangerServiceNotFoundException(org.apache.ranger.plugin.util.RangerServiceNotFoundException) InvalidNameException(javax.naming.InvalidNameException) WebApplicationException(javax.ws.rs.WebApplicationException) LdapName(javax.naming.ldap.LdapName) InvalidNameException(javax.naming.InvalidNameException) ArrayList(java.util.ArrayList) VXPolicyList(org.apache.ranger.view.VXPolicyList) List(java.util.List) VXRepositoryList(org.apache.ranger.view.VXRepositoryList) RangerService(org.apache.ranger.plugin.model.RangerService) Rdn(javax.naming.ldap.Rdn)

Example 53 with LdapName

use of javax.naming.ldap.LdapName in project cxf by apache.

the class DefaultSubjectProvider method createSubjectBean.

/**
 * Create the SubjectBean using the specified principal.
 */
protected SubjectBean createSubjectBean(Principal principal, SubjectProviderParameters subjectProviderParameters) {
    TokenProviderParameters providerParameters = subjectProviderParameters.getProviderParameters();
    TokenRequirements tokenRequirements = providerParameters.getTokenRequirements();
    KeyRequirements keyRequirements = providerParameters.getKeyRequirements();
    String tokenType = tokenRequirements.getTokenType();
    String keyType = keyRequirements.getKeyType();
    String confirmationMethod = getSubjectConfirmationMethod(tokenType, keyType);
    String subjectName = principal.getName();
    String localSubjectNameIDFormat = subjectNameIDFormat;
    if (SAML2Constants.NAMEID_FORMAT_UNSPECIFIED.equals(localSubjectNameIDFormat) && principal instanceof X500Principal) {
        // Just use the "cn" instead of the entire DN
        try {
            LdapName ln = new LdapName(principal.getName());
            for (Rdn rdn : ln.getRdns()) {
                if ("CN".equalsIgnoreCase(rdn.getType()) && (rdn.getValue() instanceof String)) {
                    subjectName = (String) rdn.getValue();
                    break;
                }
            }
        } catch (Throwable ex) {
            subjectName = principal.getName();
        // Ignore, not X500 compliant thus use the whole string as the value
        }
    } else if (!SAML2Constants.NAMEID_FORMAT_UNSPECIFIED.equals(localSubjectNameIDFormat)) {
        /* Set subjectNameIDFormat correctly based on type of principal
                unless already set to some value other than unspecified */
        if (principal instanceof UsernameTokenPrincipal) {
            localSubjectNameIDFormat = SAML2Constants.NAMEID_FORMAT_PERSISTENT;
        } else if (principal instanceof X500Principal) {
            localSubjectNameIDFormat = SAML2Constants.NAMEID_FORMAT_X509_SUBJECT_NAME;
        } else if (principal instanceof KerberosPrincipal) {
            localSubjectNameIDFormat = SAML2Constants.NAMEID_FORMAT_KERBEROS;
        } else if (localSubjectNameIDFormat == null) {
            localSubjectNameIDFormat = SAML2Constants.NAMEID_FORMAT_UNSPECIFIED;
        }
    }
    SubjectBean subjectBean = new SubjectBean(subjectName, subjectNameQualifier, confirmationMethod);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Creating new subject with principal name: " + principal.getName());
    }
    subjectBean.setSubjectNameIDFormat(localSubjectNameIDFormat);
    return subjectBean;
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) SubjectBean(org.apache.wss4j.common.saml.bean.SubjectBean) TokenRequirements(org.apache.cxf.sts.request.TokenRequirements) UsernameTokenPrincipal(org.apache.wss4j.common.principal.UsernameTokenPrincipal) X500Principal(javax.security.auth.x500.X500Principal) KeyRequirements(org.apache.cxf.sts.request.KeyRequirements) Rdn(javax.naming.ldap.Rdn) LdapName(javax.naming.ldap.LdapName)

Example 54 with LdapName

use of javax.naming.ldap.LdapName in project cxf by apache.

the class CertKeyToUserNameMapper method getUserName.

/**
 * Returns Subject DN from X509Certificate
 *
 * @param cert
 * @return Subject DN as a user name
 */
@Override
public String getUserName(Certificate cert) {
    X509Certificate certificate = (X509Certificate) cert;
    String dn = certificate.getSubjectDN().getName();
    LdapName ldapDn = getLdapName(dn);
    if (key == null) {
        throw new IllegalArgumentException("Must set a key");
    }
    for (Rdn rdn : ldapDn.getRdns()) {
        if (key.equalsIgnoreCase(rdn.getType())) {
            return (String) rdn.getValue();
        }
    }
    throw new IllegalArgumentException("No " + key + " key found in certificate DN: " + dn);
}
Also used : Rdn(javax.naming.ldap.Rdn) X509Certificate(java.security.cert.X509Certificate) LdapName(javax.naming.ldap.LdapName)

Example 55 with LdapName

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

the class CertManager method useCommonNameAsAlias.

/**
 * Extract from certificate common name ("CN") and returns it to use as certificate name.
 * This method also assure that it will not add second same alias to Truststore by adding number to alias.
 * In case when common name cannot be extracted method will return "cert{number}".
 *
 * @param cert Certificate which Common Name is meant to use
 * @return String Common Name of the certificate
 * @throws InvalidNameException
 * @throws HeadlessException
 * @throws KeyStoreException
 */
protected String useCommonNameAsAlias(X509Certificate cert) throws InvalidNameException, HeadlessException, KeyStoreException {
    String alias = null;
    String dn = cert.getSubjectX500Principal().getName();
    LdapName ldapDN = new LdapName(dn);
    for (Rdn rdn : ldapDN.getRdns()) {
        if (rdn.getType().equals("CN")) {
            alias = rdn.getValue().toString();
            int i = 1;
            while (checkForSameAlias(alias)) {
                alias = alias + Integer.toString(i);
                i++;
            }
            break;
        }
    }
    // Certificate subject doesn't have easy distinguishable common name then generate alias as cert{integer}
    if (alias == null) {
        alias = "cert";
        int i = 1;
        while (checkForSameAlias(alias)) {
            alias = alias + Integer.toString(i);
            i++;
        }
    }
    return alias;
}
Also used : 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