Search in sources :

Example 46 with CertPathValidatorException

use of java.security.cert.CertPathValidatorException in project mobile-center-sdk-android by Microsoft.

the class HttpUtilsAndroidTest method isRecoverableErrorTest.

@Test
public void isRecoverableErrorTest() {
    assertTrue(isRecoverableError(new EOFException()));
    assertTrue(isRecoverableError(new InterruptedIOException()));
    assertTrue(isRecoverableError(new SocketTimeoutException()));
    assertTrue(isRecoverableError(new SocketException()));
    assertTrue(isRecoverableError(new PortUnreachableException()));
    assertTrue(isRecoverableError(new UnknownHostException()));
    assertTrue(isRecoverableError(new RejectedExecutionException()));
    assertFalse(isRecoverableError(new MalformedURLException()));
    assertFalse(isRecoverableError(new IOException()));
    assertTrue(isRecoverableError(new IOException(new EOFException())));
    assertFalse(isRecoverableError(new IOException(new Exception())));
    for (int i = 0; i <= 4; i++) assertTrue(isRecoverableError(new HttpException(500 + i)));
    for (int i = 0; i <= 6; i++) assertFalse(isRecoverableError(new HttpException(400 + i)));
    assertTrue(isRecoverableError(new HttpException(408)));
    assertFalse(isRecoverableError(new HttpException(413)));
    assertTrue(isRecoverableError(new HttpException(429)));
    assertTrue(isRecoverableError(new SSLException("Write error: ssl=0x59c28f90: I/O error during system call, Connection timed out")));
    assertFalse(isRecoverableError(new SSLHandshakeException("java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.")));
    assertFalse(isRecoverableError(new SSLException(null, new CertPathValidatorException("Trust anchor for certification path not found."))));
    assertFalse(isRecoverableError(new SSLException("java.lang.RuntimeException: Unexpected error: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty")));
    assertTrue(isRecoverableError(new SSLException("Read error: ssl=0x9dd07200: I/O error during system call, Connection reset by peer")));
    assertTrue(isRecoverableError(new SSLException("SSL handshake aborted: ssl=0x1cc160: I/O error during system call, Connection reset by peer")));
    assertTrue(isRecoverableError(new SSLHandshakeException("javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x870c918: Failure in SSL library, usually a protocol error\nerror:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:658 0xb7c393a1:0x00000000)")));
}
Also used : InterruptedIOException(java.io.InterruptedIOException) SocketException(java.net.SocketException) PortUnreachableException(java.net.PortUnreachableException) MalformedURLException(java.net.MalformedURLException) UnknownHostException(java.net.UnknownHostException) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) SSLException(javax.net.ssl.SSLException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) MalformedURLException(java.net.MalformedURLException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) EOFException(java.io.EOFException) InterruptedIOException(java.io.InterruptedIOException) UnknownHostException(java.net.UnknownHostException) SocketException(java.net.SocketException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) SSLException(javax.net.ssl.SSLException) SocketTimeoutException(java.net.SocketTimeoutException) PortUnreachableException(java.net.PortUnreachableException) CertPathValidatorException(java.security.cert.CertPathValidatorException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) CertPathValidatorException(java.security.cert.CertPathValidatorException) SocketTimeoutException(java.net.SocketTimeoutException) EOFException(java.io.EOFException) Test(org.junit.Test)

Example 47 with CertPathValidatorException

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

the class ClientCertAuthenticator method validateClientCert.

