Search in sources :

Example 71 with CertificateParsingException

use of java.security.cert.CertificateParsingException in project zm-mailbox by Zimbra.

the class CertUtil method printSubjectAlternativeNames.

private void printSubjectAlternativeNames(PrintStream outStream) throws Exception {
    final String UPN_DISPLAY = "Principal Name";
    final String RFC822NAME_DISPLAY = "RFC822 Name";
    final String DNSNAME_DISPLAY = "DNS Name";
    outStream.format("X509v3 Subject Alternative Name: \n");
    ASN1InputStream decoder = null;
    try {
        Collection<List<?>> generalNames = cert.getSubjectAlternativeNames();
        // Check that the certificate includes the SubjectAltName extension
        if (generalNames == null) {
            return;
        }
        for (List<?> generalName : generalNames) {
            Integer tag = (Integer) generalName.get(0);
            if (GeneralName.otherName == tag.intValue()) {
                // Value is encoded using ASN.1
                decoder = new ASN1InputStream((byte[]) generalName.toArray()[1]);
                ASN1Encodable encoded = decoder.readObject();
                DERSequence derSeq = (DERSequence) encoded;
                ASN1ObjectIdentifier typeId = ASN1ObjectIdentifier.getInstance(derSeq.getObjectAt(0));
                String oid = typeId.getId();
                String value = null;
                ASN1TaggedObject otherNameValue = ASN1TaggedObject.getInstance(derSeq.getObjectAt(1));
                if (OID_UPN.equals(oid)) {
                    ASN1TaggedObject upnValue = ASN1TaggedObject.getInstance(otherNameValue.getObject());
                    DERUTF8String str = DERUTF8String.getInstance(upnValue.getObject());
                    value = str.getString();
                }
                outStream.format("    [%d] %s(%s) = %s\n", tag, oid, UPN_DISPLAY, value);
            } else if (GeneralName.rfc822Name == tag.intValue()) {
                String value = (String) generalName.get(1);
                outStream.format("    [%d] %s = %s\n", tag, RFC822NAME_DISPLAY, value);
            } else if (GeneralName.dNSName == tag.intValue()) {
                String value = (String) generalName.get(1);
                outStream.format("    [%d] %s = %s\n", tag, DNSNAME_DISPLAY, value);
            } else {
                outStream.format("    [%d] - not yet supported\n", tag);
            }
        }
    } catch (CertificateParsingException e) {
        e.printStackTrace();
    } finally {
        ByteUtil.closeStream(decoder);
    }
}
Also used : BigInteger(java.math.BigInteger) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERSequence(org.bouncycastle.asn1.DERSequence) CertificateParsingException(java.security.cert.CertificateParsingException) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) List(java.util.List) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 72 with CertificateParsingException

use of java.security.cert.CertificateParsingException in project zm-mailbox by Zimbra.

the class CertUtil method getSubjectAltNameOtherNameUPN.

String getSubjectAltNameOtherNameUPN() {
    Collection<List<?>> generalNames = null;
    try {
        generalNames = cert.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {
        ZimbraLog.account.warn(LOG_PREFIX + "unable to get subject alternative names", e);
    }
    if (generalNames == null) {
        return null;
    }
    ASN1InputStream decoder = null;
    try {
        // Check that the certificate includes the SubjectAltName extension
        for (List<?> generalName : generalNames) {
            Integer tag = (Integer) generalName.get(0);
            if (GeneralName.otherName == tag.intValue()) {
                // Value is encoded using ASN.1
                decoder = new ASN1InputStream((byte[]) generalName.toArray()[1]);
                ASN1Encodable encoded = decoder.readObject();
                DERSequence derSeq = (DERSequence) encoded;
                ASN1ObjectIdentifier typeId = ASN1ObjectIdentifier.getInstance(derSeq.getObjectAt(0));
                String oid = typeId.getId();
                String value = null;
                ASN1TaggedObject otherNameValue = ASN1TaggedObject.getInstance(derSeq.getObjectAt(1));
                if (OID_UPN.equals(oid)) {
                    ASN1TaggedObject upnValue = ASN1TaggedObject.getInstance(otherNameValue.getObject());
                    DERUTF8String str = DERUTF8String.getInstance(upnValue.getObject());
                    value = str.getString();
                    return value;
                }
            }
        }
    } catch (IOException e) {
        ZimbraLog.account.warn(LOG_PREFIX + "unable to process ASN.1 data", e);
    } finally {
        ByteUtil.closeStream(decoder);
    }
    return null;
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) CertificateParsingException(java.security.cert.CertificateParsingException) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) IOException(java.io.IOException) BigInteger(java.math.BigInteger) DERSequence(org.bouncycastle.asn1.DERSequence) List(java.util.List) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 73 with CertificateParsingException

