Search in sources :

Example 36 with CertificateID

use of org.bouncycastle.cert.ocsp.CertificateID in project netty by netty.

the class OcspRequestBuilder method build.

/**
 * ATTENTION: The returned {@link OCSPReq} is not re-usable/cacheable! It contains a one-time nonce
 * and CA's will (should) reject subsequent requests that have the same nonce value.
 */
public OCSPReq build() throws OCSPException, IOException, CertificateEncodingException {
    SecureRandom generator = checkNotNull(this.generator, "generator");
    DigestCalculator calculator = checkNotNull(this.calculator, "calculator");
    X509Certificate certificate = checkNotNull(this.certificate, "certificate");
    X509Certificate issuer = checkNotNull(this.issuer, "issuer");
    BigInteger serial = certificate.getSerialNumber();
    CertificateID certId = new CertificateID(calculator, new X509CertificateHolder(issuer.getEncoded()), serial);
    OCSPReqBuilder builder = new OCSPReqBuilder();
    builder.addRequest(certId);
    byte[] nonce = new byte[8];
    generator.nextBytes(nonce);
    Extension[] extensions = new Extension[] { new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce)) };
    builder.setRequestExtensions(new Extensions(extensions));
    return builder.build();
}
Also used : Extension(org.bouncycastle.asn1.x509.Extension) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) DigestCalculator(org.bouncycastle.operator.DigestCalculator) SecureRandom(java.security.SecureRandom) BigInteger(java.math.BigInteger) Extensions(org.bouncycastle.asn1.x509.Extensions) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) X509Certificate(java.security.cert.X509Certificate) DEROctetString(org.bouncycastle.asn1.DEROctetString)

Example 37 with CertificateID

use of org.bouncycastle.cert.ocsp.CertificateID in project keycloak by keycloak.

the class OcspHandler method handleRequest.

@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }
    final byte[] buffy = new byte[16384];
    try (InputStream requestStream = exchange.getInputStream()) {
        requestStream.read(buffy);
    }
    final OCSPReq request = new OCSPReq(buffy);
    final Req[] requested = request.getRequestList();
    final Extension nonce = request.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
    final DigestCalculator sha1Calculator = new JcaDigestCalculatorProviderBuilder().build().get(AlgorithmIdentifier.getInstance(RespID.HASH_SHA1));
    final BasicOCSPRespBuilder responseBuilder = new BasicOCSPRespBuilder(subjectPublicKeyInfo, sha1Calculator);
    if (nonce != null) {
        responseBuilder.setResponseExtensions(new Extensions(nonce));
    }
    for (final Req req : requested) {
        final CertificateID certId = req.getCertID();
        final BigInteger certificateSerialNumber = certId.getSerialNumber();
        responseBuilder.addResponse(certId, REVOKED_CERTIFICATES_STATUS.get(certificateSerialNumber));
    }
    final ContentSigner contentSigner = new BcRSAContentSignerBuilder(new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption), new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)).build(privateKey);
    final OCSPResp response = new OCSPRespBuilder().build(OCSPResp.SUCCESSFUL, responseBuilder.build(contentSigner, chain, new Date()));
    final byte[] responseBytes = response.getEncoded();
    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    responseHeaders.put(Headers.CONTENT_TYPE, "application/ocsp-response");
    final Sender responseSender = exchange.getResponseSender();
    responseSender.send(ByteBuffer.wrap(responseBytes));
    exchange.endExchange();
}
Also used : BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) OCSPRespBuilder(org.bouncycastle.cert.ocsp.OCSPRespBuilder) InputStream(java.io.InputStream) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ContentSigner(org.bouncycastle.operator.ContentSigner) Extensions(org.bouncycastle.asn1.x509.Extensions) Date(java.util.Date) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) Extension(org.bouncycastle.asn1.x509.Extension) Sender(io.undertow.io.Sender) BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) HeaderMap(io.undertow.util.HeaderMap) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) Req(org.bouncycastle.cert.ocsp.Req) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq)

Example 38 with CertificateID

use of org.bouncycastle.cert.ocsp.CertificateID in project wso2-synapse by wso2.

the class OCSPVerifierTest method generateOCSPResponse.