private void validateClientCert(X509Certificate[] certs) throws ServiceException {
    String subjectDN = null;
    try {
        boolean revocationCheckEnabled = Provisioning.getInstance().getLocalServer().isMailSSLClientCertOCSPEnabled();
        Set<TrustAnchor> trustedCertsSet = null;
        if (revocationCheckEnabled) {
            char[] pass = LC.client_ssl_truststore_password.value().toCharArray();
            trustedCertsSet = CertValidationUtil.loadTrustedAnchors(pass, LC.client_ssl_truststore.value());
        }
        for (X509Certificate cert : certs) {
            subjectDN = getSubjectDNForLogging(cert);
            CertValidationUtil.validateCertificate(cert, revocationCheckEnabled, trustedCertsSet);
        }
    } catch (CertificateExpiredException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "client certificate expired", e);
    } catch (CertificateNotYetValidException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "client certificate not yet valid", e);
    } catch (CertificateException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "can't generate certpath for client certificate", e);
    } catch (KeyStoreException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received KeyStoreException while loading KeyStore", e);
    } catch (NoSuchAlgorithmException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received NoSuchAlgorithmException while obtaining instance of certpath validator", e);
    } catch (FileNotFoundException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "mailboxd keystore can't be found", e);
    } catch (IOException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received IOException", e);
    } catch (InvalidAlgorithmParameterException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received InvalidAlgorithmParameter while obtaining instance of certpath validator", e);
    } catch (CertPathValidatorException e) {
        throw AuthFailedServiceException.AUTH_FAILED(subjectDN, "received CertPathValidatorException" + e.getMessage(), e);
    }
}
Also used : CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CertificateExpiredException(java.security.cert.CertificateExpiredException) FileNotFoundException(java.io.FileNotFoundException) TrustAnchor(java.security.cert.TrustAnchor) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertPathValidatorException(java.security.cert.CertPathValidatorException)

Example 48 with CertPathValidatorException

use of java.security.cert.CertPathValidatorException in project jdk8u_jdk by JetBrains.

the class SignerInfo method verify.

/* Returns null if verify fails, this signerInfo if
       verify succeeds. */
SignerInfo verify(PKCS7 block, byte[] data) throws NoSuchAlgorithmException, SignatureException {
    try {
        ContentInfo content = block.getContentInfo();
        if (data == null) {
            data = content.getContentBytes();
        }
        ConstraintsParameters cparams = new ConstraintsParameters(timestamp);
        String digestAlgname = getDigestAlgorithmId().getName();
        byte[] dataSigned;
        // digest and compare it with the digest of data
        if (authenticatedAttributes == null) {
            dataSigned = data;
        } else {
            // first, check content type
            ObjectIdentifier contentType = (ObjectIdentifier) authenticatedAttributes.getAttributeValue(PKCS9Attribute.CONTENT_TYPE_OID);
            if (contentType == null || !contentType.equals((Object) content.contentType))
                // contentType does not match, bad SignerInfo
                return null;
            // now, check message digest
            byte[] messageDigest = (byte[]) authenticatedAttributes.getAttributeValue(PKCS9Attribute.MESSAGE_DIGEST_OID);
            if (// fail if there is no message digest
            messageDigest == null)
                return null;
            // check that digest algorithm is not restricted
            try {
                JAR_DISABLED_CHECK.permits(digestAlgname, cparams);
            } catch (CertPathValidatorException e) {
                throw new SignatureException(e.getMessage(), e);
            }
            MessageDigest md = MessageDigest.getInstance(digestAlgname);
            byte[] computedMessageDigest = md.digest(data);
            if (messageDigest.length != computedMessageDigest.length)
                return null;
            for (int i = 0; i < messageDigest.length; i++) {
                if (messageDigest[i] != computedMessageDigest[i])
                    return null;
            }
            // message digest attribute matched
            // digest of original data
            // the data actually signed is the DER encoding of
            // the authenticated attributes (tagged with
            // the "SET OF" tag, not 0xA0).
            dataSigned = authenticatedAttributes.getDerEncoding();
        }
        // put together digest algorithm and encryption algorithm
        // to form signing algorithm
        String encryptionAlgname = getDigestEncryptionAlgorithmId().getName();
        // Workaround: sometimes the encryptionAlgname is actually
        // a signature name
        String tmp = AlgorithmId.getEncAlgFromSigAlg(encryptionAlgname);
        if (tmp != null)
            encryptionAlgname = tmp;
        String algname = AlgorithmId.makeSigAlg(digestAlgname, encryptionAlgname);
        // check that jar signature algorithm is not restricted
        try {
            JAR_DISABLED_CHECK.permits(algname, cparams);
        } catch (CertPathValidatorException e) {
            throw new SignatureException(e.getMessage(), e);
        }
        X509Certificate cert = getCertificate(block);
        if (cert == null) {
            return null;
        }
        PublicKey key = cert.getPublicKey();
        // check if the public key is restricted
        if (!JAR_DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) {
            throw new SignatureException("Public key check failed. " + "Disabled key used: " + KeyUtil.getKeySize(key) + " bit " + key.getAlgorithm());
        }
        if (cert.hasUnsupportedCriticalExtension()) {
            throw new SignatureException("Certificate has unsupported " + "critical extension(s)");
        }
        // Make sure that if the usage of the key in the certificate is
        // restricted, it can be used for digital signatures.
        // XXX We may want to check for additional extensions in the
        // future.
        boolean[] keyUsageBits = cert.getKeyUsage();
        if (keyUsageBits != null) {
            KeyUsageExtension keyUsage;
            try {
                // We don't care whether or not this extension was marked
                // critical in the certificate.
                // We're interested only in its value (i.e., the bits set)
                // and treat the extension as critical.
                keyUsage = new KeyUsageExtension(keyUsageBits);
            } catch (IOException ioe) {
                throw new SignatureException("Failed to parse keyUsage " + "extension");
            }
            boolean digSigAllowed = keyUsage.get(KeyUsageExtension.DIGITAL_SIGNATURE).booleanValue();
            boolean nonRepuAllowed = keyUsage.get(KeyUsageExtension.NON_REPUDIATION).booleanValue();
            if (!digSigAllowed && !nonRepuAllowed) {
                throw new SignatureException("Key usage restricted: " + "cannot be used for " + "digital signatures");
            }
        }
        Signature sig = Signature.getInstance(algname);
        sig.initVerify(key);
        sig.update(dataSigned);
        if (sig.verify(encryptedDigest)) {
            return this;
        }
    } catch (IOException e) {
        throw new SignatureException("IO error verifying signature:\n" + e.getMessage());
    } catch (InvalidKeyException e) {
        throw new SignatureException("InvalidKey: " + e.getMessage());
    }
    return null;
}
Also used : PublicKey(java.security.PublicKey) SignatureException(java.security.SignatureException) IOException(java.io.IOException) ConstraintsParameters(sun.security.util.ConstraintsParameters) InvalidKeyException(java.security.InvalidKeyException) X509Certificate(java.security.cert.X509Certificate) CertPathValidatorException(java.security.cert.CertPathValidatorException) Signature(java.security.Signature) MessageDigest(java.security.MessageDigest) ObjectIdentifier(sun.security.util.ObjectIdentifier) KeyUsageExtension(sun.security.x509.KeyUsageExtension)

