java.security.cert.CertificateRevokedException Java Examples

The following examples show how to use java.security.cert.CertificateRevokedException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CertificateRevocationExceptionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Override
public void assertDeserialized(Serializable initial, Serializable deserialized) {
    assertTrue(initial instanceof CertificateRevokedException);
    assertTrue(deserialized instanceof CertificateRevokedException);

    CertificateRevokedException expected = (CertificateRevokedException) initial;
    CertificateRevokedException actual = (CertificateRevokedException) deserialized;

    assertEquals(expected.getInvalidityDate(), actual.getInvalidityDate());
    assertNotSame(expected.getInvalidityDate(), actual.getInvalidityDate());
    assertEquals(expected.getRevocationDate(), actual.getRevocationDate());
    assertNotSame(expected.getRevocationDate(), actual.getRevocationDate());
    assertEquals(expected.getRevocationReason(), expected.getRevocationReason());
    assertEquals(expected.getAuthorityName(), actual.getAuthorityName());
    assertNotSame(expected.getAuthorityName(), actual.getAuthorityName());

    assertEquals(expected.getExtensions().size(), actual.getExtensions().size());
    assertEquals(expected.getExtensions().keySet(), actual.getExtensions().keySet());
}
 
Example #2
Source File: CertificateValidatorTest.java    From deprecated-security-ssl with Apache License 2.0 5 votes vote down vote up
@Test
public void testCRLDP() throws Exception {

    //trust chain incl intermediate certificates (root + intermediates)
    Collection<? extends Certificate> rootCas;
    final File trustedCas = getAbsoluteFilePathFromClassPath("root-ca.pem");
    try(FileInputStream trin = new FileInputStream(trustedCas)) {
        rootCas =  (Collection<? extends Certificate>) CertificateFactory.getInstance("X.509").generateCertificates(trin);
    }
    
    Assert.assertEquals(rootCas.size(), 1);

    //certificate chain to validate (client cert + intermediates but without root)
    Collection<? extends Certificate> certsToValidate;
    final File certs = getAbsoluteFilePathFromClassPath("crl/revoked.crt.pem");
    //final File certs = getAbsoluteFilePathFromClassPath("node-0.crt.pem");
    try(FileInputStream trin = new FileInputStream(certs)) {
        certsToValidate =  (Collection<? extends Certificate>) CertificateFactory.getInstance("X.509").generateCertificates(trin);
    }
    
    Assert.assertEquals(certsToValidate.size(), 2);
    
    CertificateValidator validator = new CertificateValidator(rootCas.toArray(new X509Certificate[0]), Collections.emptyList());
    validator.setEnableCRLDP(true);
    validator.setEnableOCSP(true);
    validator.setDate(CRL_DATE);
    try {
        validator.validate(certsToValidate.toArray(new X509Certificate[0]));
        Assert.fail();
    } catch (CertificateException e) {
        Assert.assertTrue(ExceptionUtils.getRootCause(e) instanceof CertificateRevokedException);
    }
}
 
Example #3
Source File: CertificateRevocationExceptionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testGetInvalidityDate() throws Exception {
    CertificateRevokedException exception = getTestException();

    Date firstDate = exception.getInvalidityDate();
    assertNotSame(firstDate, exception.getInvalidityDate());

    firstDate.setYear(firstDate.getYear() + 1);
    assertTrue(firstDate.compareTo(exception.getInvalidityDate()) > 0);
}
 
Example #4
Source File: CertificateRevocationExceptionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testGetRevocationDate() throws Exception {
    CertificateRevokedException exception = getTestException();

    Date firstDate = exception.getRevocationDate();
    assertNotSame(firstDate, exception.getRevocationDate());

    firstDate.setYear(firstDate.getYear() + 1);
    assertTrue(firstDate.compareTo(exception.getRevocationDate()) > 0);
}
 
