Search in sources :

Example 1 with BasicOCSPResp

use of org.bouncycastle.cert.ocsp.BasicOCSPResp in project Openfire by igniterealtime.

the class OCSPChecker method check.

@Override
public void check(Certificate cert, Collection<String> unresolvedCritExts) throws CertPathValidatorException {
    Log.debug("OCSPChecker: check called");
    InputStream in = null;
    OutputStream out = null;
    try {
        // Examine OCSP properties
        X509Certificate responderCert = null;
        //defaults to issuers cert
        boolean haveResponderCert = true;
        X500Principal responderSubjectName = null;
        boolean haveIssuerCert = false;
        // If we set the subject name, we need to find the certificate
        if (ocspServerSubject != null) {
            haveResponderCert = false;
            responderSubjectName = new X500Principal(ocspServerSubject);
        }
        X509Certificate issuerCert = null;
        X509Certificate currCert = (X509Certificate) cert;
        // Set the issuer certificate if we were passed a chain
        if (certIndex != 0) {
            issuerCert = certs[certIndex];
            haveIssuerCert = true;
            if (haveResponderCert) {
                responderCert = certs[certIndex];
            }
        }
        if (!haveIssuerCert || !haveResponderCert) {
            if (!haveResponderCert) {
                Log.debug("OCSPChecker: Looking for responder's certificate");
            }
            if (!haveIssuerCert) {
                Log.debug("OCSPChecker: Looking for issuer's certificate");
            }
            // Extract the anchor certs
            Iterator anchors = pkixParams.getTrustAnchors().iterator();
            if (!anchors.hasNext()) {
                throw new CertPathValidatorException("Must specify at least one trust anchor");
            }
            X500Principal certIssuerName = currCert.getIssuerX500Principal();
            while (anchors.hasNext() && (!haveIssuerCert || !haveResponderCert)) {
                TrustAnchor anchor = (TrustAnchor) anchors.next();
                X509Certificate anchorCert = anchor.getTrustedCert();
                X500Principal anchorSubjectName = anchorCert.getSubjectX500Principal();
                // Check if this anchor cert is the issuer cert
                if (!haveIssuerCert && certIssuerName.equals(anchorSubjectName)) {
                    issuerCert = anchorCert;
                    haveIssuerCert = true;
                    //If we have not set the responderCert at this point, set it to the issuer
                    if (haveResponderCert && responderCert == null) {
                        responderCert = anchorCert;
                        Log.debug("OCSPChecker: Responder's certificate = issuer certificate");
                    }
                }
                // Check if this anchor cert is the responder cert
                if (!haveResponderCert) {
                    if (responderSubjectName != null && responderSubjectName.equals(anchorSubjectName)) {
                        responderCert = anchorCert;
                        haveResponderCert = true;
                    }
                }
            }
            if (issuerCert == null) {
                //No trust anchor was found matching the issuer
                throw new CertPathValidatorException("No trusted certificate for " + currCert.getIssuerDN());
            }
            // Check cert stores if responder cert has not yet been found
            if (!haveResponderCert) {
                Log.debug("OCSPChecker: Searching cert stores for responder's certificate");
                if (responderSubjectName != null) {
                    X509CertSelector filter = new X509CertSelector();
                    filter.setSubject(responderSubjectName.getName());
                    List<CertStore> certStores = pkixParams.getCertStores();
                    for (CertStore certStore : certStores) {
                        Iterator i = certStore.getCertificates(filter).iterator();
                        if (i.hasNext()) {
                            responderCert = (X509Certificate) i.next();
                            haveResponderCert = true;
                            break;
                        }
                    }
                }
            }
        }
        // Could not find the responder cert
        if (!haveResponderCert) {
            throw new CertPathValidatorException("Cannot find the responder's certificate.");
        }
        // Construct an OCSP Request
        OCSPReqBuilder gen = new OCSPReqBuilder();
        CertificateID certID = new CertificateID(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCert.getEncoded()), currCert.getSerialNumber());
        gen.addRequest(certID);
        OCSPReq ocspRequest = gen.build();
        URL url;
        if (ocspServerUrl != null) {
            try {
                url = new URL(ocspServerUrl);
            } catch (MalformedURLException e) {
                throw new CertPathValidatorException(e);
            }
        } else {
            throw new CertPathValidatorException("Must set OCSP Server URL");
        }
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        Log.debug("OCSPChecker: connecting to OCSP service at: " + url);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "application/ocsp-request");
        con.setRequestProperty("Accept", "application/ocsp-response");
        byte[] bytes = ocspRequest.getEncoded();
        con.setRequestProperty("Content-length", String.valueOf(bytes.length));
        out = con.getOutputStream();
        out.write(bytes);
        out.flush();
        // Check the response
        if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
            Log.debug("OCSPChecker: Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage());
        }
        in = con.getInputStream();
        OCSPResp ocspResponse = new OCSPResp(in);
        BigInteger serialNumber = currCert.getSerialNumber();
        BasicOCSPResp brep = (BasicOCSPResp) ocspResponse.getResponseObject();
        try {
            if (!brep.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(responderCert.getPublicKey()))) {
                throw new CertPathValidatorException("OCSP response is not verified");
            }
        } catch (Exception e) {
            throw new CertPathValidatorException("OCSP response could not be verified (" + e.getMessage() + ")", null, cp, certIndex);
        }
        SingleResp[] singleResp = brep.getResponses();
        boolean foundResponse = false;
        for (SingleResp resp : singleResp) {
            CertificateID respCertID = resp.getCertID();
            if (respCertID.equals(certID)) {
                Object status = resp.getCertStatus();
                if (status == CertificateStatus.GOOD) {
                    Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: good");
                    foundResponse = true;
                    break;
                } else if (status instanceof org.bouncycastle.cert.ocsp.RevokedStatus) {
                    Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: revoked");
                    throw new CertPathValidatorException("Certificate has been revoked", null, cp, certIndex);
                } else if (status instanceof org.bouncycastle.cert.ocsp.UnknownStatus) {
                    Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: unknown");
                    throw new CertPathValidatorException("Certificate's revocation status is unknown", null, cp, certIndex);
                } else {
                    Log.debug("Status of certificate (with serial number " + serialNumber.toString() + ") is: not recognized");
                    throw new CertPathValidatorException("Unknown OCSP response for certificate", null, cp, certIndex);
                }
            }
        }
        // Check that response applies to the cert that was supplied
        if (!foundResponse) {
            throw new CertPathValidatorException("No certificates in the OCSP response match the " + "certificate supplied in the OCSP request.");
        }
    } catch (CertPathValidatorException cpve) {
        throw cpve;
    } catch (Exception e) {
        throw new CertPathValidatorException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
                throw new CertPathValidatorException(ioe);
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException ioe) {
                throw new CertPathValidatorException(ioe);
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) OutputStream(java.io.OutputStream) X509CertSelector(java.security.cert.X509CertSelector) URL(java.net.URL) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) HttpURLConnection(java.net.HttpURLConnection) Iterator(java.util.Iterator) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) InputStream(java.io.InputStream) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) TrustAnchor(java.security.cert.TrustAnchor) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) CertPathValidatorException(java.security.cert.CertPathValidatorException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) NoSuchProviderException(java.security.NoSuchProviderException) CertPathValidatorException(java.security.cert.CertPathValidatorException) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) X500Principal(javax.security.auth.x500.X500Principal) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) CertStore(java.security.cert.CertStore)

