Example usage for org.bouncycastle.asn1.ocsp OCSPObjectIdentifiers id_pkix_ocsp_nocheck

List of usage examples for org.bouncycastle.asn1.ocsp OCSPObjectIdentifiers id_pkix_ocsp_nocheck

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.ocsp OCSPObjectIdentifiers id_pkix_ocsp_nocheck.

Prototype

ASN1ObjectIdentifier id_pkix_ocsp_nocheck

To view the source code for org.bouncycastle.asn1.ocsp OCSPObjectIdentifiers id_pkix_ocsp_nocheck.

Click Source Link

Document

OID: 1.3.6.1.5.5.7.48.1.5

Usage

From source file:be.fedict.trust.ocsp.OcspTrustLinker.java

License:Open Source License

@Override
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy)
        throws TrustLinkerResultException, Exception {
    URI ocspUri = getOcspUri(childCertificate);
    if (null == ocspUri) {
        return TrustLinkerResult.UNDECIDED;
    }/* ww w  .  ja  va 2s.c o  m*/
    LOG.debug("OCSP URI: " + ocspUri);

    OCSPResp ocspResp = this.ocspRepository.findOcspResponse(ocspUri, childCertificate, certificate,
            validationDate);
    if (null == ocspResp) {
        LOG.debug("OCSP response not found");
        return TrustLinkerResult.UNDECIDED;
    }

    int ocspRespStatus = ocspResp.getStatus();
    if (OCSPResponseStatus.SUCCESSFUL != ocspRespStatus) {
        LOG.debug("OCSP response status: " + ocspRespStatus);
        return TrustLinkerResult.UNDECIDED;
    }

    Object responseObject = ocspResp.getResponseObject();
    BasicOCSPResp basicOCSPResp = (BasicOCSPResp) responseObject;

    X509CertificateHolder[] responseCertificates = basicOCSPResp.getCerts();
    for (X509CertificateHolder responseCertificate : responseCertificates) {
        LOG.debug("OCSP response cert: " + responseCertificate.getSubject());
        LOG.debug("OCSP response cert issuer: " + responseCertificate.getIssuer());
    }

    algorithmPolicy.checkSignatureAlgorithm(basicOCSPResp.getSignatureAlgOID().getId(), validationDate);

    if (0 == responseCertificates.length) {
        /*
         * This means that the OCSP response has been signed by the issuing
         * CA itself.
         */
        ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(certificate.getPublicKey());
        boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider);
        if (false == verificationResult) {
            LOG.debug("OCSP response signature invalid");
            return TrustLinkerResult.UNDECIDED;
        }
    } else {
        /*
         * We're dealing with a dedicated authorized OCSP Responder
         * certificate, or of course with a CA that issues the OCSP
         * Responses itself.
         */

        X509CertificateHolder ocspResponderCertificate = responseCertificates[0];
        ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(ocspResponderCertificate);

        boolean verificationResult = basicOCSPResp.isSignatureValid(contentVerifierProvider);
        if (false == verificationResult) {
            LOG.debug("OCSP Responser response signature invalid");
            return TrustLinkerResult.UNDECIDED;
        }
        if (false == Arrays.equals(certificate.getEncoded(), ocspResponderCertificate.getEncoded())) {
            // check certificate signature algorithm
            algorithmPolicy.checkSignatureAlgorithm(
                    ocspResponderCertificate.getSignatureAlgorithm().getAlgorithm().getId(), validationDate);

            X509Certificate issuingCaCertificate;
            if (responseCertificates.length < 2) {
                // so the OCSP certificate chain only contains a single
                // entry
                LOG.debug("OCSP responder complete certificate chain missing");
                /*
                 * Here we assume that the OCSP Responder is directly signed
                 * by the CA.
                 */
                issuingCaCertificate = certificate;
            } else {
                CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
                issuingCaCertificate = (X509Certificate) certificateFactory
                        .generateCertificate(new ByteArrayInputStream(responseCertificates[1].getEncoded()));
                /*
                 * Is next check really required?
                 */
                if (false == certificate.equals(issuingCaCertificate)) {
                    LOG.debug("OCSP responder certificate not issued by CA");
                    return TrustLinkerResult.UNDECIDED;
                }
            }
            // check certificate signature
            algorithmPolicy.checkSignatureAlgorithm(issuingCaCertificate.getSigAlgOID(), validationDate);

            PublicKeyTrustLinker publicKeyTrustLinker = new PublicKeyTrustLinker();
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate x509OcspResponderCertificate = (X509Certificate) certificateFactory
                    .generateCertificate(new ByteArrayInputStream(ocspResponderCertificate.getEncoded()));
            LOG.debug("OCSP Responder public key fingerprint: "
                    + DigestUtils.sha1Hex(x509OcspResponderCertificate.getPublicKey().getEncoded()));
            publicKeyTrustLinker.hasTrustLink(x509OcspResponderCertificate, issuingCaCertificate,
                    validationDate, revocationData, algorithmPolicy);
            if (null == x509OcspResponderCertificate
                    .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId())) {
                LOG.debug("OCSP Responder certificate should have id-pkix-ocsp-nocheck");
                /*
                 * TODO: perform CRL validation on the OCSP Responder
                 * certificate. On the other hand, do we really want to
                 * check the checker?
                 */
                return TrustLinkerResult.UNDECIDED;
            }
            List<String> extendedKeyUsage = x509OcspResponderCertificate.getExtendedKeyUsage();
            if (null == extendedKeyUsage) {
                LOG.debug("OCSP Responder certificate has no extended key usage extension");
                return TrustLinkerResult.UNDECIDED;
            }
            if (false == extendedKeyUsage.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) {
                LOG.debug("OCSP Responder certificate should have a OCSPSigning extended key usage");
                return TrustLinkerResult.UNDECIDED;
            }
        } else {
            LOG.debug("OCSP Responder certificate equals the CA certificate");
            // and the CA certificate is already trusted at this point
        }
    }

    DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build();
    CertificateID certificateId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1),
            new JcaX509CertificateHolder(certificate), childCertificate.getSerialNumber());

    SingleResp[] singleResps = basicOCSPResp.getResponses();
    for (SingleResp singleResp : singleResps) {
        CertificateID responseCertificateId = singleResp.getCertID();
        if (false == certificateId.equals(responseCertificateId)) {
            continue;
        }
        DateTime thisUpdate = new DateTime(singleResp.getThisUpdate());
        DateTime nextUpdate;
        if (null != singleResp.getNextUpdate()) {
            nextUpdate = new DateTime(singleResp.getNextUpdate());
        } else {
            LOG.debug("no OCSP nextUpdate");
            nextUpdate = thisUpdate;
        }
        LOG.debug("OCSP thisUpdate: " + thisUpdate);
        LOG.debug("(OCSP) nextUpdate: " + nextUpdate);
        DateTime beginValidity = thisUpdate.minus(this.freshnessInterval);
        DateTime endValidity = nextUpdate.plus(this.freshnessInterval);
        DateTime validationDateTime = new DateTime(validationDate);
        if (validationDateTime.isBefore(beginValidity)) {
            LOG.warn("OCSP response not yet valid");
            continue;
        }
        if (validationDateTime.isAfter(endValidity)) {
            LOG.warn("OCSP response expired");
            continue;
        }
        if (null == singleResp.getCertStatus()) {
            LOG.debug("OCSP OK for: " + childCertificate.getSubjectX500Principal());
            addRevocationData(revocationData, ocspResp, ocspUri);
            return TrustLinkerResult.TRUSTED;
        } else {
            LOG.debug("OCSP certificate status: " + singleResp.getCertStatus().getClass().getName());
            if (singleResp.getCertStatus() instanceof RevokedStatus) {
                LOG.debug("OCSP status revoked");
            }
            addRevocationData(revocationData, ocspResp, ocspUri);
            throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
                    "certificate revoked by OCSP");
        }
    }

    LOG.debug("no matching OCSP response entry");
    return TrustLinkerResult.UNDECIDED;
}

