Search in sources :

Example 1 with UnknownStatus

use of org.bouncycastle.cert.ocsp.UnknownStatus in project xipki by xipki.

the class OcspQa method checkSingleCert.

// method checkOcsp
private List<ValidationIssue> checkSingleCert(int index, SingleResp singleResp, IssuerHash issuerHash, OcspCertStatus expectedStatus, byte[] encodedCert, Date expectedRevTime, boolean extendedRevoke, Occurrence nextupdateOccurrence, Occurrence certhashOccurrence, ASN1ObjectIdentifier certhashAlg) {
    if (expectedStatus == OcspCertStatus.unknown || expectedStatus == OcspCertStatus.issuerUnknown) {
        certhashOccurrence = Occurrence.forbidden;
    }
    List<ValidationIssue> issues = new LinkedList<>();
    // issuer hash
    ValidationIssue issue = new ValidationIssue("OCSP.RESPONSE." + index + ".ISSUER", "certificate issuer");
    issues.add(issue);
    CertificateID certId = singleResp.getCertID();
    HashAlgo hashAlgo = HashAlgo.getInstance(certId.getHashAlgOID());
    if (hashAlgo == null) {
        issue.setFailureMessage("unknown hash algorithm " + certId.getHashAlgOID().getId());
    } else {
        if (!issuerHash.match(hashAlgo, certId.getIssuerNameHash(), certId.getIssuerKeyHash())) {
            issue.setFailureMessage("issuer not match");
        }
    }
    // status
    issue = new ValidationIssue("OCSP.RESPONSE." + index + ".STATUS", "certificate status");
    issues.add(issue);
    CertificateStatus singleCertStatus = singleResp.getCertStatus();
    OcspCertStatus status = null;
    Long revTimeSec = null;
    if (singleCertStatus == null) {
        status = OcspCertStatus.good;
    } else if (singleCertStatus instanceof RevokedStatus) {
        RevokedStatus revStatus = (RevokedStatus) singleCertStatus;
        revTimeSec = revStatus.getRevocationTime().getTime() / 1000;
        if (revStatus.hasRevocationReason()) {
            int reason = revStatus.getRevocationReason();
            if (extendedRevoke && reason == CrlReason.CERTIFICATE_HOLD.getCode() && revTimeSec == 0) {
                status = OcspCertStatus.unknown;
                revTimeSec = null;
            } else {
                CrlReason revocationReason = CrlReason.forReasonCode(reason);
                switch(revocationReason) {
                    case UNSPECIFIED:
                        status = OcspCertStatus.unspecified;
                        break;
                    case KEY_COMPROMISE:
                        status = OcspCertStatus.keyCompromise;
                        break;
                    case CA_COMPROMISE:
                        status = OcspCertStatus.cACompromise;
                        break;
                    case AFFILIATION_CHANGED:
                        status = OcspCertStatus.affiliationChanged;
                        break;
                    case SUPERSEDED:
                        status = OcspCertStatus.superseded;
                        break;
                    case CERTIFICATE_HOLD:
                        status = OcspCertStatus.certificateHold;
                        break;
                    case REMOVE_FROM_CRL:
                        status = OcspCertStatus.removeFromCRL;
                        break;
                    case PRIVILEGE_WITHDRAWN:
                        status = OcspCertStatus.privilegeWithdrawn;
                        break;
                    case AA_COMPROMISE:
                        status = OcspCertStatus.aACompromise;
                        break;
                    case CESSATION_OF_OPERATION:
                        status = OcspCertStatus.cessationOfOperation;
                        break;
                    default:
                        issue.setFailureMessage("should not reach here, unknown CRLReason " + revocationReason);
                        break;
                }
            }
        // end if
        } else {
            status = OcspCertStatus.rev_noreason;
        }
    // end if (revStatus.hasRevocationReason())
    } else if (singleCertStatus instanceof UnknownStatus) {
        status = extendedRevoke ? OcspCertStatus.issuerUnknown : OcspCertStatus.unknown;
    } else {
        issue.setFailureMessage("unknown certstatus: " + singleCertStatus.getClass().getName());
    }
    if (!issue.isFailed() && expectedStatus != status) {
        issue.setFailureMessage("is='" + status + "', but expected='" + expectedStatus + "'");
    }
    // revocation time
    issue = new ValidationIssue("OCSP.RESPONSE." + index + ".REVTIME", "certificate time");
    issues.add(issue);
    if (expectedRevTime != null) {
        if (revTimeSec == null) {
            issue.setFailureMessage("is='null', but expected='" + formatTime(expectedRevTime) + "'");
        } else if (revTimeSec != expectedRevTime.getTime() / 1000) {
            issue.setFailureMessage("is='" + formatTime(new Date(revTimeSec * 1000)) + "', but expected='" + formatTime(expectedRevTime) + "'");
        }
    }
    // nextUpdate
    Date nextUpdate = singleResp.getNextUpdate();
    issue = checkOccurrence("OCSP.RESPONSE." + index + ".NEXTUPDATE", nextUpdate, nextupdateOccurrence);
    issues.add(issue);
    Extension extension = singleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash);
    issue = checkOccurrence("OCSP.RESPONSE." + index + ".CERTHASH", extension, certhashOccurrence);
    issues.add(issue);
    if (extension != null) {
        ASN1Encodable extensionValue = extension.getParsedValue();
        CertHash certHash = CertHash.getInstance(extensionValue);
        ASN1ObjectIdentifier hashAlgOid = certHash.getHashAlgorithm().getAlgorithm();
        if (certhashAlg != null) {
            // certHash algorithm
            issue = new ValidationIssue("OCSP.RESPONSE." + index + ".CHASH.ALG", "certhash algorithm");
            issues.add(issue);
            ASN1ObjectIdentifier is = certHash.getHashAlgorithm().getAlgorithm();
            if (!certhashAlg.equals(is)) {
                issue.setFailureMessage("is '" + is.getId() + "', but expected '" + certhashAlg.getId() + "'");
            }
        }
        byte[] hashValue = certHash.getCertificateHash();
        if (encodedCert != null) {
            issue = new ValidationIssue("OCSP.RESPONSE." + index + ".CHASH.VALIDITY", "certhash validity");
            issues.add(issue);
            try {
                MessageDigest md = MessageDigest.getInstance(hashAlgOid.getId());
                byte[] expectedHashValue = md.digest(encodedCert);
                if (!Arrays.equals(expectedHashValue, hashValue)) {
                    issue.setFailureMessage("certhash does not match the requested certificate");
                }
            } catch (NoSuchAlgorithmException ex) {
                issue.setFailureMessage("NoSuchAlgorithm " + hashAlgOid.getId());
            }
        }
    // end if(encodedCert != null)
    }
    return issues;
}
Also used : CertHash(org.bouncycastle.asn1.isismtt.ocsp.CertHash) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) HashAlgo(org.xipki.security.HashAlgo) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ValidationIssue(org.xipki.common.qa.ValidationIssue) LinkedList(java.util.LinkedList) Date(java.util.Date) UnknownStatus(org.bouncycastle.cert.ocsp.UnknownStatus) Extension(org.bouncycastle.asn1.x509.Extension) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) CrlReason(org.xipki.security.CrlReason) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) MessageDigest(java.security.MessageDigest) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 2 with UnknownStatus