Example #5
Source File: CertificateRevocationExceptionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testGetExtensions() throws Exception {
    CertificateRevokedException original = getTestException();
    Map<String, Extension> extensions = original.getExtensions();
    assertNotSame(extensions, original.getExtensions());

    try {
        extensions.put("2.2.2.2", getReasonExtension());
        fail();
    } catch (UnsupportedOperationException expected) {
    }
}
 
Example #6
Source File: CertificateRevocationExceptionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private CertificateRevokedException getTestException() {
    HashMap<String, Extension> extensions = new HashMap<String, Extension>();
    // REASON_CODE
    extensions.put("2.5.29.21", getReasonExtension());
    extensions.put("2.5.29.24", getInvalidityExtension());
    return new CertificateRevokedException(
                    new Date(1199226851000L),
                    CRLReason.CESSATION_OF_OPERATION,
                    new X500Principal("CN=test1"),
                    extensions);
}
 
Example #7
Source File: TmchXmlSignatureTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testRevokedTmvTmvrevokedTreatystatuteAgentEnglishActive() {
  smdData = loadSmd("revoked/tmv/TMVRevoked-TreatyStatute-Agent-English-Active.smd");
  CertificateRevokedException e =
      assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData));
  assertThat(e).hasMessageThat().contains("KEY_COMPROMISE");
}
 
Example #8
Source File: TmchXmlSignatureTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testRevokedTmvTmvrevokedTreatystatuteAgentChineseActive() {
  smdData = loadSmd("revoked/tmv/TMVRevoked-TreatyStatute-Agent-Chinese-Active.smd");
  CertificateRevokedException e =
      assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData));
  assertThat(e).hasMessageThat().contains("KEY_COMPROMISE");
}
 
Example #9
Source File: TmchXmlSignatureTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testRevokedTmvTmvrevokedTrademarkAgentRussianActive() {
  smdData = loadSmd("revoked/tmv/TMVRevoked-Trademark-Agent-Russian-Active.smd");
  CertificateRevokedException e =
      assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData));
  assertThat(e).hasMessageThat().contains("Certificate has been revoked");
}
 
Example #10
Source File: TmchXmlSignatureTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testRevokedTmvTmvrevokedTrademarkAgentEnglishActive() {
  smdData = loadSmd("revoked/tmv/TMVRevoked-Trademark-Agent-English-Active.smd");
  CertificateRevokedException e =
      assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData));
  assertThat(e).hasMessageThat().contains("Certificate has been revoked");
}
 
Example #11
Source File: TmchXmlSignatureTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testRevokedTmvTmvrevokedCourtAgentFrenchActive() {
  smdData = loadSmd("revoked/tmv/TMVRevoked-Court-Agent-French-Active.smd");
  CertificateRevokedException e =
      assertThrows(CertificateRevokedException.class, () -> tmchXmlSignature.verify(smdData));
  assertThat(e).hasMessageThat().contains("KEY_COMPROMISE");
}
 
Example #12
Source File: TmchCertificateAuthorityTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailure_verifyRevoked() {
  TmchCertificateAuthority tmchCertificateAuthority = new TmchCertificateAuthority(PILOT, clock);
  CertificateRevokedException thrown =
      assertThrows(
          CertificateRevokedException.class,
          () -> tmchCertificateAuthority.verify(loadCertificate(REVOKED_TEST_CERTIFICATE)));
  assertThat(thrown).hasMessageThat().contains("revoked, reason: KEY_COMPROMISE");
}
 
Example #13
Source File: X509Utils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Check that {@code cert} is signed by the {@code ca} and not revoked.
 *
 * <p>Support for certificate chains has not been implemented.
 *
 * @throws GeneralSecurityException for unsupported protocols, certs not signed by the TMCH,
 *         parsing errors, encoding errors, if the CRL is expired, or if the CRL is older than the
 *         one currently in memory.
 */
