Search in sources :

Example 11 with Time

use of org.bouncycastle.asn1.x509.Time in project keycloak by keycloak.

the class CRLUtils method check.

/**
 * Check the signature on CRL and check if 1st certificate from the chain ((The actual certificate from the client)) is valid and not available on CRL.
 *
 * @param certs The 1st certificate is the actual certificate of the user. The other certificates represents the certificate chain
 * @param crl Given CRL
 * @throws GeneralSecurityException if some error in validation happens. Typically certificate not valid, or CRL signature not valid
 */
public static void check(X509Certificate[] certs, X509CRL crl, KeycloakSession session) throws GeneralSecurityException {
    if (certs.length < 2) {
        throw new GeneralSecurityException("Not possible to verify signature on CRL. X509 certificate doesn't have CA chain available on it");
    }
    X500Principal crlIssuerPrincipal = crl.getIssuerX500Principal();
    X509Certificate crlSignatureCertificate = null;
    // Try to find the certificate in the CA chain, which was used to sign the CRL
    for (int i = 1; i < certs.length; i++) {
        X509Certificate currentCACert = certs[i];
        if (crlIssuerPrincipal.equals(currentCACert.getSubjectX500Principal())) {
            crlSignatureCertificate = currentCACert;
            log.tracef("Found certificate used to sign CRL in the CA chain of the certificate. CRL issuer: %s", crlIssuerPrincipal);
            break;
        }
    }
    // Try to find the CRL issuer certificate in the truststore
    if (crlSignatureCertificate == null) {
        log.tracef("Not found CRL issuer '%s' in the CA chain of the certificate. Fallback to lookup CRL issuer in the truststore", crlIssuerPrincipal);
        crlSignatureCertificate = findCRLSignatureCertificateInTruststore(session, certs, crlIssuerPrincipal);
    }
    // Verify signature on CRL
    // TODO: It will be nice to cache CRLs and also verify their signatures just once at the time when CRL is loaded, rather than in every request
    crl.verify(crlSignatureCertificate.getPublicKey());
    // Finally check if
    if (crl.isRevoked(certs[0])) {
        String message = String.format("Certificate has been revoked, certificate's subject: %s", certs[0].getSubjectDN().getName());
        log.debug(message);
        throw new GeneralSecurityException(message);
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) X500Principal(javax.security.auth.x500.X500Principal) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) X509Certificate(java.security.cert.X509Certificate) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Example 12 with Time

use of org.bouncycastle.asn1.x509.Time in project keystore-explorer by kaikramer.

the class JarSigner method createSignatureBlock.

private static byte[] createSignatureBlock(byte[] toSign, PrivateKey privateKey, X509Certificate[] certificateChain, SignatureType signatureType, String tsaUrl, Provider provider) throws CryptoException {
    try {
        List<X509Certificate> certList = new ArrayList<>();
        Collections.addAll(certList, certificateChain);
        DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
        JcaContentSignerBuilder csb = new JcaContentSignerBuilder(signatureType.jce()).setSecureRandom(SecureRandom.getInstance("SHA1PRNG"));
        if (provider != null) {
            csb.setProvider(provider);
        }
        JcaSignerInfoGeneratorBuilder siGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digCalcProv);
        // remove cmsAlgorithmProtect for compatibility reasons
        SignerInfoGenerator sigGen = siGeneratorBuilder.build(csb.build(privateKey), certificateChain[0]);
        final CMSAttributeTableGenerator sAttrGen = sigGen.getSignedAttributeTableGenerator();
        sigGen = new SignerInfoGenerator(sigGen, new DefaultSignedAttributeTableGenerator() {

            @Override
            public AttributeTable getAttributes(@SuppressWarnings("rawtypes") Map parameters) {
                AttributeTable ret = sAttrGen.getAttributes(parameters);
                return ret.remove(CMSAttributes.cmsAlgorithmProtect);
            }
        }, sigGen.getUnsignedAttributeTableGenerator());
        CMSSignedDataGenerator dataGen = new CMSSignedDataGenerator();
        dataGen.addSignerInfoGenerator(sigGen);
        dataGen.addCertificates(new JcaCertStore(certList));
        CMSSignedData signedData = dataGen.generate(new CMSProcessableByteArray(toSign), true);
        // now let TSA time-stamp the signature
        if (tsaUrl != null && !tsaUrl.isEmpty()) {
            signedData = addTimestamp(tsaUrl, signedData);
        }
        return signedData.getEncoded();
    } catch (Exception ex) {
        throw new CryptoException(res.getString("SignatureBlockCreationFailed.exception.message"), ex);
    }
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) DefaultSignedAttributeTableGenerator(org.bouncycastle.cms.DefaultSignedAttributeTableGenerator) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) CryptoException(org.kse.crypto.CryptoException) IOException(java.io.IOException) JcaSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) CMSAttributeTableGenerator(org.bouncycastle.cms.CMSAttributeTableGenerator) SignerInfoGenerator(org.bouncycastle.cms.SignerInfoGenerator) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) CryptoException(org.kse.crypto.CryptoException) Map(java.util.Map)