use of org.bouncycastle.cert.ocsp.UnknownStatus in project xipki by xipki.

the class OcspStatusCmd method processResponse.

@Override
protected Object processResponse(OCSPResp response, X509Certificate respIssuer, IssuerHash issuerHash, List<BigInteger> serialNumbers, Map<BigInteger, byte[]> encodedCerts) throws Exception {
    ParamUtil.requireNonNull("response", response);
    ParamUtil.requireNonNull("issuerHash", issuerHash);
    ParamUtil.requireNonNull("serialNumbers", serialNumbers);
    BasicOCSPResp basicResp = OcspUtils.extractBasicOcspResp(response);
    boolean extendedRevoke = basicResp.getExtension(ObjectIdentifiers.id_pkix_ocsp_extendedRevoke) != null;
    SingleResp[] singleResponses = basicResp.getResponses();
    if (singleResponses == null || singleResponses.length == 0) {
        throw new CmdFailure("received no status from server");
    }
    final int n = singleResponses.length;
    if (n != serialNumbers.size()) {
        throw new CmdFailure("received status with " + n + " single responses from server, but " + serialNumbers.size() + " were requested");
    }
    Date[] thisUpdates = new Date[n];
    for (int i = 0; i < n; i++) {
        thisUpdates[i] = singleResponses[i].getThisUpdate();
    }
    // check the signature if available
    if (null == basicResp.getSignature()) {
        println("response is not signed");
    } else {
        X509CertificateHolder[] responderCerts = basicResp.getCerts();
        if (responderCerts == null || responderCerts.length < 1) {
            throw new CmdFailure("no responder certificate is contained in the response");
        }
        ResponderID respId = basicResp.getResponderId().toASN1Primitive();
        X500Name respIdByName = respId.getName();
        byte[] respIdByKey = respId.getKeyHash();
        X509CertificateHolder respSigner = null;
        for (X509CertificateHolder cert : responderCerts) {
            if (respIdByName != null) {
                if (cert.getSubject().equals(respIdByName)) {
                    respSigner = cert;
                }
            } else {
                byte[] spkiSha1 = HashAlgo.SHA1.hash(cert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes());
                if (Arrays.equals(respIdByKey, spkiSha1)) {
                    respSigner = cert;
                }
            }
            if (respSigner != null) {
                break;
            }
        }
        if (respSigner == null) {
            throw new CmdFailure("no responder certificate match the ResponderId");
        }
        boolean validOn = true;
        for (Date thisUpdate : thisUpdates) {
            validOn = respSigner.isValidOn(thisUpdate);
            if (!validOn) {
                throw new CmdFailure("responder certificate is not valid on " + thisUpdate);
            }
        }
        if (validOn) {
            PublicKey responderPubKey = KeyUtil.generatePublicKey(respSigner.getSubjectPublicKeyInfo());
            ContentVerifierProvider cvp = securityFactory.getContentVerifierProvider(responderPubKey);
            boolean sigValid = basicResp.isSignatureValid(cvp);
            if (!sigValid) {
                throw new CmdFailure("response is equipped with invalid signature");
            }
            // verify the OCSPResponse signer
            if (respIssuer != null) {
                boolean certValid = true;
                X509Certificate jceRespSigner = X509Util.toX509Cert(respSigner.toASN1Structure());
                if (X509Util.issues(respIssuer, jceRespSigner)) {
                    try {
                        jceRespSigner.verify(respIssuer.getPublicKey());
                    } catch (SignatureException ex) {
                        certValid = false;
                    }
                }
                if (!certValid) {
                    throw new CmdFailure("response is equipped with valid signature but the" + " OCSP signer is not trusted");
                }
            } else {
                println("response is equipped with valid signature");
            }
        // end if(respIssuer)
        }
        if (verbose.booleanValue()) {
            println("responder is " + X509Util.getRfc4519Name(responderCerts[0].getSubject()));
        }
    }
    for (int i = 0; i < n; i++) {
        if (n > 1) {
            println("---------------------------- " + i + "----------------------------");
        }
        SingleResp singleResp = singleResponses[i];
        CertificateStatus singleCertStatus = singleResp.getCertStatus();
        String status;
        if (singleCertStatus == null) {
            status = "good";
        } else if (singleCertStatus instanceof RevokedStatus) {
            RevokedStatus revStatus = (RevokedStatus) singleCertStatus;
            Date revTime = revStatus.getRevocationTime();
            Date invTime = null;
            Extension ext = singleResp.getExtension(Extension.invalidityDate);
            if (ext != null) {
                invTime = ASN1GeneralizedTime.getInstance(ext.getParsedValue()).getDate();
            }
            if (revStatus.hasRevocationReason()) {
                int reason = revStatus.getRevocationReason();
                if (extendedRevoke && reason == CrlReason.CERTIFICATE_HOLD.getCode() && revTime.getTime() == 0) {
                    status = "unknown (RFC6960)";
                } else {
                    status = StringUtil.concatObjects("revoked, reason = ", CrlReason.forReasonCode(reason).getDescription(), ", revocationTime = ", revTime, (invTime == null ? "" : ", invalidityTime = " + invTime));
                }
            } else {
                status = "revoked, no reason, revocationTime = " + revTime;
            }
        } else if (singleCertStatus instanceof UnknownStatus) {
            status = "unknown (RFC2560)";
        } else {
            status = "ERROR";
        }
        StringBuilder msg = new StringBuilder();
        CertificateID certId = singleResp.getCertID();
        HashAlgo hashAlgo = HashAlgo.getNonNullInstance(certId.getHashAlgOID());
        boolean issuerMatch = issuerHash.match(hashAlgo, certId.getIssuerNameHash(), certId.getIssuerKeyHash());
        BigInteger serialNumber = certId.getSerialNumber();
        msg.append("issuer matched: ").append(issuerMatch);
        msg.append("\nserialNumber: ").append(LogUtil.formatCsn(serialNumber));
        msg.append("\nCertificate status: ").append(status);
        if (verbose.booleanValue()) {
            msg.append("\nthisUpdate: ").append(singleResp.getThisUpdate());
            msg.append("\nnextUpdate: ").append(singleResp.getNextUpdate());
            Extension extension = singleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash);
            if (extension != null) {
                msg.append("\nCertHash is provided:\n");
                ASN1Encodable extensionValue = extension.getParsedValue();
                CertHash certHash = CertHash.getInstance(extensionValue);
                ASN1ObjectIdentifier hashAlgOid = certHash.getHashAlgorithm().getAlgorithm();
                byte[] hashValue = certHash.getCertificateHash();
                msg.append("\tHash algo : ").append(hashAlgOid.getId()).append("\n");
                msg.append("\tHash value: ").append(Hex.encode(hashValue)).append("\n");
                if (encodedCerts != null) {
                    byte[] encodedCert = encodedCerts.get(serialNumber);
                    MessageDigest md = MessageDigest.getInstance(hashAlgOid.getId());
                    byte[] expectedHashValue = md.digest(encodedCert);
                    if (Arrays.equals(expectedHashValue, hashValue)) {
                        msg.append("\tThis matches the requested certificate");
                    } else {
                        msg.append("\tThis differs from the requested certificate");
                    }
                }
            }
            // end if (extension != null)
            extension = singleResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff);
            if (extension != null) {
                ASN1Encodable extensionValue = extension.getParsedValue();
                ASN1GeneralizedTime time = ASN1GeneralizedTime.getInstance(extensionValue);
                msg.append("\nArchive-CutOff: ");
                msg.append(time.getTimeString());
            }
            AlgorithmIdentifier sigAlg = basicResp.getSignatureAlgorithmID();
            if (sigAlg == null) {
                msg.append(("\nresponse is not signed"));
            } else {
                String sigAlgName = AlgorithmUtil.getSignatureAlgoName(sigAlg);
                if (sigAlgName == null) {
                    sigAlgName = "unknown";
                }
                msg.append("\nresponse is signed with ").append(sigAlgName);
            }
            // extensions
            msg.append("\nExtensions: ");
            List<?> extensionOids = basicResp.getExtensionOIDs();
            if (extensionOids == null || extensionOids.size() == 0) {
                msg.append("-");
            } else {
                int size = extensionOids.size();
                for (int j = 0; j < size; j++) {
                    ASN1ObjectIdentifier extensionOid = (ASN1ObjectIdentifier) extensionOids.get(j);
                    String name = EXTENSION_OIDNAME_MAP.get(extensionOid);
                    if (name == null) {
                        msg.append(extensionOid.getId());
                    } else {
                        msg.append(name);
                    }
                    if (j != size - 1) {
                        msg.append(", ");
                    }
                }
            }
        }
        // end if (verbose.booleanValue())
        println(msg.toString());
    }
    // end for
    println("");
    return null;
}
Also used : HashAlgo(org.xipki.security.HashAlgo) ResponderID(org.bouncycastle.asn1.ocsp.ResponderID) ASN1GeneralizedTime(org.bouncycastle.asn1.ASN1GeneralizedTime) X500Name(org.bouncycastle.asn1.x500.X500Name) SignatureException(java.security.SignatureException) UnknownStatus(org.bouncycastle.cert.ocsp.UnknownStatus) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) CmdFailure(org.xipki.console.karaf.CmdFailure) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) MessageDigest(java.security.MessageDigest) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) CertHash(org.bouncycastle.asn1.isismtt.ocsp.CertHash) PublicKey(java.security.PublicKey) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) Extension(org.bouncycastle.asn1.x509.Extension) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 3 with UnknownStatus