From source file:be.fedict.trust.test.PKITestUtils.java

License:Open Source License

public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn,
        DateTime notBefore, DateTime notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey,
        boolean caFlag, int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage,
        String signatureAlgorithm, boolean tsa, boolean includeSKID, boolean includeAKID,
        PublicKey akidPublicKey, String certificatePolicy, Boolean qcCompliance, boolean ocspResponder,
        boolean qcSSCD) throws IOException, InvalidKeyException, IllegalStateException,
        NoSuchAlgorithmException, SignatureException, CertificateException, OperatorCreationException {

    X500Name issuerName;//from w  w  w  .j a  v a 2 s  .  c  o m
    if (null != issuerCertificate) {
        issuerName = new X500Name(issuerCertificate.getSubjectX500Principal().toString());
    } else {
        issuerName = new X500Name(subjectDn);
    }
    X500Name subjectName = new X500Name(subjectDn);
    BigInteger serial = new BigInteger(128, new SecureRandom());
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuerName, serial,
            notBefore.toDate(), notAfter.toDate(), subjectName, publicKeyInfo);

    JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
    if (includeSKID) {
        x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                extensionUtils.createSubjectKeyIdentifier(subjectPublicKey));
    }

    if (includeAKID) {

        PublicKey authorityPublicKey;
        if (null != akidPublicKey) {
            authorityPublicKey = akidPublicKey;
        } else if (null != issuerCertificate) {
            authorityPublicKey = issuerCertificate.getPublicKey();
        } else {
            authorityPublicKey = subjectPublicKey;
        }
        x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                extensionUtils.createAuthorityKeyIdentifier(authorityPublicKey));
    }

    if (caFlag) {
        if (-1 == pathLength) {
            x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true,
                    new BasicConstraints(2147483647));
        } else {
            x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true,
                    new BasicConstraints(pathLength));
        }
    }

    if (null != crlUri) {
        GeneralName generalName = new GeneralName(GeneralName.uniformResourceIdentifier,
                new DERIA5String(crlUri));
        GeneralNames generalNames = new GeneralNames(generalName);
        DistributionPointName distPointName = new DistributionPointName(generalNames);
        DistributionPoint distPoint = new DistributionPoint(distPointName, null, null);
        DistributionPoint[] crlDistPoints = new DistributionPoint[] { distPoint };
        CRLDistPoint crlDistPoint = new CRLDistPoint(crlDistPoints);
        x509v3CertificateBuilder.addExtension(Extension.cRLDistributionPoints, false, crlDistPoint);
    }

    if (null != ocspUri) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        x509v3CertificateBuilder.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    if (null != keyUsage) {
        x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, keyUsage);
    }

    if (null != certificatePolicy) {
        ASN1ObjectIdentifier policyObjectIdentifier = new ASN1ObjectIdentifier(certificatePolicy);
        PolicyInformation policyInformation = new PolicyInformation(policyObjectIdentifier);
        x509v3CertificateBuilder.addExtension(Extension.certificatePolicies, false,
                new DERSequence(policyInformation));
    }

    if (null != qcCompliance) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        if (qcCompliance) {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_QcCompliance));
        } else {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_RetentionPeriod));
        }
        if (qcSSCD) {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_QcSSCD));
        }
        x509v3CertificateBuilder.addExtension(Extension.qCStatements, true, new DERSequence(vec));

    }

    if (tsa) {
        x509v3CertificateBuilder.addExtension(Extension.extendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));
    }

    if (ocspResponder) {
        x509v3CertificateBuilder.addExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck, false,
                DERNull.INSTANCE);

        x509v3CertificateBuilder.addExtension(Extension.extendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_OCSPSigning));
    }

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.createKey(issuerPrivateKey.getEncoded());

    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(asymmetricKeyParameter);
    X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate = x509CertificateHolder.getEncoded();

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    return certificate;
}