Example 2 with BasicOCSPResp

use of org.bouncycastle.cert.ocsp.BasicOCSPResp in project poi by apache.

the class XAdESXLSignatureFacet method postSign.

@Override
public void postSign(Document document) throws MarshalException {
    LOG.log(POILogger.DEBUG, "XAdES-X-L post sign phase");
    QualifyingPropertiesDocument qualDoc = null;
    QualifyingPropertiesType qualProps = null;
    // check for XAdES-BES
    NodeList qualNl = document.getElementsByTagNameNS(XADES_132_NS, "QualifyingProperties");
    if (qualNl.getLength() == 1) {
        try {
            qualDoc = QualifyingPropertiesDocument.Factory.parse(qualNl.item(0), DEFAULT_XML_OPTIONS);
        } catch (XmlException e) {
            throw new MarshalException(e);
        }
        qualProps = qualDoc.getQualifyingProperties();
    } else {
        throw new MarshalException("no XAdES-BES extension present");
    }
    // create basic XML container structure
    UnsignedPropertiesType unsignedProps = qualProps.getUnsignedProperties();
    if (unsignedProps == null) {
        unsignedProps = qualProps.addNewUnsignedProperties();
    }
    UnsignedSignaturePropertiesType unsignedSigProps = unsignedProps.getUnsignedSignatureProperties();
    if (unsignedSigProps == null) {
        unsignedSigProps = unsignedProps.addNewUnsignedSignatureProperties();
    }
    // create the XAdES-T time-stamp
    NodeList nlSigVal = document.getElementsByTagNameNS(XML_DIGSIG_NS, "SignatureValue");
    if (nlSigVal.getLength() != 1) {
        throw new IllegalArgumentException("SignatureValue is not set.");
    }
    RevocationData tsaRevocationDataXadesT = new RevocationData();
    LOG.log(POILogger.DEBUG, "creating XAdES-T time-stamp");
    XAdESTimeStampType signatureTimeStamp = createXAdESTimeStamp(Collections.singletonList(nlSigVal.item(0)), tsaRevocationDataXadesT);
    // marshal the XAdES-T extension
    unsignedSigProps.addNewSignatureTimeStamp().set(signatureTimeStamp);
    // xadesv141::TimeStampValidationData
    if (tsaRevocationDataXadesT.hasRevocationDataEntries()) {
        ValidationDataType validationData = createValidationData(tsaRevocationDataXadesT);
        insertXChild(unsignedSigProps, validationData);
    }
    if (signatureConfig.getRevocationDataService() == null) {
        /*
             * Without revocation data service we cannot construct the XAdES-C
             * extension.
             */
        return;
    }
    // XAdES-C: complete certificate refs
    CompleteCertificateRefsType completeCertificateRefs = unsignedSigProps.addNewCompleteCertificateRefs();
    CertIDListType certIdList = completeCertificateRefs.addNewCertRefs();
    /*
         * We skip the signing certificate itself according to section
         * 4.4.3.2 of the XAdES 1.4.1 specification.
         */
    List<X509Certificate> certChain = signatureConfig.getSigningCertificateChain();
    int chainSize = certChain.size();
    if (chainSize > 1) {
        for (X509Certificate cert : certChain.subList(1, chainSize)) {
            CertIDType certId = certIdList.addNewCert();
            XAdESSignatureFacet.setCertID(certId, signatureConfig, false, cert);
        }
    }
    // XAdES-C: complete revocation refs
    CompleteRevocationRefsType completeRevocationRefs = unsignedSigProps.addNewCompleteRevocationRefs();
    RevocationData revocationData = signatureConfig.getRevocationDataService().getRevocationData(certChain);
    if (revocationData.hasCRLs()) {
        CRLRefsType crlRefs = completeRevocationRefs.addNewCRLRefs();
        completeRevocationRefs.setCRLRefs(crlRefs);
        for (byte[] encodedCrl : revocationData.getCRLs()) {
            CRLRefType crlRef = crlRefs.addNewCRLRef();
            X509CRL crl;
            try {
                crl = (X509CRL) this.certificateFactory.generateCRL(new ByteArrayInputStream(encodedCrl));
            } catch (CRLException e) {
                throw new RuntimeException("CRL parse error: " + e.getMessage(), e);
            }
            CRLIdentifierType crlIdentifier = crlRef.addNewCRLIdentifier();
            String issuerName = crl.getIssuerDN().getName().replace(",", ", ");
            crlIdentifier.setIssuer(issuerName);
            Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT);
            cal.setTime(crl.getThisUpdate());
            crlIdentifier.setIssueTime(cal);
            crlIdentifier.setNumber(getCrlNumber(crl));
            DigestAlgAndValueType digestAlgAndValue = crlRef.addNewDigestAlgAndValue();
            XAdESSignatureFacet.setDigestAlgAndValue(digestAlgAndValue, encodedCrl, signatureConfig.getDigestAlgo());
        }
    }
    if (revocationData.hasOCSPs()) {
        OCSPRefsType ocspRefs = completeRevocationRefs.addNewOCSPRefs();
        for (byte[] ocsp : revocationData.getOCSPs()) {
            try {
                OCSPRefType ocspRef = ocspRefs.addNewOCSPRef();
                DigestAlgAndValueType digestAlgAndValue = ocspRef.addNewDigestAlgAndValue();
                XAdESSignatureFacet.setDigestAlgAndValue(digestAlgAndValue, ocsp, signatureConfig.getDigestAlgo());
                OCSPIdentifierType ocspIdentifier = ocspRef.addNewOCSPIdentifier();
                OCSPResp ocspResp = new OCSPResp(ocsp);
                BasicOCSPResp basicOcspResp = (BasicOCSPResp) ocspResp.getResponseObject();
                Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ROOT);
                cal.setTime(basicOcspResp.getProducedAt());
                ocspIdentifier.setProducedAt(cal);
                ResponderIDType responderId = ocspIdentifier.addNewResponderID();
                RespID respId = basicOcspResp.getResponderId();
                ResponderID ocspResponderId = respId.toASN1Primitive();
                DERTaggedObject derTaggedObject = (DERTaggedObject) ocspResponderId.toASN1Primitive();
                if (2 == derTaggedObject.getTagNo()) {
                    ASN1OctetString keyHashOctetString = (ASN1OctetString) derTaggedObject.getObject();
                    byte[] key = keyHashOctetString.getOctets();
                    responderId.setByKey(key);
                } else {
                    X500Name name = X500Name.getInstance(derTaggedObject.getObject());
                    String nameStr = name.toString();
                    responderId.setByName(nameStr);
                }
            } catch (Exception e) {
                throw new RuntimeException("OCSP decoding error: " + e.getMessage(), e);
            }
        }
    }
    // marshal XAdES-C
    // XAdES-X Type 1 timestamp
    List<Node> timeStampNodesXadesX1 = new ArrayList<Node>();
    timeStampNodesXadesX1.add(nlSigVal.item(0));
    timeStampNodesXadesX1.add(signatureTimeStamp.getDomNode());
    timeStampNodesXadesX1.add(completeCertificateRefs.getDomNode());
    timeStampNodesXadesX1.add(completeRevocationRefs.getDomNode());
    RevocationData tsaRevocationDataXadesX1 = new RevocationData();
    LOG.log(POILogger.DEBUG, "creating XAdES-X time-stamp");
    XAdESTimeStampType timeStampXadesX1 = createXAdESTimeStamp(timeStampNodesXadesX1, tsaRevocationDataXadesX1);
    if (tsaRevocationDataXadesX1.hasRevocationDataEntries()) {
        ValidationDataType timeStampXadesX1ValidationData = createValidationData(tsaRevocationDataXadesX1);
        insertXChild(unsignedSigProps, timeStampXadesX1ValidationData);
    }
    // marshal XAdES-X
    unsignedSigProps.addNewSigAndRefsTimeStamp().set(timeStampXadesX1);
    // XAdES-X-L
    CertificateValuesType certificateValues = unsignedSigProps.addNewCertificateValues();
    for (X509Certificate certificate : certChain) {
        EncapsulatedPKIDataType encapsulatedPKIDataType = certificateValues.addNewEncapsulatedX509Certificate();
        try {
            encapsulatedPKIDataType.setByteArrayValue(certificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
        }
    }
    RevocationValuesType revocationValues = unsignedSigProps.addNewRevocationValues();
    createRevocationValues(revocationValues, revocationData);
    // marshal XAdES-X-L
    Node n = document.importNode(qualProps.getDomNode(), true);
    qualNl.item(0).getParentNode().replaceChild(n, qualNl.item(0));
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) MarshalException(javax.xml.crypto.MarshalException) X509CRL(java.security.cert.X509CRL) ValidationDataType(org.etsi.uri.x01903.v14.ValidationDataType) Node(org.w3c.dom.Node) ResponderID(org.bouncycastle.asn1.ocsp.ResponderID) ArrayList(java.util.ArrayList) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) X500Name(org.bouncycastle.asn1.x500.X500Name) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) CRLException(java.security.cert.CRLException) RevocationData(org.apache.poi.poifs.crypt.dsig.services.RevocationData) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) NodeList(org.w3c.dom.NodeList) Calendar(java.util.Calendar) CertificateEncodingException(java.security.cert.CertificateEncodingException) X509Certificate(java.security.cert.X509Certificate) MarshalException(javax.xml.crypto.MarshalException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) XmlException(org.apache.xmlbeans.XmlException) CRLException(java.security.cert.CRLException) CertificateEncodingException(java.security.cert.CertificateEncodingException) ByteArrayInputStream(java.io.ByteArrayInputStream) XmlException(org.apache.xmlbeans.XmlException) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) RespID(org.bouncycastle.cert.ocsp.RespID)