use of org.bouncycastle.cert.ocsp.UnknownStatus in project ddf by codice.

the class OcspChecker method getStatusFromOcspResponse.

/**
 * Gets the {@link CertificateStatus} from the given {@param ocspResponse}.
 *
 * @param ocspResponse - the {@link OCSPResp} to get the {@link CertificateStatus} from.
 * @return the {@link CertificateStatus} from the given {@param ocspResponse}. Returns an {@link
 *     UnknownStatus} if the status could not be found.
 */
private CertificateStatus getStatusFromOcspResponse(OCSPResp ocspResponse, X509Certificate certificate) {
    try {
        BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();
        if (basicResponse == null) {
            return new UnknownStatus();
        }
        SingleResp[] singleResps = basicResponse.getResponses();
        if (singleResps == null) {
            return new UnknownStatus();
        }
        SingleResp response = Arrays.stream(singleResps).filter(singleResp -> singleResp.getCertID() != null).filter(singleResp -> singleResp.getCertID().getSerialNumber().equals(certificate.getSerialNumber())).findFirst().orElse(null);
        if (response == null) {
            LOGGER.debug("Certificate status from OCSP response is unknown.");
            return new UnknownStatus();
        }
        if (response.getCertStatus() == null) {
            LOGGER.debug("Certificate status from OCSP response is good.");
            return CertificateStatus.GOOD;
        }
        return response.getCertStatus();
    } catch (OCSPException e) {
        return new UnknownStatus();
    }
}
Also used : X509Certificate(java.security.cert.X509Certificate) Req(org.bouncycastle.cert.ocsp.Req) Arrays(java.util.Arrays) AccessDescription(org.bouncycastle.asn1.x509.AccessDescription) Enumeration(java.util.Enumeration) Extension(org.bouncycastle.asn1.x509.Extension) URISyntaxException(java.net.URISyntaxException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) LoggerFactory(org.slf4j.LoggerFactory) KeyStoreException(java.security.KeyStoreException) X500Name(org.bouncycastle.asn1.x500.X500Name) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) Map(java.util.Map) URI(java.net.URI) X509ExtensionUtil(org.bouncycastle.x509.extension.X509ExtensionUtil) ClientBuilderFactory(org.codice.ddf.cxf.client.ClientBuilderFactory) OcspService(org.codice.ddf.security.OcspService) OCSPReqBuilder(org.bouncycastle.cert.ocsp.OCSPReqBuilder) NoticePriority(org.codice.ddf.system.alerts.NoticePriority) Set(java.util.Set) KeyStore(java.security.KeyStore) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) ClientBuilder(org.codice.ddf.cxf.client.ClientBuilder) PrivilegedAction(java.security.PrivilegedAction) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Response(javax.ws.rs.core.Response) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Entry(java.util.Map.Entry) ProcessingException(javax.ws.rs.ProcessingException) SecureCxfClientFactory(org.codice.ddf.cxf.client.SecureCxfClientFactory) AccessController(java.security.AccessController) Certificate(org.bouncycastle.asn1.x509.Certificate) CertificateEncodingException(java.security.cert.CertificateEncodingException) EventAdmin(org.osgi.service.event.EventAdmin) RevokedStatus(org.bouncycastle.cert.ocsp.RevokedStatus) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) AuthorityInformationAccess(org.bouncycastle.asn1.x509.AuthorityInformationAccess) HashMap(java.util.HashMap) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) SecurityConstants(ddf.security.SecurityConstants) Nullable(javax.annotation.Nullable) DERIA5String(org.bouncycastle.asn1.DERIA5String) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) Logger(org.slf4j.Logger) SecurityLogger(ddf.security.audit.SecurityLogger) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) UnknownStatus(org.bouncycastle.cert.ocsp.UnknownStatus) WebClient(org.apache.cxf.jaxrs.client.WebClient) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) DigestCalculator(org.bouncycastle.operator.DigestCalculator) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) CertificateException(java.security.cert.CertificateException) BasicOCSPResponse(org.bouncycastle.asn1.ocsp.BasicOCSPResponse) SystemNotice(org.codice.ddf.system.alerts.SystemNotice) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Event(org.osgi.service.event.Event) InputStream(java.io.InputStream) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) UnknownStatus(org.bouncycastle.cert.ocsp.UnknownStatus)