From source file:com.itextpdf.signatures.OCSPVerifier.java

License:Open Source License

/**
 * Verifies if an OCSP response is genuine
 * If it doesn't verify against the issuer certificate and response's certificates, it may verify
 * using a trusted anchor or cert.//from w  w w .  ja v  a 2  s.  com
 * @param ocspResp the OCSP response
 * @param issuerCert the issuer certificate
 * @throws GeneralSecurityException
 * @throws IOException
 */
public void isValidResponse(BasicOCSPResp ocspResp, X509Certificate issuerCert)
        throws GeneralSecurityException, IOException {
    //OCSP response might be signed by the issuer certificate or
    //the Authorized OCSP responder certificate containing the id-kp-OCSPSigning extended key usage extension
    X509Certificate responderCert = null;

    //first check if the issuer certificate signed the response
    //since it is expected to be the most common case
    if (isSignatureValid(ocspResp, issuerCert)) {
        responderCert = issuerCert;
    }

    //if the issuer certificate didn't sign the ocsp response, look for authorized ocsp responses
    // from properties or from certificate chain received with response
    if (responderCert == null) {
        if (ocspResp.getCerts() != null) {
            //look for existence of Authorized OCSP responder inside the cert chain in ocsp response
            Iterable<X509Certificate> certs = SignUtils.getCertsFromOcspResponse(ocspResp);
            for (X509Certificate cert : certs) {
                List keyPurposes = null;
                try {
                    keyPurposes = cert.getExtendedKeyUsage();
                    if ((keyPurposes != null) && keyPurposes.contains(id_kp_OCSPSigning)
                            && isSignatureValid(ocspResp, cert)) {
                        responderCert = cert;
                        break;
                    }
                } catch (CertificateParsingException ignored) {
                }
            }
            // Certificate signing the ocsp response is not found in ocsp response's certificate chain received
            // and is not signed by the issuer certificate.
            if (responderCert == null) {
                throw new VerificationException(issuerCert, "OCSP response could not be verified");
            }
        } else {
            //certificate chain is not present in response received
            //try to verify using rootStore
            if (rootStore != null) {
                try {
                    for (X509Certificate anchor : SignUtils.getCertificates(rootStore)) {
                        if (isSignatureValid(ocspResp, anchor)) {
                            responderCert = anchor;
                            break;
                        }
                    }
                } catch (Exception e) {
                    responderCert = (X509Certificate) null;
                }
            }

            // OCSP Response does not contain certificate chain, and response is not signed by any
            // of the rootStore or the issuer certificate.
            if (responderCert == null) {
                throw new VerificationException(issuerCert, "OCSP response could not be verified");
            }
        }
    }

    //check "This certificate MUST be issued directly by the CA that issued the certificate in question".
    responderCert.verify(issuerCert.getPublicKey());

    // validating ocsp signers certificate
    // Check if responders certificate has id-pkix-ocsp-nocheck extension,
    // in which case we do not validate (perform revocation check on) ocsp certs for lifetime of certificate
    if (responderCert.getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()) == null) {
        CRL crl;
        try {
            crl = CertificateUtil.getCRL(responderCert);
        } catch (Exception ignored) {
            crl = (CRL) null;
        }
        if (crl != null && crl instanceof X509CRL) {
            CRLVerifier crlVerifier = new CRLVerifier(null, null);
            crlVerifier.setRootStore(rootStore);
            crlVerifier.setOnlineCheckingAllowed(onlineCheckingAllowed);
            crlVerifier.verify((X509CRL) crl, responderCert, issuerCert, DateTimeUtil.getCurrentTimeDate());
            return;
        }
    }

    //check if lifetime of certificate is ok
    responderCert.checkValidity();
}