use of java.security.cert.CertificateParsingException in project fabric-sdk-java by hyperledger.

the class HFCAClientIT method verifyOptions.

// ==========================================================================================
// Helper methods
// ==========================================================================================
private void verifyOptions(String cert, EnrollmentRequest req) throws CertificateException {
    try {
        BufferedInputStream pem = new BufferedInputStream(new ByteArrayInputStream(cert.getBytes()));
        CertificateFactory certFactory = CertificateFactory.getInstance(Config.getConfig().getCertificateFormat());
        X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(pem);
        // check Subject Alternative Names
        Collection<List<?>> altNames = certificate.getSubjectAlternativeNames();
        if (altNames == null) {
            if (req.getHosts() != null && !req.getHosts().isEmpty()) {
                fail("Host name is not included in certificate");
            }
            return;
        }
        ArrayList<String> subAltList = new ArrayList<>();
        for (List<?> item : altNames) {
            int type = (Integer) item.get(0);
            if (type == 2) {
                subAltList.add((String) item.get(1));
            }
        }
        if (!subAltList.equals(req.getHosts())) {
            fail("Subject Alternative Names not matched the host names specified in enrollment request");
        }
    } catch (CertificateParsingException e) {
        fail("Cannot parse certificate. Error is: " + e.getMessage());
        throw e;
    } catch (CertificateException e) {
        fail("Cannot regenerate x509 certificate. Error is: " + e.getMessage());
        throw e;
    }
}
Also used : CertificateParsingException(java.security.cert.CertificateParsingException) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) TBSCertList(org.bouncycastle.asn1.x509.TBSCertList) List(java.util.List) ArrayList(java.util.ArrayList)

Example 74 with CertificateParsingException

use of java.security.cert.CertificateParsingException in project perun by CESNET.

the class Api method setupPerunPrincipal.