Example 13 with Time

use of org.bouncycastle.asn1.x509.Time in project keystore-explorer by kaikramer.

the class Asn1Dump method dumpGeneralizedTime.

private String dumpGeneralizedTime(ASN1GeneralizedTime asn1Time) {
    StringBuilder sb = new StringBuilder();
    sb.append(indentSequence.toString(indentLevel));
    sb.append("GENERALIZED TIME=");
    Date date;
    try {
        date = asn1Time.getDate();
    } catch (ParseException e) {
        throw new RuntimeException("Cannot parse generalized time");
    }
    String formattedDate = new SimpleDateFormat("dd/MMM/yyyy HH:mm:ss.SSS z").format(date);
    sb.append(formattedDate);
    sb.append(" (");
    sb.append(asn1Time.getTime());
    sb.append(")");
    sb.append(NEWLINE);
    return sb.toString();
}
Also used : ParseException(java.text.ParseException) DERNumericString(org.bouncycastle.asn1.DERNumericString) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) DERGeneralString(org.bouncycastle.asn1.DERGeneralString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERT61String(org.bouncycastle.asn1.DERT61String) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERVisibleString(org.bouncycastle.asn1.DERVisibleString) ASN1String(org.bouncycastle.asn1.ASN1String) DERUniversalString(org.bouncycastle.asn1.DERUniversalString) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 14 with Time

use of org.bouncycastle.asn1.x509.Time in project keystore-explorer by kaikramer.

the class Asn1Dump method dumpUTCTime.

private String dumpUTCTime(ASN1UTCTime asn1Time) {
    StringBuilder sb = new StringBuilder();
    sb.append(indentSequence.toString(indentLevel));
    sb.append("UTC TIME=");
    // UTCTime, note does not support ms precision hence the different date format
    Date date;
    try {
        date = asn1Time.getDate();
    } catch (ParseException e) {
        throw new RuntimeException("Cannot parse utc time");
    }
    String formattedDate = new SimpleDateFormat("dd/MMM/yyyy HH:mm:ss z").format(date);
    sb.append(formattedDate);
    sb.append(" (");
    sb.append(asn1Time.getTime());
    sb.append(")");
    sb.append(NEWLINE);
    return sb.toString();
}
Also used : ParseException(java.text.ParseException) DERNumericString(org.bouncycastle.asn1.DERNumericString) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) DERGeneralString(org.bouncycastle.asn1.DERGeneralString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERT61String(org.bouncycastle.asn1.DERT61String) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERVisibleString(org.bouncycastle.asn1.DERVisibleString) ASN1String(org.bouncycastle.asn1.ASN1String) DERUniversalString(org.bouncycastle.asn1.DERUniversalString) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Example 15 with Time

use of org.bouncycastle.asn1.x509.Time in project Spark by igniterealtime.

the class SparkTrustManager method validatePath.

/**
 * 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);
    // 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);
        // 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");
        }
        // 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");
    }
}
Also used : X509CRL(java.security.cert.X509CRL) PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) CertificateRevokedException(java.security.cert.CertificateRevokedException) CertPathBuilderResult(java.security.cert.CertPathBuilderResult) X509CertSelector(java.security.cert.X509CertSelector) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) CertPathValidator(java.security.cert.CertPathValidator) PKIXCertPathValidatorResult(java.security.cert.PKIXCertPathValidatorResult) PKIXRevocationChecker(java.security.cert.PKIXRevocationChecker) CertPathBuilder(java.security.cert.CertPathBuilder) CertPath(java.security.cert.CertPath)

Aggregations

Date (java.util.Date)26 IOException (java.io.IOException)20 X509Certificate (java.security.cert.X509Certificate)20 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)19 BigInteger (java.math.BigInteger)18 DEROctetString (org.bouncycastle.asn1.DEROctetString)16 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)14 DERIA5String (org.bouncycastle.asn1.DERIA5String)12 X500Name (org.bouncycastle.asn1.x500.X500Name)11 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)11 Calendar (java.util.Calendar)9 ASN1GeneralizedTime (org.bouncycastle.asn1.ASN1GeneralizedTime)8 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)8 Time (org.bouncycastle.asn1.x509.Time)8 ArrayList (java.util.ArrayList)7 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)7 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)7 ASN1TaggedObject (org.bouncycastle.asn1.ASN1TaggedObject)6 Extension (org.bouncycastle.asn1.x509.Extension)6 ASN1EncodableVector (com.android.org.bouncycastle.asn1.ASN1EncodableVector)5