From source file:eu.europa.esig.dss.DSSASN1Utils.java

License:Open Source License

/**
 * Indicates if the revocation data should be checked for an OCSP signing certificate.<br>
 * http://www.ietf.org/rfc/rfc2560.txt?number=2560<br>
 * A CA may specify that an OCSP client can trust a responder for the lifetime of the responder's certificate. The
 * CA//from  www  .j  ava 2s. com
 * does so by including the extension id-pkix-ocsp-nocheck. This SHOULD be a non-critical extension. The value of
 * the
 * extension should be NULL.
 *
 * @return
 */
public static boolean hasIdPkixOcspNoCheckExtension(CertificateToken token) {
    final byte[] extensionValue = token.getCertificate()
            .getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId());
    if (extensionValue != null) {
        try {
            final ASN1Primitive derObject = toASN1Primitive(extensionValue);
            if (derObject instanceof DEROctetString) {
                return isDEROctetStringNull((DEROctetString) derObject);
            }
        } catch (Exception e) {
            LOG.debug("Exception when processing 'id_pkix_ocsp_no_check'", e);
        }
    }
    return false;
}

From source file:org.cesecore.certificates.certificate.certextensions.standard.OcspNoCheck.java

License:Open Source License

@Override
public void init(final CertificateProfile certProf) {
    super.setOID(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId());
    super.setCriticalFlag(false);
}

From source file:org.cesecore.certificates.certificateprofile.CertificateProfileTest.java

License:Open Source License

@Test
public void test06CertificateExtensions() throws Exception {
    CertificateProfile profile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_NO_PROFILE);

    // Check standard values for the certificate profile
    List<String> l = profile.getUsedStandardCertificateExtensions();
    assertEquals(6, l.size());//from   w  w w .  j av a  2  s  . c om
    assertTrue(l.contains(Extension.keyUsage.getId()));
    assertTrue(l.contains(Extension.basicConstraints.getId()));
    assertTrue(l.contains(Extension.subjectKeyIdentifier.getId()));
    assertTrue(l.contains(Extension.authorityKeyIdentifier.getId()));
    assertTrue(l.contains(Extension.subjectAlternativeName.getId()));
    assertTrue(l.contains(Extension.issuerAlternativeName.getId()));

    CertificateProfile eprofile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);

    // Check standard values for the certificate profile
    l = eprofile.getUsedStandardCertificateExtensions();
    assertEquals(7, l.size());
    assertTrue(l.contains(Extension.keyUsage.getId()));
    assertTrue(l.contains(Extension.basicConstraints.getId()));
    assertTrue(l.contains(Extension.subjectKeyIdentifier.getId()));
    assertTrue(l.contains(Extension.authorityKeyIdentifier.getId()));
    assertTrue(l.contains(Extension.subjectAlternativeName.getId()));
    assertTrue(l.contains(Extension.issuerAlternativeName.getId()));
    assertTrue(l.contains(Extension.extendedKeyUsage.getId()));

    profile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_NO_PROFILE);
    profile.setUseAuthorityInformationAccess(true);
    profile.setUseCertificatePolicies(true);
    profile.setUseCRLDistributionPoint(true);
    profile.setUseFreshestCRL(true);
    profile.setUseMicrosoftTemplate(true);
    profile.setUseOcspNoCheck(true);
    profile.setUseQCStatement(true);
    profile.setUseExtendedKeyUsage(true);
    profile.setUseSubjectDirAttributes(true);
    l = profile.getUsedStandardCertificateExtensions();
    assertEquals(15, l.size());
    assertTrue(l.contains(Extension.keyUsage.getId()));
    assertTrue(l.contains(Extension.basicConstraints.getId()));
    assertTrue(l.contains(Extension.subjectKeyIdentifier.getId()));
    assertTrue(l.contains(Extension.authorityKeyIdentifier.getId()));
    assertTrue(l.contains(Extension.subjectAlternativeName.getId()));
    assertTrue(l.contains(Extension.issuerAlternativeName.getId()));
    assertTrue(l.contains(Extension.extendedKeyUsage.getId()));
    assertTrue(l.contains(Extension.authorityInfoAccess.getId()));
    assertTrue(l.contains(Extension.certificatePolicies.getId()));
    assertTrue(l.contains(Extension.cRLDistributionPoints.getId()));
    assertTrue(l.contains(Extension.freshestCRL.getId()));
    assertTrue(l.contains(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()));
    assertTrue(l.contains(Extension.qCStatements.getId()));
    assertTrue(l.contains(Extension.subjectDirectoryAttributes.getId()));
    assertTrue(l.contains(CertTools.OID_MSTEMPLATE));
}