/**
 * This makes the corresponding OCSP response to the OCSP request which is sent to the fake CA. If the request
 * has a certificateID which is marked as revoked by the CA, the OCSP response will say that the certificate
 * which is referred to by the request, is revoked.
 *
 * @param request the OCSP request which asks if the certificate is revoked.
 * @param caPrivateKey privateKey of the fake CA.
 * @param caPublicKey  publicKey of the fake CA
 * @param revokedID the ID at fake CA which is checked against the certificateId in the request.
 * @return the created OCSP response by the fake CA.
 * @throws NoSuchProviderException
 * @throws OCSPException
 * @throws OperatorCreationException
 */
private OCSPResp generateOCSPResponse(OCSPReq request, X509CertificateHolder certificateHolder, PrivateKey caPrivateKey, PublicKey caPublicKey, CertificateID revokedID) throws NoSuchProviderException, OCSPException, OperatorCreationException {
    BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(new RespID(certificateHolder.getSubject()));
    Extension extension = request.getExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp.getId()));
    if (extension != null) {
        basicOCSPRespBuilder.setResponseExtensions(new Extensions(extension));
    }
    Req[] requests = request.getRequestList();
    for (Req req : requests) {
        CertificateID certID = req.getCertID();
        if (certID.equals(revokedID)) {
            RevokedStatus revokedStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn);
            Date nextUpdate = new Date(new Date().getTime() + TestConstants.NEXT_UPDATE_PERIOD);
            basicOCSPRespBuilder.addResponse(certID, revokedStatus, nextUpdate, (Extensions) null);
        } else {
            basicOCSPRespBuilder.addResponse(certID, CertificateStatus.GOOD);
        }
    }
    X509CertificateHolder[] chain = { certificateHolder };
    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(caPrivateKey);
    BasicOCSPResp basicResp = basicOCSPRespBuilder.build(signer, chain, new Date());
    OCSPRespBuilder builder = new OCSPRespBuilder();
    return builder.build(OCSPRespBuilder.SUCCESSFUL, basicResp);
}
Also used : BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) OCSPRespBuilder(org.bouncycastle.cert.ocsp.OCSPRespBuilder) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) Extensions(org.bouncycastle.asn1.x509.Extensions) Date(java.util.Date) Extension(org.bouncycastle.asn1.x509.Extension) BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) RespID(org.bouncycastle.cert.ocsp.RespID) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) Req(org.bouncycastle.cert.ocsp.Req) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq)

Example 39 with CertificateID

use of org.bouncycastle.cert.ocsp.CertificateID in project jans by JanssenProject.

the class OCSPCertificateVerifier method validate.

@Override
public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers, Date validationDate) {
    X509Certificate issuer = issuers.get(0);
    ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate, ValidationStatus.ValidatorSourceType.OCSP, ValidationStatus.CertificateValidity.UNKNOWN);
    try {
        Principal subjectX500Principal = certificate.getSubjectX500Principal();
        String ocspUrl = getOCSPUrl(certificate);
        if (ocspUrl == null) {
            log.error("OCSP URL for '" + subjectX500Principal + "' is empty");
            return status;
        }
        log.debug("OCSP URL for '" + subjectX500Principal + "' is '" + ocspUrl + "'");
        DigestCalculator digestCalculator = new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1);
        CertificateID certificateId = new CertificateID(digestCalculator, new JcaX509CertificateHolder(certificate), certificate.getSerialNumber());
        // Generate OCSP request
        OCSPReq ocspReq = generateOCSPRequest(certificateId);
        // Get OCSP response from server
        OCSPResp ocspResp = requestOCSPResponse(ocspUrl, ocspReq);
        if (ocspResp.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
            log.error("OCSP response is invalid!");
            status.setValidity(ValidationStatus.CertificateValidity.INVALID);
            return status;
        }
        boolean foundResponse = false;
        BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject();
        SingleResp[] singleResps = basicOCSPResp.getResponses();
        for (SingleResp singleResp : singleResps) {
            CertificateID responseCertificateId = singleResp.getCertID();
            if (!certificateId.equals(responseCertificateId)) {
                continue;
            }
            foundResponse = true;
            log.debug("OCSP validationDate: " + validationDate);
            log.debug("OCSP thisUpdate: " + singleResp.getThisUpdate());
            log.debug("OCSP nextUpdate: " + singleResp.getNextUpdate());
            status.setRevocationObjectIssuingTime(basicOCSPResp.getProducedAt());
            Object certStatus = singleResp.getCertStatus();
            if (certStatus == CertificateStatus.GOOD) {
                log.debug("OCSP status is valid for '" + certificate.getSubjectX500Principal() + "'");
                status.setValidity(ValidationStatus.CertificateValidity.VALID);
            } else {
                if (singleResp.getCertStatus() instanceof RevokedStatus) {
                    log.warn("OCSP status is revoked for: " + subjectX500Principal);
                    if (validationDate.before(((RevokedStatus) singleResp.getCertStatus()).getRevocationTime())) {
                        log.warn("OCSP revocation time after the validation date, the certificate '" + subjectX500Principal + "' was valid at " + validationDate);
                        status.setValidity(ValidationStatus.CertificateValidity.VALID);
                    } else {
                        Date revocationDate = ((RevokedStatus) singleResp.getCertStatus()).getRevocationTime();
                        log.info("OCSP for certificate '" + subjectX500Principal + "' is revoked since " + revocationDate);
                        status.setRevocationDate(revocationDate);
                        status.setRevocationObjectIssuingTime(singleResp.getThisUpdate());
                        status.setValidity(ValidationStatus.CertificateValidity.REVOKED);
                    }
                }
            }
        }
        if (!foundResponse) {
            log.error("There is no matching OCSP response entries");
        }
    } catch (Exception ex) {
        log.error("OCSP exception: ", ex);
    }
    return status;
}
Also used : CertificateID(org.bouncycastle.cert.ocsp.CertificateID) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) IOException(java.io.IOException) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) ValidationStatus(io.jans.as.common.cert.validation.model.ValidationStatus) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) Principal(java.security.Principal)