public static void verifyCertificate(
    X509Certificate rootCert, X509CRL crl, @Tainted X509Certificate cert, Date now)
        throws GeneralSecurityException {
  cert.checkValidity(checkNotNull(now, "now"));
  cert.verify(rootCert.getPublicKey());
  if (crl.isRevoked(cert)) {
    X509CRLEntry entry = crl.getRevokedCertificate(cert);
    throw new CertificateRevokedException(
        checkNotNull(entry.getRevocationDate(), "revocationDate"),
        Optional.ofNullable(entry.getRevocationReason()).orElse(CRLReason.UNSPECIFIED),
        firstNonNull(entry.getCertificateIssuer(), crl.getIssuerX500Principal()),
        ImmutableMap.of());
  }
}
 
Example #14
Source File: SslErrorTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Parameterized.Parameters(name = "{index}: serverProvider = {0}, clientProvider = {1}, exception = {2}")
public static Collection<Object[]> data() {
    List<SslProvider> serverProviders = new ArrayList<SslProvider>(2);
    List<SslProvider> clientProviders = new ArrayList<SslProvider>(3);

    if (OpenSsl.isAvailable()) {
        serverProviders.add(SslProvider.OPENSSL);
        serverProviders.add(SslProvider.OPENSSL_REFCNT);
        clientProviders.add(SslProvider.OPENSSL);
        clientProviders.add(SslProvider.OPENSSL_REFCNT);
    }
    // We not test with SslProvider.JDK on the server side as the JDK implementation currently just send the same
    // alert all the time, sigh.....
    clientProviders.add(SslProvider.JDK);

    List<CertificateException> exceptions = new ArrayList<CertificateException>(6);
    exceptions.add(new CertificateExpiredException());
    exceptions.add(new CertificateNotYetValidException());
    exceptions.add(new CertificateRevokedException(
            new Date(), CRLReason.AA_COMPROMISE, new X500Principal(""),
            Collections.<String, Extension>emptyMap()));

    // Also use wrapped exceptions as this is what the JDK implementation of X509TrustManagerFactory is doing.
    exceptions.add(newCertificateException(CertPathValidatorException.BasicReason.EXPIRED));
    exceptions.add(newCertificateException(CertPathValidatorException.BasicReason.NOT_YET_VALID));
    exceptions.add(newCertificateException(CertPathValidatorException.BasicReason.REVOKED));

    List<Object[]> params = new ArrayList<Object[]>();
    for (SslProvider serverProvider: serverProviders) {
        for (SslProvider clientProvider: clientProviders) {
            for (CertificateException exception: exceptions) {
                params.add(new Object[] { serverProvider, clientProvider, exception});
            }
        }
    }
    return params;
}
 
Example #15
Source File: CertificateValidatorTest.java    From deprecated-security-ssl with Apache License 2.0 5 votes vote down vote up
@Test
public void testStaticCRL() throws Exception {
    
    File staticCrl = getAbsoluteFilePathFromClassPath("crl/revoked.crl");
    Collection<? extends CRL> crls = null;
    try(FileInputStream crlin = new FileInputStream(staticCrl)) {
        crls = CertificateFactory.getInstance("X.509").generateCRLs(crlin);
    }
    
    Assert.assertEquals(crls.size(), 1);
    
    //trust chain incl intermediate certificates (root + intermediates)
    Collection<? extends Certificate> rootCas;
    final File trustedCas = getAbsoluteFilePathFromClassPath("chain-ca.pem");
    try(FileInputStream trin = new FileInputStream(trustedCas)) {
        rootCas =  (Collection<? extends Certificate>) CertificateFactory.getInstance("X.509").generateCertificates(trin);
    }
    
    Assert.assertEquals(rootCas.size(), 2);

    //certificate chain to validate (client cert + intermediates but without root)
    Collection<? extends Certificate> certsToValidate;
    final File certs = getAbsoluteFilePathFromClassPath("crl/revoked.crt.pem");
    try(FileInputStream trin = new FileInputStream(certs)) {
        certsToValidate =  (Collection<? extends Certificate>) CertificateFactory.getInstance("X.509").generateCertificates(trin);
    }
    
    Assert.assertEquals(certsToValidate.size(), 2);
    
    CertificateValidator validator = new CertificateValidator(rootCas.toArray(new X509Certificate[0]), crls);
    validator.setDate(CRL_DATE);
    try {
        validator.validate(certsToValidate.toArray(new X509Certificate[0]));
        Assert.fail();
    } catch (CertificateException e) {
        Assert.assertTrue(ExceptionUtils.getRootCause(e) instanceof CertificateRevokedException);
    }
}
 