From source file:org.ejbca.core.model.ca.certificateprofiles.CertificateProfileTest.java

License:Open Source License

public void test09CertificateExtensions() throws Exception {
    log.trace(">test09CertificateExtensions()");

    CertificateProfile profile = new CertificateProfile();

    // Check standard values for the certificate profile
    List l = profile.getUsedStandardCertificateExtensions();
    assertEquals(l.size(), 5);//from  w w w  .j a va  2s. co m
    assertTrue(l.contains(X509Extensions.KeyUsage.getId()));
    assertTrue(l.contains(X509Extensions.BasicConstraints.getId()));
    assertTrue(l.contains(X509Extensions.SubjectKeyIdentifier.getId()));
    assertTrue(l.contains(X509Extensions.AuthorityKeyIdentifier.getId()));
    assertTrue(l.contains(X509Extensions.SubjectAlternativeName.getId()));

    CertificateProfile eprofile = new EndUserCertificateProfile();

    // Check standard values for the certificate profile
    l = eprofile.getUsedStandardCertificateExtensions();
    assertEquals(l.size(), 6);
    assertTrue(l.contains(X509Extensions.KeyUsage.getId()));
    assertTrue(l.contains(X509Extensions.BasicConstraints.getId()));
    assertTrue(l.contains(X509Extensions.SubjectKeyIdentifier.getId()));
    assertTrue(l.contains(X509Extensions.AuthorityKeyIdentifier.getId()));
    assertTrue(l.contains(X509Extensions.SubjectAlternativeName.getId()));
    assertTrue(l.contains(X509Extensions.ExtendedKeyUsage.getId()));

    profile = new CertificateProfile();
    profile.setUseAuthorityInformationAccess(true);
    profile.setUseCertificatePolicies(true);
    profile.setUseCRLDistributionPoint(true);
    profile.setUseFreshestCRL(true);
    profile.setUseMicrosoftTemplate(true);
    profile.setUseOcspNoCheck(true);
    profile.setUseQCStatement(true);
    profile.setUseExtendedKeyUsage(true);
    profile.setUseSubjectDirAttributes(true);
    l = profile.getUsedStandardCertificateExtensions();
    assertEquals(l.size(), 14);
    assertTrue(l.contains(X509Extensions.KeyUsage.getId()));
    assertTrue(l.contains(X509Extensions.BasicConstraints.getId()));
    assertTrue(l.contains(X509Extensions.SubjectKeyIdentifier.getId()));
    assertTrue(l.contains(X509Extensions.AuthorityKeyIdentifier.getId()));
    assertTrue(l.contains(X509Extensions.SubjectAlternativeName.getId()));
    assertTrue(l.contains(X509Extensions.ExtendedKeyUsage.getId()));
    assertTrue(l.contains(X509Extensions.AuthorityInfoAccess.getId()));
    assertTrue(l.contains(X509Extensions.CertificatePolicies.getId()));
    assertTrue(l.contains(X509Extensions.CRLDistributionPoints.getId()));
    assertTrue(l.contains(X509Extensions.FreshestCRL.getId()));
    assertTrue(l.contains(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()));
    assertTrue(l.contains(X509Extensions.QCStatements.getId()));
    assertTrue(l.contains(X509Extensions.SubjectDirectoryAttributes.getId()));
    assertTrue(l.contains(CertTools.OID_MSTEMPLATE));

}

From source file:org.ejbca.core.protocol.cmp.CrmfRAPbeMultipleKeyIdRequestTest.java

License:Open Source License