Example 4 with UnknownStatus

use of org.bouncycastle.cert.ocsp.UnknownStatus in project ddf by codice.

the class OcspChecker method sendOcspRequests.

/**
 * Sends the {@param ocspReq} request to all configured {@code cspServerUrls} & the OCSP server
 * urls optionally given in the given {@param cert}.
 *
 * @param cert - the {@link X509Certificate} to check.
 * @param ocspRequest - the {@link OCSPReq} to send.
 * @return a {@link List} of {@link OCSPResp}s for every configured {@code ocspServerUrls} & the
 *     OCSP server * urls optionally given in the given {@param cert}. Problematic responses are
 *     represented as null values.
 */
@VisibleForTesting
Map<URI, CertificateStatus> sendOcspRequests(X509Certificate cert, OCSPReq ocspRequest) {
    Set<URI> urlsToCheck = new HashSet<>();
    if (ocspServerUrls != null) {
        urlsToCheck.addAll(ocspServerUrls);
    }
    // try and pull an OCSP server url off of the cert
    urlsToCheck.addAll(getOcspUrlsFromCert(cert));
    if (LOGGER.isTraceEnabled()) {
        logRequest(ocspRequest);
    }
    Map<URI, CertificateStatus> ocspStatuses = new HashMap<>();
    for (URI ocspServerUrl : urlsToCheck) {
        try {
            ClientBuilder<WebClient> clientBuilder = factory.getClientBuilder();
            SecureCxfClientFactory<WebClient> cxfClientFactory = clientBuilder.endpoint(ocspServerUrl.toString()).interfaceClass(WebClient.class).build();
            WebClient client = cxfClientFactory.getWebClient().accept("application/ocsp-response").type("application/ocsp-request");
            LOGGER.debug("Sending OCSP request to URL: {}", ocspServerUrl);
            Response response = client.post(ocspRequest.getEncoded());
            OCSPResp ocspResponse = createOcspResponse(response);
            if (LOGGER.isTraceEnabled()) {
                logResponse(ocspResponse);
            }
            ocspStatuses.put(ocspServerUrl, getStatusFromOcspResponse(ocspResponse, cert));
            continue;
        } catch (IOException | OcspCheckerException | ProcessingException e) {
            LOGGER.debug("Problem with the response from the OCSP Server at URL {}." + CONTINUING_MSG, ocspServerUrl, e);
        }
        ocspStatuses.put(ocspServerUrl, // if ocspServerUrl is null or if there was an exception
        new UnknownStatus());
    }
    return ocspStatuses;
}
Also used : HashMap(java.util.HashMap) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) IOException(java.io.IOException) URI(java.net.URI) WebClient(org.apache.cxf.jaxrs.client.WebClient) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) UnknownStatus(org.bouncycastle.cert.ocsp.UnknownStatus) Response(javax.ws.rs.core.Response) BasicOCSPResponse(org.bouncycastle.asn1.ocsp.BasicOCSPResponse) HashSet(java.util.HashSet) ProcessingException(javax.ws.rs.ProcessingException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Aggregations

CertificateStatus (org.bouncycastle.cert.ocsp.CertificateStatus)4 UnknownStatus (org.bouncycastle.cert.ocsp.UnknownStatus)4 Extension (org.bouncycastle.asn1.x509.Extension)3 BasicOCSPResp (org.bouncycastle.cert.ocsp.BasicOCSPResp)3 CertificateID (org.bouncycastle.cert.ocsp.CertificateID)3 RevokedStatus (org.bouncycastle.cert.ocsp.RevokedStatus)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 IOException (java.io.IOException)2 URI (java.net.URI)2 MessageDigest (java.security.MessageDigest)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 X509Certificate (java.security.cert.X509Certificate)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)2 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)2 CertHash (org.bouncycastle.asn1.isismtt.ocsp.CertHash)2 X500Name (org.bouncycastle.asn1.x500.X500Name)2 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)2