Example #16
Source File: ReferenceCountedOpenSslContext.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
@Override
public final int verify(long ssl, byte[][] chain, String auth) {
    X509Certificate[] peerCerts = certificates(chain);
    final ReferenceCountedOpenSslEngine engine = engineMap.get(ssl);
    try {
        verify(engine, peerCerts, auth);
        return CertificateVerifier.X509_V_OK;
    } catch (Throwable cause) {
        logger.debug("verification of certificate failed", cause);
        SSLHandshakeException e = new SSLHandshakeException("General OpenSslEngine problem");
        e.initCause(cause);
        engine.handshakeException = e;

        // Try to extract the correct error code that should be used.
        if (cause instanceof OpenSslCertificateException) {
            // This will never return a negative error code as its validated when constructing the
            // OpenSslCertificateException.
            return ((OpenSslCertificateException) cause).errorCode();
        }
        if (cause instanceof CertificateExpiredException) {
            return CertificateVerifier.X509_V_ERR_CERT_HAS_EXPIRED;
        }
        if (cause instanceof CertificateNotYetValidException) {
            return CertificateVerifier.X509_V_ERR_CERT_NOT_YET_VALID;
        }
        if (PlatformDependent.javaVersion() >= 7) {
            if (cause instanceof CertificateRevokedException) {
                return CertificateVerifier.X509_V_ERR_CERT_REVOKED;
            }

            // The X509TrustManagerImpl uses a Validator which wraps a CertPathValidatorException into
            // an CertificateException. So we need to handle the wrapped CertPathValidatorException to be
            // able to send the correct alert.
            Throwable wrapped = cause.getCause();
            while (wrapped != null) {
                if (wrapped instanceof CertPathValidatorException) {
                    CertPathValidatorException ex = (CertPathValidatorException) wrapped;
                    CertPathValidatorException.Reason reason = ex.getReason();
                    if (reason == CertPathValidatorException.BasicReason.EXPIRED) {
                        return CertificateVerifier.X509_V_ERR_CERT_HAS_EXPIRED;
                    }
                    if (reason == CertPathValidatorException.BasicReason.NOT_YET_VALID) {
                        return CertificateVerifier.X509_V_ERR_CERT_NOT_YET_VALID;
                    }
                    if (reason == CertPathValidatorException.BasicReason.REVOKED) {
                        return CertificateVerifier.X509_V_ERR_CERT_REVOKED;
                    }
                }
                wrapped = wrapped.getCause();
            }
        }

        // Could not detect a specific error code to use, so fallback to a default code.
        return CertificateVerifier.X509_V_ERR_UNSPECIFIED;
    }
}
 
Example #17
Source File: CertificateRevocationExceptionTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testGetAuthorityName() throws Exception {
    CertificateRevokedException exception = getTestException();
    assertEquals(new X500Principal("CN=test1"), exception.getAuthorityName());
}
 
Example #18
Source File: SparkTrustManager.java    From Spark with Apache License 2.0 4 votes vote down vote up
/**
 * Validate certificate path
 * 
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws InvalidAlgorithmParameterException
 * @throws CertPathValidatorException
 * @throws CertPathBuilderException
 * @throws CertificateException
 */