Example 49 with CertPathValidatorException

use of java.security.cert.CertPathValidatorException in project jdk8u_jdk by JetBrains.

the class BasicChecker method verifyNameChaining.

/**
     * Internal method to check that cert has a valid DN to be next in a chain
     */
private void verifyNameChaining(X509Certificate cert) throws CertPathValidatorException {
    if (prevSubject != null) {
        String msg = "subject/issuer name chaining";
        if (debug != null)
            debug.println("---checking " + msg + "...");
        X500Principal currIssuer = cert.getIssuerX500Principal();
        // reject null or empty issuer DNs
        if (X500Name.asX500Name(currIssuer).isEmpty()) {
            throw new CertPathValidatorException(msg + " check failed: " + "empty/null issuer DN in certificate is invalid", null, null, -1, PKIXReason.NAME_CHAINING);
        }
        if (!(currIssuer.equals(prevSubject))) {
            throw new CertPathValidatorException(msg + " check failed", null, null, -1, PKIXReason.NAME_CHAINING);
        }
        if (debug != null)
            debug.println(msg + " verified.");
    }
}
Also used : CertPathValidatorException(java.security.cert.CertPathValidatorException) X500Principal(javax.security.auth.x500.X500Principal)

Example 50 with CertPathValidatorException

use of java.security.cert.CertPathValidatorException in project jdk8u_jdk by JetBrains.

the class OCSPResponse method verify.