@Test
public void test07ExtensionOverride() throws Exception {

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    // Create some crazy extensions to see that we get them when using
    // extension override.
    // We should not get our values when not using extension override
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    // SubjectAltName
    GeneralNames san = CertTools.getGeneralNamesFromAltName("dnsName=foo.bar.com");
    extgen.addExtension(Extension.subjectAlternativeName, false, san);
    // KeyUsage/* w  w  w  .  jav a  2  s  .co m*/
    int bcku = 0;
    bcku = X509KeyUsage.decipherOnly;
    X509KeyUsage ku = new X509KeyUsage(bcku);
    extgen.addExtension(Extension.keyUsage, false, ku);
    // Extended Key Usage
    List<KeyPurposeId> usage = new ArrayList<KeyPurposeId>();
    usage.add(KeyPurposeId.id_kp_codeSigning);
    ExtendedKeyUsage eku = ExtendedKeyUsage.getInstance(usage);
    extgen.addExtension(Extension.extendedKeyUsage, false, eku);
    // OcspNoCheck
    extgen.addExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck, false, DERNull.INSTANCE);
    // Netscape cert type
    extgen.addExtension(new ASN1ObjectIdentifier("2.16.840.1.113730.1.1"), false,
            new NetscapeCertType(NetscapeCertType.objectSigningCA));
    // My completely own
    extgen.addExtension(new ASN1ObjectIdentifier("1.1.1.1.1"), false, new DERIA5String("PrimeKey"));

    // Make the complete extension package
    Extensions exts = extgen.generate();

    // First test without extension override
    PKIMessage one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, exts,
            null, null, null, null, null);
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId2", 567);

    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    assertNotNull(req);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId);
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("dNSName=foo.bar.com") != -1);

    // Check key usage that it is nonRepudiation for KeyId2
    boolean[] kubits = cert.getKeyUsage();
    assertFalse(kubits[0]);
    assertTrue(kubits[1]);
    assertFalse(kubits[2]);
    assertFalse(kubits[3]);
    assertFalse(kubits[4]);
    assertFalse(kubits[5]);
    assertFalse(kubits[6]);
    assertFalse(kubits[7]);
    assertFalse(kubits[8]);
    // Our own ext should not be here
    assertNull(cert.getExtensionValue("1.1.1.1.1"));
    assertNull(cert.getExtensionValue("2.16.840.1.113730.1.1"));
    assertNull(cert.getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()));

    // Skip confirmation message, we have tested that several times already

    //
    // Do the same with keyId4, that has full extension override
    one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, exts, null, null,
            null, null, null);
    req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId4", 567);

    ir = (CertReqMessages) req.getBody().getContent();
    reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    assertNotNull(req);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId);
    altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("dNSName=foo.bar.com") != -1);

    // Check key usage that it is decipherOnly for KeyId4
    kubits = cert.getKeyUsage();
    assertFalse(kubits[0]);
    assertFalse(kubits[1]);
    assertFalse(kubits[2]);
    assertFalse(kubits[3]);
    assertFalse(kubits[4]);
    assertFalse(kubits[5]);
    assertFalse(kubits[6]);
    assertFalse(kubits[7]);
    assertTrue(kubits[8]);
    // Our own ext should not be here
    assertNotNull(cert.getExtensionValue("1.1.1.1.1"));
    assertNotNull(cert.getExtensionValue("2.16.840.1.113730.1.1"));
    assertNotNull(cert.getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()));
    List<String> l = cert.getExtendedKeyUsage();
    assertEquals(1, l.size());
    String s = l.get(0);
    assertEquals(KeyPurposeId.id_kp_codeSigning.getId(), s);

    // Skip confirmation message, we have tested that several times already
}

From source file:org.keycloak.common.util.OCSPUtils.java

License:Apache License