private void validatePath(X509Certificate[] chain)
        throws NoSuchAlgorithmException, KeyStoreException, InvalidAlgorithmParameterException,
        CertPathValidatorException, CertPathBuilderException, CertificateException {
    // PKIX algorithm is defined in rfc3280
    CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX");
    CertPathBuilder certPathBuilder = CertPathBuilder.getInstance("PKIX");

    X509CertSelector certSelector = new X509CertSelector();

    // set last certificate (often root CA) from chain for CertSelector so trust store must contain it
    certSelector.setCertificate(chain[chain.length - 1]);

    // checks against time validity aren't done here as are already done in checkDateValidity (X509Certificate[]
    // chain)
    certSelector.setCertificateValid(null);
    // create parameters using trustStore as source of Trust Anchors and using X509CertSelector
    PKIXBuilderParameters parameters = new PKIXBuilderParameters(allStore, certSelector);

    // will use PKIXRevocationChecker (or nothing if revocation mechanisms are
    // disabled) instead of the default revocation checker
    parameters.setRevocationEnabled(false);   

    // if revoked certificates aren't accepted, but no revocation checks then only
    // certificates from blacklist will be rejected
    if (acceptRevoked == false) {
        
        // OCSP checking is done according to Java PKI Programmer's Guide, PKIXRevocationChecker was added in Java 8:
        // https://docs.oracle.com/javase/8/docs/technotes/guides/security/certpath/CertPathProgGuide.html#PKIXRevocationChecker
        PKIXRevocationChecker checker = (PKIXRevocationChecker) certPathBuilder.getRevocationChecker();

        EnumSet<PKIXRevocationChecker.Option> checkerOptions = EnumSet.noneOf(PKIXRevocationChecker.Option.class);
        // if soft fail isn't enabled then OCSP or CRL must pass validation, in case
        // when any of them cannot be validated verification will fail, if soft fail
        // is enabled then in case of network issues revocation checking is omitted
        if (allowSoftFail) {
            checkerOptions.add(PKIXRevocationChecker.Option.SOFT_FAIL);
        }
        // check OCSP, CRL serve as backup
        if (checkOCSP && checkCRL) {
            checker.setOptions(checkerOptions);
            parameters.addCertPathChecker(checker);
        } else if (!checkOCSP && checkCRL) {
            // check only CRL, if CRL fail then there is no fallback to OCSP
            checkerOptions.add(PKIXRevocationChecker.Option.PREFER_CRLS);
            checkerOptions.add(PKIXRevocationChecker.Option.NO_FALLBACK);
            checker.setOptions(checkerOptions);
            parameters.addCertPathChecker(checker);
        }
                    
    }
    
    try {
        CertPathBuilderResult pathResult = certPathBuilder.build(parameters);
        CertPath certPath = pathResult.getCertPath();

        PKIXCertPathValidatorResult validationResult = (PKIXCertPathValidatorResult) certPathValidator
                .validate(certPath, parameters);
        X509Certificate trustedCert = validationResult.getTrustAnchor().getTrustedCert();

        if (trustedCert == null) {
            throw new CertificateException("certificate path failed: Trusted CA is NULL");
        }
        // check if all certificates in path have Basic Constraints, only certificate that isn't required to have
        // this extension is last certificate: root CA
        for (int i = 0; i < chain.length - 1; i++) {
            checkBasicConstraints(chain[i]);
        }
    } catch (CertificateRevokedException e) {
        Log.warning("Certificate was revoked", e);
        for (X509Certificate cert : chain) {
            for (X509CRL crl : crlCollection) {
                if (crl.isRevoked(cert)) {
                    try {
                        addToBlackList(cert);
                    } catch (IOException | HeadlessException | InvalidNameException e1) {
                        Log.error("Couldn't move to the blacklist", e1);
                    }
                    break;
                }
            }
        }
        throw new CertificateException("Certificate was revoked");
    }
}