Example 3 with BasicOCSPResp

use of org.bouncycastle.cert.ocsp.BasicOCSPResp in project poi by apache.

the class PkiTestUtils method createOcspResp.

public static OCSPResp createOcspResp(X509Certificate certificate, boolean revoked, X509Certificate issuerCertificate, X509Certificate ocspResponderCertificate, PrivateKey ocspResponderPrivateKey, String signatureAlgorithm, long nonceTimeinMillis) throws Exception {
    DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1);
    X509CertificateHolder issuerHolder = new X509CertificateHolder(issuerCertificate.getEncoded());
    CertificateID certId = new CertificateID(digestCalc, issuerHolder, certificate.getSerialNumber());
    // request
    //create a nonce to avoid replay attack
    BigInteger nonce = BigInteger.valueOf(nonceTimeinMillis);
    DEROctetString nonceDer = new DEROctetString(nonce.toByteArray());
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, nonceDer);
    Extensions exts = new Extensions(ext);
    OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder();
    ocspReqBuilder.addRequest(certId);
    ocspReqBuilder.setRequestExtensions(exts);
    OCSPReq ocspReq = ocspReqBuilder.build();
    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(CertificateID.HASH_SHA1, ocspResponderCertificate.getPublicKey().getEncoded());
    BasicOCSPRespBuilder basicOCSPRespBuilder = new BasicOCSPRespBuilder(keyInfo, digestCalc);
    basicOCSPRespBuilder.setResponseExtensions(exts);
    // request processing
    Req[] requestList = ocspReq.getRequestList();
    for (Req ocspRequest : requestList) {
        CertificateID certificateID = ocspRequest.getCertID();
        CertificateStatus certificateStatus = CertificateStatus.GOOD;
        if (revoked) {
            certificateStatus = new RevokedStatus(new Date(), CRLReason.privilegeWithdrawn);
        }
        basicOCSPRespBuilder.addResponse(certificateID, certificateStatus);
    }
    // basic response generation
    X509CertificateHolder[] chain = null;
    if (!ocspResponderCertificate.equals(issuerCertificate)) {
        // TODO: HorribleProxy can't convert array input params yet
        chain = new X509CertificateHolder[] { new X509CertificateHolder(ocspResponderCertificate.getEncoded()), issuerHolder };
    }
    ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(ocspResponderPrivateKey);
    BasicOCSPResp basicOCSPResp = basicOCSPRespBuilder.build(contentSigner, chain, new Date(nonceTimeinMillis));
    OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder();
    OCSPResp ocspResp = ocspRespBuilder.build(OCSPRespBuilder.SUCCESSFUL, basicOCSPResp);
    return ocspResp;
}
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) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ContentSigner(org.bouncycastle.operator.ContentSigner) Extensions(org.bouncycastle.asn1.x509.Extensions) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DEROctetString(org.bouncycastle.asn1.DEROctetString) Date(java.util.Date) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) Extension(org.bouncycastle.asn1.x509.Extension) BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) Req(org.bouncycastle.cert.ocsp.Req) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq)