private static void verifyResponse(BasicOCSPResp basicOcspResponse, X509Certificate issuerCertificate,
        X509Certificate responderCertificate, byte[] requestNonce, Date date)
        throws NoSuchProviderException, NoSuchAlgorithmException, CertificateNotYetValidException,
        CertificateExpiredException, CertPathValidatorException {

    List<X509CertificateHolder> certs = new ArrayList<>(Arrays.asList(basicOcspResponse.getCerts()));
    X509Certificate signingCert = null;

    try {//w  w w  .j  ava  2 s  .c  o m
        certs.add(new JcaX509CertificateHolder(issuerCertificate));
        if (responderCertificate != null) {
            certs.add(new JcaX509CertificateHolder(responderCertificate));
        }
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    }
    if (certs.size() > 0) {

        X500Name responderName = basicOcspResponse.getResponderId().toASN1Primitive().getName();
        byte[] responderKey = basicOcspResponse.getResponderId().toASN1Primitive().getKeyHash();

        if (responderName != null) {
            logger.log(Level.INFO, "Responder Name: {0}", responderName.toString());
            for (X509CertificateHolder certHolder : certs) {
                try {
                    X509Certificate tempCert = new JcaX509CertificateConverter().setProvider("BC")
                            .getCertificate(certHolder);
                    X500Name respName = new X500Name(tempCert.getSubjectX500Principal().getName());
                    if (responderName.equals(respName)) {
                        signingCert = tempCert;
                        logger.log(Level.INFO,
                                "Found a certificate whose principal \"{0}\" matches the responder name \"{1}\"",
                                new Object[] { tempCert.getSubjectDN().getName(), responderName.toString() });
                        break;
                    }
                } catch (CertificateException e) {
                    logger.log(Level.FINE, e.getMessage());
                }
            }
        } else if (responderKey != null) {
            SubjectKeyIdentifier responderSubjectKey = new SubjectKeyIdentifier(responderKey);
            logger.log(Level.INFO, "Responder Key: {0}", Arrays.toString(responderKey));
            for (X509CertificateHolder certHolder : certs) {
                try {
                    X509Certificate tempCert = new JcaX509CertificateConverter().setProvider("BC")
                            .getCertificate(certHolder);

                    SubjectKeyIdentifier subjectKeyIdentifier = null;
                    if (certHolder.getExtensions() != null) {
                        subjectKeyIdentifier = SubjectKeyIdentifier.fromExtensions(certHolder.getExtensions());
                    }

                    if (subjectKeyIdentifier != null) {
                        logger.log(Level.INFO, "Certificate: {0}\nSubject Key Id: {1}",
                                new Object[] { tempCert.getSubjectDN().getName(),
                                        Arrays.toString(subjectKeyIdentifier.getKeyIdentifier()) });
                    }

                    if (subjectKeyIdentifier != null && responderSubjectKey.equals(subjectKeyIdentifier)) {
                        signingCert = tempCert;
                        logger.log(Level.INFO,
                                "Found a signer certificate \"{0}\" with the subject key extension value matching the responder key",
                                signingCert.getSubjectDN().getName());

                        break;
                    }

                    subjectKeyIdentifier = new JcaX509ExtensionUtils()
                            .createSubjectKeyIdentifier(tempCert.getPublicKey());
                    if (responderSubjectKey.equals(subjectKeyIdentifier)) {
                        signingCert = tempCert;
                        logger.log(Level.INFO,
                                "Found a certificate \"{0}\" with the subject key matching the OCSP responder key",
                                signingCert.getSubjectDN().getName());
                        break;
                    }

                } catch (CertificateException e) {
                    logger.log(Level.FINE, e.getMessage());
                }
            }
        }
    }
    if (signingCert != null) {
        if (signingCert.equals(issuerCertificate)) {
            logger.log(Level.INFO, "OCSP response is signed by the target''s Issuing CA");
        } else if (responderCertificate != null && signingCert.equals(responderCertificate)) {
            // https://www.ietf.org/rfc/rfc2560.txt
            // 2.6  OCSP Signature Authority Delegation
            // - The responder certificate is issued to the responder by CA
            logger.log(Level.INFO, "OCSP response is signed by an authorized responder certificate");
        } else {
            // 4.2.2.2  Authorized Responders
            // 3. Includes a value of id-ad-ocspSigning in an ExtendedKeyUsage
            // extension and is issued by the CA that issued the certificate in
            // question."
            if (!signingCert.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) {
                logger.log(Level.INFO, "Signer certificate''s Issuer: {0}\nIssuer certificate''s Subject: {1}",
                        new Object[] { signingCert.getIssuerX500Principal().getName(),
                                issuerCertificate.getSubjectX500Principal().getName() });
                throw new CertPathValidatorException(
                        "Responder\'s certificate is not authorized to sign OCSP responses");
            }
            try {
                List<String> purposes = signingCert.getExtendedKeyUsage();
                if (purposes != null && !purposes.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) {
                    logger.log(Level.INFO, "OCSPSigning extended usage is not set");
                    throw new CertPathValidatorException(
                            "Responder\'s certificate not valid for signing OCSP responses");
                }
            } catch (CertificateParsingException e) {
                logger.log(Level.FINE, "Failed to get certificate''s extended key usage extension\n{0}",
                        e.getMessage());
            }
            if (date == null) {
                signingCert.checkValidity();
            } else {
                signingCert.checkValidity(date);
            }
            try {
                Extension noOCSPCheck = new JcaX509CertificateHolder(signingCert)
                        .getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck);
                // TODO If the extension is present, the OCSP client can trust the
                // responder's certificate for the lifetime of the certificate.
                logger.log(Level.INFO, "OCSP no-check extension is {0} present",
                        noOCSPCheck == null ? "not" : "");
            } catch (CertificateEncodingException e) {
                logger.log(Level.FINE, "Certificate encoding exception: {0}", e.getMessage());
            }

            try {
                signingCert.verify(issuerCertificate.getPublicKey());
                logger.log(Level.INFO, "OCSP response is signed by an Authorized Responder");

            } catch (GeneralSecurityException ex) {
                signingCert = null;
            }
        }
    }
    if (signingCert == null) {
        throw new CertPathValidatorException("Unable to verify OCSP Response\'s signature");
    } else {
        if (!verifySignature(basicOcspResponse, signingCert)) {
            throw new CertPathValidatorException("Error verifying OCSP Response\'s signature");
        } else {
            Extension responseNonce = basicOcspResponse.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
            if (responseNonce != null && requestNonce != null
                    && !Arrays.equals(requestNonce, responseNonce.getExtnValue().getOctets())) {
                throw new CertPathValidatorException("Nonces do not match.");
            } else {
                // See Sun's OCSP implementation.
                // https://www.ietf.org/rfc/rfc2560.txt, if nextUpdate is not set,
                // the responder is indicating that newer update is avilable all the time
                long current = date == null ? System.currentTimeMillis() : date.getTime();
                Date stop = new Date(current + (long) TIME_SKEW);
                Date start = new Date(current - (long) TIME_SKEW);

                Iterator<SingleResp> iter = Arrays.asList(basicOcspResponse.getResponses()).iterator();
                SingleResp singleRes = null;
                do {
                    if (!iter.hasNext()) {
                        return;
                    }
                    singleRes = iter.next();
                } while (!stop.before(singleRes.getThisUpdate())
                        && !start.after(singleRes.getNextUpdate() != null ? singleRes.getNextUpdate()
                                : singleRes.getThisUpdate()));

                throw new CertPathValidatorException(
                        "Response is unreliable: its validity interval is out-of-date");
            }
        }
    }
}