Example 40 with CertificateID

use of org.bouncycastle.cert.ocsp.CertificateID in project X-Road by nordic-institute.

the class OcspVerifier method verifyResponseValidity.

private SingleResp verifyResponseValidity(OCSPResp response, X509Certificate subject, X509Certificate issuer) throws Exception {
    BasicOCSPResp basicResp = (BasicOCSPResp) response.getResponseObject();
    SingleResp singleResp = basicResp.getResponses()[0];
    CertificateID requestCertId = createCertId(subject, issuer);
    // that which was identified in the corresponding request;
    if (!singleResp.getCertID().equals(requestCertId)) {
        throw new CodedException(X_INCORRECT_VALIDATION_INFO, "OCSP response does not apply to certificate (sn = %s)", subject.getSerialNumber());
    }
    X509Certificate ocspCert = getOcspCert(basicResp);
    if (ocspCert == null) {
        throw new CodedException(X_INCORRECT_VALIDATION_INFO, "Could not find OCSP certificate for responder ID");
    }
    if (!verifySignature(basicResp, ocspCert)) {
        throw new CodedException(X_INCORRECT_VALIDATION_INFO, "Signature on OCSP response is not valid");
    }
    // 4. The signer is currently authorized to sign the response.
    if (!isAuthorizedOcspSigner(ocspCert, issuer)) {
        throw new CodedException(X_INCORRECT_VALIDATION_INFO, "OCSP responder is not authorized for given CA");
    }
    return singleResp;
}
Also used : CodedException(ee.ria.xroad.common.CodedException) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) X509Certificate(java.security.cert.X509Certificate)

Aggregations

CertificateID (org.bouncycastle.cert.ocsp.CertificateID)49 OCSPReqBuilder (org.bouncycastle.cert.ocsp.OCSPReqBuilder)24 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)23 Extension (org.bouncycastle.asn1.x509.Extension)22 IOException (java.io.IOException)21 Extensions (org.bouncycastle.asn1.x509.Extensions)19 JcaDigestCalculatorProviderBuilder (org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder)18 BasicOCSPResp (org.bouncycastle.cert.ocsp.BasicOCSPResp)17 SingleResp (org.bouncycastle.cert.ocsp.SingleResp)17 BigInteger (java.math.BigInteger)16 X509Certificate (java.security.cert.X509Certificate)16 DEROctetString (org.bouncycastle.asn1.DEROctetString)16 JcaX509CertificateHolder (org.bouncycastle.cert.jcajce.JcaX509CertificateHolder)14 DigestCalculator (org.bouncycastle.operator.DigestCalculator)14 OCSPReq (org.bouncycastle.cert.ocsp.OCSPReq)13 Date (java.util.Date)12 OCSPException (org.bouncycastle.cert.ocsp.OCSPException)12 OCSPResp (org.bouncycastle.cert.ocsp.OCSPResp)12 DigestCalculatorProvider (org.bouncycastle.operator.DigestCalculatorProvider)12 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)12