void verify(List<CertId> certIds, IssuerInfo issuerInfo, X509Certificate responderCert, Date date, byte[] nonce, String variant) throws CertPathValidatorException {
    switch(responseStatus) {
        case SUCCESSFUL:
            break;
        case TRY_LATER:
        case INTERNAL_ERROR:
            throw new CertPathValidatorException("OCSP response error: " + responseStatus, null, null, -1, BasicReason.UNDETERMINED_REVOCATION_STATUS);
        case UNAUTHORIZED:
        default:
            throw new CertPathValidatorException("OCSP response error: " + responseStatus);
    }
    // certs that were supplied in the request
    for (CertId certId : certIds) {
        SingleResponse sr = getSingleResponse(certId);
        if (sr == null) {
            if (debug != null) {
                debug.println("No response found for CertId: " + certId);
            }
            throw new CertPathValidatorException("OCSP response does not include a response for a " + "certificate supplied in the OCSP request");
        }
        if (debug != null) {
            debug.println("Status of certificate (with serial number " + certId.getSerialNumber() + ") is: " + sr.getCertStatus());
        }
    }
    // Locate the signer cert
    if (signerCert == null) {
        // of certs from the OCSP response
        try {
            if (issuerInfo.getCertificate() != null) {
                certs.add(X509CertImpl.toImpl(issuerInfo.getCertificate()));
            }
            if (responderCert != null) {
                certs.add(X509CertImpl.toImpl(responderCert));
            }
        } catch (CertificateException ce) {
            throw new CertPathValidatorException("Invalid issuer or trusted responder certificate", ce);
        }
        if (respId.getType() == ResponderId.Type.BY_NAME) {
            X500Principal rName = respId.getResponderName();
            for (X509CertImpl cert : certs) {
                if (cert.getSubjectX500Principal().equals(rName)) {
                    signerCert = cert;
                    break;
                }
            }
        } else if (respId.getType() == ResponderId.Type.BY_KEY) {
            KeyIdentifier ridKeyId = respId.getKeyIdentifier();
            for (X509CertImpl cert : certs) {
                // Match responder's key identifier against the cert's SKID
                // This will match if the SKID is encoded using the 160-bit
                // SHA-1 hash method as defined in RFC 5280.
                KeyIdentifier certKeyId = cert.getSubjectKeyId();
                if (certKeyId != null && ridKeyId.equals(certKeyId)) {
                    signerCert = cert;
                    break;
                } else {
                    // cert's public key using the 160-bit SHA-1 method.
                    try {
                        certKeyId = new KeyIdentifier(cert.getPublicKey());
                    } catch (IOException e) {
                    // ignore
                    }
                    if (ridKeyId.equals(certKeyId)) {
                        signerCert = cert;
                        break;
                    }
                }
            }
        }
    }
    // Check whether the signer cert returned by the responder is trusted
    if (signerCert != null) {
        // Check if the response is signed by the issuing CA
        if (signerCert.getSubjectX500Principal().equals(issuerInfo.getName()) && signerCert.getPublicKey().equals(issuerInfo.getPublicKey())) {
            if (debug != null) {
                debug.println("OCSP response is signed by the target's " + "Issuing CA");
            }
        // cert is trusted, now verify the signed response
        // Check if the response is signed by a trusted responder
        } else if (signerCert.equals(responderCert)) {
            if (debug != null) {
                debug.println("OCSP response is signed by a Trusted " + "Responder");
            }
        // cert is trusted, now verify the signed response
        // Check if the response is signed by an authorized responder
        } else if (signerCert.getIssuerX500Principal().equals(issuerInfo.getName())) {
            // Check for the OCSPSigning key purpose
            try {
                List<String> keyPurposes = signerCert.getExtendedKeyUsage();
                if (keyPurposes == null || !keyPurposes.contains(KP_OCSP_SIGNING_OID)) {
                    throw new CertPathValidatorException("Responder's certificate not valid for signing " + "OCSP responses");
                }
            } catch (CertificateParsingException cpe) {
                // assume cert is not valid for signing
                throw new CertPathValidatorException("Responder's certificate not valid for signing " + "OCSP responses", cpe);
            }
            // Check algorithm constraints specified in security property
            // "jdk.certpath.disabledAlgorithms".
            AlgorithmChecker algChecker = new AlgorithmChecker(issuerInfo.getAnchor(), date, variant);
            algChecker.init(false);
            algChecker.check(signerCert, Collections.<String>emptySet());
            // check the validity
            try {
                if (date == null) {
                    signerCert.checkValidity();
                } else {
                    signerCert.checkValidity(date);
                }
            } catch (CertificateException e) {
                throw new CertPathValidatorException("Responder's certificate not within the " + "validity period", e);
            }
            // check for revocation
            //
            // A CA may specify that an OCSP client can trust a
            // responder for the lifetime of the responder's
            // certificate. The CA does so by including the
            // extension id-pkix-ocsp-nocheck.
            //
            Extension noCheck = signerCert.getExtension(PKIXExtensions.OCSPNoCheck_Id);
            if (noCheck != null) {
                if (debug != null) {
                    debug.println("Responder's certificate includes " + "the extension id-pkix-ocsp-nocheck.");
                }
            } else {
            // we should do the revocation checking of the
            // authorized responder in a future update.
            }
            // verify the signature
            try {
                signerCert.verify(issuerInfo.getPublicKey());
                if (debug != null) {
                    debug.println("OCSP response is signed by an " + "Authorized Responder");
                }
            // cert is trusted, now verify the signed response
            } catch (GeneralSecurityException e) {
                signerCert = null;
            }
        } else {
            throw new CertPathValidatorException("Responder's certificate is not authorized to sign " + "OCSP responses");
        }
    }
    // key from the trusted responder cert
    if (signerCert != null) {
        // Check algorithm constraints specified in security property
        // "jdk.certpath.disabledAlgorithms".
        AlgorithmChecker.check(signerCert.getPublicKey(), sigAlgId, variant);
        if (!verifySignature(signerCert)) {
            throw new CertPathValidatorException("Error verifying OCSP Response's signature");
        }
    } else {
        // Need responder's cert in order to verify the signature
        throw new CertPathValidatorException("Unable to verify OCSP Response's signature");
    }
    if (nonce != null) {
        if (responseNonce != null && !Arrays.equals(nonce, responseNonce)) {
            throw new CertPathValidatorException("Nonces don't match");
        }
    }
    // Check freshness of OCSPResponse
    long now = (date == null) ? System.currentTimeMillis() : date.getTime();
    Date nowPlusSkew = new Date(now + MAX_CLOCK_SKEW);
    Date nowMinusSkew = new Date(now - MAX_CLOCK_SKEW);
    for (SingleResponse sr : singleResponseMap.values()) {
        if (debug != null) {
            String until = "";
            if (sr.nextUpdate != null) {
                until = " until " + sr.nextUpdate;
            }
            debug.println("OCSP response validity interval is from " + sr.thisUpdate + until);
            debug.println("Checking validity of OCSP response on: " + new Date(now));
        }
        //     MAX(thisUpdate, nextUpdate) + MAX_CLOCK_SKEW ]
        if (nowPlusSkew.before(sr.thisUpdate) || nowMinusSkew.after(sr.nextUpdate != null ? sr.nextUpdate : sr.thisUpdate)) {
            throw new CertPathValidatorException("Response is unreliable: its validity " + "interval is out-of-date");
        }
    }
}
Also used : CertificateParsingException(java.security.cert.CertificateParsingException) CertificateException(java.security.cert.CertificateException) Date(java.util.Date) CertPathValidatorException(java.security.cert.CertPathValidatorException) X500Principal(javax.security.auth.x500.X500Principal)

Aggregations

CertPathValidatorException (java.security.cert.CertPathValidatorException)92 IOException (java.io.IOException)45 X509Certificate (java.security.cert.X509Certificate)43 ExtCertPathValidatorException (org.bouncycastle.jce.exception.ExtCertPathValidatorException)36 ArrayList (java.util.ArrayList)35 GeneralSecurityException (java.security.GeneralSecurityException)32 List (java.util.List)30 CertPathBuilderException (java.security.cert.CertPathBuilderException)24 CertificateExpiredException (java.security.cert.CertificateExpiredException)24 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)24 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)23 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)23 IssuingDistributionPoint (org.bouncycastle.asn1.x509.IssuingDistributionPoint)21 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)18 Enumeration (java.util.Enumeration)15 Iterator (java.util.Iterator)15 CertificateException (java.security.cert.CertificateException)13 CertPath (java.security.cert.CertPath)12 HashSet (java.util.HashSet)12 Set (java.util.Set)10