From source file:org.poreid.verify.ocsp.OCSPClient.java

License:Open Source License

public CertStatus getCertificateStatus() throws OCSPValidationException {
    try {/*from   w  ww .j  ava  2s .c o  m*/
        if (null == url) {
            throw new OCSPValidationException("Certificado no tem validao por OCSP");
        }

        byte[] encodedOcspRequest = generateOCSPRequest(issuer, certificate.getSerialNumber()).getEncoded();

        HttpURLConnection httpConnection;
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setRequestProperty("Content-Type", "application/ocsp-request");
        httpConnection.setRequestProperty("Accept", "application/ocsp-response");
        httpConnection.setDoOutput(true);

        try (DataOutputStream dataOut = new DataOutputStream(
                new BufferedOutputStream(httpConnection.getOutputStream()))) {
            dataOut.write(encodedOcspRequest);
            dataOut.flush();
        }

        InputStream in = (InputStream) httpConnection.getContent();

        if (httpConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new OCSPValidationException(
                    "Cdigo HTTP recebido != 200 [" + httpConnection.getResponseCode() + "]");
        }

        OCSPResp ocspResponse = new OCSPResp(in);
        BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();

        byte[] receivedNonce = basicResponse.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnId()
                .getEncoded();
        if (!Arrays.equals(receivedNonce, sentNonce)) {
            throw new OCSPValidationException("Nonce na resposta ocsp no coincide com nonce do pedido ocsp");
        }

        X509CertificateHolder certHolder = basicResponse.getCerts()[0];
        if (!basicResponse
                .isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(issuer))) {
            if (!certHolder.isValidOn(Date.from(Instant.now()))) {
                throw new OCSPValidationException("Certificado no  vlido na data atual");
            }
            // Certificado tem de ter uma Key Purpose ID for authorized responders
            if (!ExtendedKeyUsage.fromExtensions(certHolder.getExtensions())
                    .hasKeyPurposeId(KeyPurposeId.id_kp_OCSPSigning)) {
                throw new OCSPValidationException(
                        "Certificado no contm extenso necessria (id_kp_OCSPSigning)");
            }
            // Certificado tem de ser emitido pela mesma CA do certificado que estamos a verificar
            if (!certHolder.isSignatureValid(
                    new JcaContentVerifierProviderBuilder().setProvider("BC").build(issuer))) {
                throw new OCSPValidationException("Certificado no  assinado pelo mesmo issuer");
            }
            // Validar assinatura na resposta ocsp
            if (!basicResponse.isSignatureValid(
                    new JcaContentVerifierProviderBuilder().setProvider("BC").build(certHolder))) {
                throw new OCSPValidationException("No foi possivel validar resposta ocsp");
            }
        } else {
            if (!certHolder.isValidOn(Date.from(Instant.now()))) {
                throw new OCSPValidationException("Certificado no  vlido na data atual");
            }
        }

        // Politica de Certificados do SCEE
        if (null == certHolder.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck).getExtnId()) {
            throw new OCSPValidationException(
                    "Extenso id_pkix_ocsp_nocheck no encontrada no certificado (Politica de Certificados do SCEE)");
        }

        SingleResp[] responses = basicResponse.getResponses();
        if (responses[0].getCertID().getSerialNumber().equals(certificate.getSerialNumber())) {
            CertificateStatus status = responses[0].getCertStatus();
            if (status == CertificateStatus.GOOD) {
                return CertStatus.GOOD;
            } else {

                if (status instanceof RevokedStatus) {
                    revokedStatus = (RevokedStatus) status;
                    return CertStatus.REVOKED;
                } else {
                    return CertStatus.UNKNOWN;
                }
            }
        } else {
            throw new OCSPValidationException(
                    "Nmero de srie do certificado na resposta ocsp no coincide com nmero de srie do certificado");
        }
    } catch (CertificateEncodingException | OperatorCreationException | OCSPException | IOException ex) {
        throw new OCSPValidationException("No foi possivel efetuar a validao atravs de OCSP ("
                + certificate.getSubjectX500Principal().getName() + ")", ex);
    } catch (CertException | CertificateException ex) {
        throw new OCSPValidationException("No foi possivel efetuar a validao atravs de OCSP ("
                + certificate.getSubjectX500Principal().getName() + ")", ex);
    }
}