private static PerunPrincipal setupPerunPrincipal(HttpServletRequest req, Deserializer des) throws UserNotExistsException {
    String extSourceLoaString = null;
    String extLogin = null;
    String extSourceName = null;
    String extSourceType = null;
    int extSourceLoa;
    Map<String, String> additionalInformations = new HashMap<>();
    String shibIdentityProvider = getStringAttribute(req, SHIB_IDENTITY_PROVIDER);
    String sourceIdpEntityId = getStringAttribute(req, SOURCE_IDP_ENTITY_ID);
    String remoteUser = req.getRemoteUser();
    CoreConfig config = BeansUtils.getCoreConfig();
    // If we have header Shib-Identity-Provider, then the user uses identity federation to authenticate
    if (isNotEmpty(shibIdentityProvider)) {
        extSourceName = getOriginalIdP(shibIdentityProvider, sourceIdpEntityId);
        extSourceType = ExtSourcesManager.EXTSOURCE_IDP;
        extSourceLoaString = getStringAttribute(req, LOA);
        if (isEmpty(extSourceLoaString))
            extSourceLoaString = BeansUtils.getCoreConfig().getDefaultLoaIdP();
        // FIXME: find better place where do the operation with attributes from federation
        String eppn = getStringAttribute(req, "eppn");
        if (isNotEmpty(eppn)) {
            // Remove scope from the eppn attribute
            additionalInformations.put("eppnwoscope", StringUtils.substringBefore(eppn, "@"));
        }
        // Store IdP used by user to session, since for IdentityConsolidator and Registrar we need to know,
        // if user logged in through proxy or not - we provide different links etc.
        additionalInformations.put(UsersManagerBl.ORIGIN_IDENTITY_PROVIDER_KEY, shibIdentityProvider);
        if (isNotEmpty(remoteUser)) {
            extLogin = remoteUser;
        }
    } else // If OIDC_CLAIM_sub header is present, it means user authenticated via OAuth2 with MITRE.
    if (isNotEmpty(req.getHeader(OIDC_CLAIM_SUB))) {
        extLogin = req.getHeader(OIDC_CLAIM_SUB);
        // this is configurable, as the OIDC server has the source of sub claim also configurable
        String iss = req.getHeader(OIDC_CLAIM_ISS);
        if (iss != null) {
            extSourceName = BeansUtils.getCoreConfig().getOidcIssuersExtsourceNames().get(iss);
            extSourceType = BeansUtils.getCoreConfig().getOidcIssuersExtsourceTypes().get(iss);
            if (extSourceName == null || extSourceType == null) {
                throw new InternalErrorException("OIDC issuer " + iss + " not configured");
            }
        } else {
            throw new InternalErrorException("OIDC issuer not send by Authorization Server");
        }
        extSourceLoaString = "-1";
        log.debug("detected OIDC/OAuth2 client for sub={},iss={}", extLogin, iss);
    } else // EXT_SOURCE was defined in Apache configuration (e.g. Kerberos or Local)
    if (req.getAttribute(EXTSOURCE) != null) {
        extSourceName = getStringAttribute(req, EXTSOURCE);
        extSourceType = getStringAttribute(req, EXTSOURCETYPE);
        extSourceLoaString = getStringAttribute(req, EXTSOURCELOA);
        extLogin = getExtLogin(req, extSourceName, remoteUser);
    } else // Cert must be last since Apache asks for certificate everytime and fills cert properties even when Kerberos is in place.
    if (Objects.equals(req.getAttribute(SSL_CLIENT_VERIFY), SUCCESS)) {
        String certDN = getStringAttribute(req, SSL_CLIENT_SUBJECT_DN);
        String caDN = getStringAttribute(req, SSL_CLIENT_ISSUER_DN);
        String wholeCert = getStringAttribute(req, SSL_CLIENT_CERT);
        extSourceName = caDN;
        extSourceType = ExtSourcesManager.EXTSOURCE_X509;
        extSourceLoaString = getStringAttribute(req, EXTSOURCELOA);
        extLogin = certDN;
        // Store X509 certificate in the additionalInformations structure
        // FIXME: duplicit
        additionalInformations.put("userCertificates", AttributesManagerBlImpl.escapeMapAttributeValue(certDN) + AttributesManagerImpl.KEY_VALUE_DELIMITER + AttributesManagerBlImpl.escapeMapAttributeValue(wholeCert));
        additionalInformations.put("userCertDNs", AttributesManagerBlImpl.escapeMapAttributeValue(certDN) + AttributesManagerImpl.KEY_VALUE_DELIMITER + AttributesManagerBlImpl.escapeMapAttributeValue(caDN));
        additionalInformations.put(SSL_CLIENT_SUBJECT_DN, certDN);
        // Store X509
        additionalInformations.put("dn", certDN);
        additionalInformations.put("cadn", caDN);
        additionalInformations.put("certificate", wholeCert);
        // Get organization from the certificate
        Pattern p = Pattern.compile("[oO]\\s*=\\s*([^/]*)");
        Matcher m = p.matcher(certDN);
        if (m.find()) {
            additionalInformations.put("o", m.group(1));
        }
        // Get CN from the certificate
        Pattern p2 = Pattern.compile("CN=([^/]*)");
        Matcher m2 = p2.matcher(certDN);
        if (m2.find()) {
            additionalInformations.put("cn", m2.group(1));
        }
        // Get the X.509 certificate object
        X509Certificate[] certs = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
        // Get the emails
        if (certs != null && certs.length > 0 && certs[0] != null) {
            String emails = "";
            Collection<List<?>> altNames;
            try {
                altNames = certs[0].getSubjectAlternativeNames();
                if (altNames != null) {
                    for (List<?> entry : altNames) {
                        if (((Integer) entry.get(0)) == 1) {
                            emails = (String) entry.get(1);
                        }
                    }
                }
            } catch (CertificateParsingException e) {
                log.error("Error during parsing certificate {}", Arrays.asList(certs));
            }
            additionalInformations.put("mail", emails);
        }
    }
    // store selected attributes for update
    for (AttributeDefinition attr : config.getAttributesForUpdate().getOrDefault(extSourceType, Collections.emptyList())) {
        String attrValue = (String) req.getAttribute(attr.getFriendlyName());
        if (attrValue != null) {
            // fix shibboleth encoding
            if (ExtSourcesManager.EXTSOURCE_IDP.equals(extSourceType)) {
                attrValue = new String(attrValue.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            }
            log.debug("storing {}={} to additionalInformations", attr.getFriendlyName(), attrValue);
            additionalInformations.put(attr.getFriendlyName(), attrValue);
        }
    }
    // If the RPC was called by the user who can do delegation and delegatedLogin is set, set the values sent in the request
    if (des != null && extLogin != null) {
        List<String> powerUsers = config.getRpcPowerusers();
        if (powerUsers.contains(extLogin) && des.contains(DELEGATED_LOGIN)) {
            // Rewrite the remoteUser and extSource
            extLogin = des.readString(DELEGATED_LOGIN);
            extSourceName = des.readString(DELEGATED_EXTSOURCE_NAME);
            extSourceType = des.readString(DELEGATED_EXTSOURCE_TYPE);
            // Clear additionalInformations because they were valid only to the user who can do delegation
            additionalInformations.clear();
        }
    }
    // extSourceLoa must be number, if any specified then set to 0
    if (isEmpty(extSourceLoaString)) {
        extSourceLoa = 0;
    } else {
        try {
            extSourceLoa = Integer.parseInt(extSourceLoaString);
        } catch (NumberFormatException ex) {
            extSourceLoa = 0;
        }
    }
    // Check if any of authentication system returns extLogin and extSourceName
    if (isEmpty(extLogin) || isEmpty(extSourceName)) {
        throw new UserNotExistsException("extLogin or extSourceName is empty");
    }
    log.trace("creating PerunPrincipal(actor={},extSourceName={},extSourceType={},extSourceLoa={},additionalInformations={})", extLogin, extSourceName, extSourceType, extSourceLoa, additionalInformations);
    return new PerunPrincipal(extLogin, extSourceName, extSourceType, extSourceLoa, additionalInformations);
}
Also used : Pattern(java.util.regex.Pattern) CertificateParsingException(java.security.cert.CertificateParsingException) HashMap(java.util.HashMap) CoreConfig(cz.metacentrum.perun.core.api.CoreConfig) Matcher(java.util.regex.Matcher) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) AttributeDefinition(cz.metacentrum.perun.core.api.AttributeDefinition) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) X509Certificate(java.security.cert.X509Certificate) Collection(java.util.Collection) PerunPrincipal(cz.metacentrum.perun.core.api.PerunPrincipal) List(java.util.List) ArrayList(java.util.ArrayList)