Example 4 with BasicOCSPResp

use of org.bouncycastle.cert.ocsp.BasicOCSPResp in project oxAuth by GluuFederation.

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, ValidatorSourceType.OCSP, 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(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(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(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(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) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) CertificateEncodingException(java.security.cert.CertificateEncodingException) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) ValidationStatus(org.xdi.oxauth.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)

Aggregations

BasicOCSPResp (org.bouncycastle.cert.ocsp.BasicOCSPResp)4 OCSPResp (org.bouncycastle.cert.ocsp.OCSPResp)4 IOException (java.io.IOException)3 X509Certificate (java.security.cert.X509Certificate)3 CertificateID (org.bouncycastle.cert.ocsp.CertificateID)3 OCSPReq (org.bouncycastle.cert.ocsp.OCSPReq)3 JcaDigestCalculatorProviderBuilder (org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder)3 BigInteger (java.math.BigInteger)2 MalformedURLException (java.net.MalformedURLException)2 CertificateEncodingException (java.security.cert.CertificateEncodingException)2 Date (java.util.Date)2 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)2 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)2 OCSPReqBuilder (org.bouncycastle.cert.ocsp.OCSPReqBuilder)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 HttpURLConnection (java.net.HttpURLConnection)1 URL (java.net.URL)1 NoSuchProviderException (java.security.NoSuchProviderException)1