use of org.bouncycastle.cert.ocsp.OCSPResp in project neo4j by neo4j.
the class CertConfiguredSecureSocketConnection method getSeenOcspResponses.
public Set<BasicOCSPResp> getSeenOcspResponses() throws IOException, OCSPException {
Set<BasicOCSPResp> ocspResponses = new HashSet<>();
List<byte[]> binaryStatusResponses = ((ExtendedSSLSession) ((SSLSocket) getSocket()).getSession()).getStatusResponses();
for (byte[] bResp : binaryStatusResponses) {
if (bResp.length > 0) {
OCSPResp ocspResp = new OCSPResp(bResp);
ocspResponses.add((BasicOCSPResp) ocspResp.getResponseObject());
}
}
return ocspResponses;
}
use of org.bouncycastle.cert.ocsp.OCSPResp 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;
}
use of org.bouncycastle.cert.ocsp.OCSPResp in project netty by netty.
the class OcspUtils method request.
/**
* TODO: This is a very crude and non-scalable HTTP client to fetch the OCSP response from the
* CA's OCSP responder server. It's meant to demonstrate the basic building blocks on how to
* interact with the responder server and you should consider using Netty's HTTP client instead.
*/
public static OCSPResp request(URI uri, OCSPReq request, long timeout, TimeUnit unit) throws IOException {
byte[] encoded = request.getEncoded();
URL url = uri.toURL();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
connection.setConnectTimeout((int) unit.toMillis(timeout));
connection.setReadTimeout((int) unit.toMillis(timeout));
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("host", uri.getHost());
connection.setRequestProperty("content-type", OCSP_REQUEST_TYPE);
connection.setRequestProperty("accept", OCSP_RESPONSE_TYPE);
connection.setRequestProperty("content-length", String.valueOf(encoded.length));
OutputStream out = connection.getOutputStream();
try {
out.write(encoded);
out.flush();
InputStream in = connection.getInputStream();
try {
int code = connection.getResponseCode();
if (code != HttpsURLConnection.HTTP_OK) {
throw new IOException("Unexpected status-code=" + code);
}
String contentType = connection.getContentType();
if (!contentType.equalsIgnoreCase(OCSP_RESPONSE_TYPE)) {
throw new IOException("Unexpected content-type=" + contentType);
}
int contentLength = connection.getContentLength();
if (contentLength == -1) {
// Probably a terrible idea!
contentLength = Integer.MAX_VALUE;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[8192];
int length = -1;
while ((length = in.read(buffer)) != -1) {
baos.write(buffer, 0, length);
if (baos.size() >= contentLength) {
break;
}
}
} finally {
baos.close();
}
return new OCSPResp(baos.toByteArray());
} finally {
in.close();
}
} finally {
out.close();
}
} finally {
connection.disconnect();
}
}
use of org.bouncycastle.cert.ocsp.OCSPResp 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);
}
}
}
}
use of org.bouncycastle.cert.ocsp.OCSPResp 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();
}
}
Aggregations