Example 75 with CertificateParsingException

use of java.security.cert.CertificateParsingException in project smarthome by eclipse.

the class ExtensibleTrustManagerImplTest method shouldBeResilientAgainstInvalidCertificates.

@Test
public void shouldBeResilientAgainstInvalidCertificates() throws CertificateException, IllegalAccessException {
    FieldUtils.writeField(subject, "defaultTrustManager", defaultTrustManager, true);
    when(topOfChain.getSubjectX500Principal()).thenReturn(new X500Principal("CN=example.com, OU=Smarthome, O=Eclipse, C=DE"));
    when(topOfChain.getSubjectAlternativeNames()).thenThrow(new CertificateParsingException("Invalid certificate!!!"));
    subject.checkClientTrusted(chain, "just");
    verify(defaultTrustManager).checkClientTrusted(chain, "just", (Socket) null);
    verifyNoMoreInteractions(trustmanager);
}
Also used : CertificateParsingException(java.security.cert.CertificateParsingException) X500Principal(javax.security.auth.x500.X500Principal) Test(org.junit.Test)

Aggregations

CertificateParsingException (java.security.cert.CertificateParsingException)75 List (java.util.List)27 IOException (java.io.IOException)18 ArrayList (java.util.ArrayList)18 X509Certificate (java.security.cert.X509Certificate)16 CertificateException (java.security.cert.CertificateException)14 Collection (java.util.Collection)13 X500Principal (javax.security.auth.x500.X500Principal)13 BigInteger (java.math.BigInteger)8 InvalidKeyException (java.security.InvalidKeyException)7 HashMap (java.util.HashMap)7 DERIA5String (org.bouncycastle.asn1.DERIA5String)7 DEROctetString (org.bouncycastle.asn1.DEROctetString)7 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 NoSuchProviderException (java.security.NoSuchProviderException)6 SignatureException (java.security.SignatureException)6 CertificateEncodingException (java.security.cert.CertificateEncodingException)6 CertificateExpiredException (java.security.cert.CertificateExpiredException)6 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)6 GeneralName (org.bouncycastle.asn1.x509.GeneralName)6