use of org.bouncycastle.cert.ocsp.OCSPReq in project oxAuth by GluuFederation.
the class OCSPCertificateVerifier method generateOCSPRequest.
private OCSPReq generateOCSPRequest(CertificateID certificateId) throws OCSPException, OperatorCreationException, CertificateEncodingException {
OCSPReqBuilder ocspReqGenerator = new OCSPReqBuilder();
ocspReqGenerator.addRequest(certificateId);
OCSPReq ocspReq = ocspReqGenerator.build();
return ocspReq;
}
use of org.bouncycastle.cert.ocsp.OCSPReq in project nifi by apache.
the class OcspCertificateValidator method getOcspStatus.
/**
* Gets the OCSP status for the specified subject and issuer certificates.
*
* @param ocspStatusKey status key
* @return ocsp status
*/
private OcspStatus getOcspStatus(final OcspRequest ocspStatusKey) {
final X509Certificate subjectCertificate = ocspStatusKey.getSubjectCertificate();
final X509Certificate issuerCertificate = ocspStatusKey.getIssuerCertificate();
// initialize the default status
final OcspStatus ocspStatus = new OcspStatus();
ocspStatus.setVerificationStatus(VerificationStatus.Unknown);
ocspStatus.setValidationStatus(ValidationStatus.Unknown);
try {
// prepare the request
final BigInteger subjectSerialNumber = subjectCertificate.getSerialNumber();
final DigestCalculatorProvider calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
final CertificateID certificateId = new CertificateID(calculatorProviderBuilder.get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCertificate.getEncoded()), subjectSerialNumber);
// generate the request
final OCSPReqBuilder requestGenerator = new OCSPReqBuilder();
requestGenerator.addRequest(certificateId);
// Create a nonce to avoid replay attack
BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true, new DEROctetString(nonce.toByteArray()));
requestGenerator.setRequestExtensions(new Extensions(new Extension[] { ext }));
final OCSPReq ocspRequest = requestGenerator.build();
// perform the request
final Response response = getClientResponse(ocspRequest);
// ensure the request was completed successfully
if (Response.Status.OK.getStatusCode() != response.getStatusInfo().getStatusCode()) {
logger.warn(String.format("OCSP request was unsuccessful (%s).", response.getStatus()));
return ocspStatus;
}
// interpret the response
OCSPResp ocspResponse = new OCSPResp(response.readEntity(InputStream.class));
// verify the response status
switch(ocspResponse.getStatus()) {
case OCSPRespBuilder.SUCCESSFUL:
ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Successful);
break;
case OCSPRespBuilder.INTERNAL_ERROR:
ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.InternalError);
break;
case OCSPRespBuilder.MALFORMED_REQUEST:
ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.MalformedRequest);
break;
case OCSPRespBuilder.SIG_REQUIRED:
ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.SignatureRequired);
break;
case OCSPRespBuilder.TRY_LATER:
ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.TryLater);
break;
case OCSPRespBuilder.UNAUTHORIZED:
ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unauthorized);
break;
default:
ocspStatus.setResponseStatus(OcspStatus.ResponseStatus.Unknown);
break;
}
// only proceed if the response was successful
if (ocspResponse.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
logger.warn(String.format("OCSP request was unsuccessful (%s).", ocspStatus.getResponseStatus().toString()));
return ocspStatus;
}
// ensure the appropriate response object
final Object ocspResponseObject = ocspResponse.getResponseObject();
if (ocspResponseObject == null || !(ocspResponseObject instanceof BasicOCSPResp)) {
logger.warn(String.format("Unexpected OCSP response object: %s", ocspResponseObject));
return ocspStatus;
}
// get the response object
final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) ocspResponse.getResponseObject();
// attempt to locate the responder certificate
final X509CertificateHolder[] responderCertificates = basicOcspResponse.getCerts();
if (responderCertificates.length != 1) {
logger.warn(String.format("Unexpected number of OCSP responder certificates: %s", responderCertificates.length));
return ocspStatus;
}
// get the responder certificate
final X509Certificate trustedResponderCertificate = getTrustedResponderCertificate(responderCertificates[0], issuerCertificate);
if (trustedResponderCertificate != null) {
// verify the response
if (basicOcspResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(trustedResponderCertificate.getPublicKey()))) {
ocspStatus.setVerificationStatus(VerificationStatus.Verified);
} else {
ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
}
} else {
ocspStatus.setVerificationStatus(VerificationStatus.Unverified);
}
// validate the response
final SingleResp[] responses = basicOcspResponse.getResponses();
for (SingleResp singleResponse : responses) {
final CertificateID responseCertificateId = singleResponse.getCertID();
final BigInteger responseSerialNumber = responseCertificateId.getSerialNumber();
if (responseSerialNumber.equals(subjectSerialNumber)) {
Object certStatus = singleResponse.getCertStatus();
// interpret the certificate status
if (CertificateStatus.GOOD == certStatus) {
ocspStatus.setValidationStatus(ValidationStatus.Good);
} else if (certStatus instanceof RevokedStatus) {
ocspStatus.setValidationStatus(ValidationStatus.Revoked);
} else {
ocspStatus.setValidationStatus(ValidationStatus.Unknown);
}
}
}
} catch (final OCSPException | IOException | ProcessingException | OperatorCreationException e) {
logger.error(e.getMessage(), e);
} catch (CertificateException e) {
e.printStackTrace();
}
return ocspStatus;
}
use of org.bouncycastle.cert.ocsp.OCSPReq in project xipki by xipki.
the class OcspServerImpl method checkSignature.
// method initStore
private Object checkSignature(byte[] request, RequestOption requestOption) throws OCSPException, CertificateParsingException, InvalidAlgorithmParameterException {
OCSPRequest req;
try {
if (!requestOption.isValidateSignature()) {
return OcspRequest.getInstance(request);
}
if (!OcspRequest.containsSignature(request)) {
if (requestOption.isSignatureRequired()) {
LOG.warn("signature in request required");
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.sigRequired);
} else {
return OcspRequest.getInstance(request);
}
}
try {
req = OCSPRequest.getInstance(request);
} catch (IllegalArgumentException ex) {
throw new EncodingException("could not parse OCSP request", ex);
}
} catch (EncodingException ex) {
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
OCSPReq ocspReq = new OCSPReq(req);
X509CertificateHolder[] certs = ocspReq.getCerts();
if (certs == null || certs.length < 1) {
LOG.warn("no certificate found in request to verify the signature");
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.unauthorized);
}
ContentVerifierProvider cvp;
try {
cvp = securityFactory.getContentVerifierProvider(certs[0]);
} catch (InvalidKeyException ex) {
String message = ex.getMessage();
LOG.warn("securityFactory.getContentVerifierProvider, InvalidKeyException: {}", message);
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.unauthorized);
}
boolean sigValid = ocspReq.isSignatureValid(cvp);
if (!sigValid) {
LOG.warn("request signature is invalid");
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.unauthorized);
}
// validate the certPath
Date referenceTime = new Date();
if (canBuildCertpath(certs, requestOption, referenceTime)) {
try {
return OcspRequest.getInstance(req);
} catch (EncodingException ex) {
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.malformedRequest);
}
}
LOG.warn("could not build certpath for the request's signer certificate");
return unsuccesfulOCSPRespMap.get(OcspResponseStatus.unauthorized);
}
use of org.bouncycastle.cert.ocsp.OCSPReq in project netty by netty.
the class OcspServerExample method main.
public static void main(String[] args) throws Exception {
// We assume there's a private key.
PrivateKey privateKey = null;
// Step 1: Load the certificate chain for netty.io. We'll need the certificate
// and the issuer's certificate and we don't need any of the intermediate certs.
// The array is assumed to be a certain order to keep things simple.
X509Certificate[] keyCertChain = parseCertificates(OcspServerExample.class, "netty_io_chain.pem");
X509Certificate certificate = keyCertChain[0];
X509Certificate issuer = keyCertChain[keyCertChain.length - 1];
// Step 2: We need the URL of the CA's OCSP responder server. It's somewhere encoded
// into the certificate! Notice that it's an HTTP URL.
URI uri = OcspUtils.ocspUri(certificate);
System.out.println("OCSP Responder URI: " + uri);
if (uri == null) {
throw new IllegalStateException("The CA/certificate doesn't have an OCSP responder");
}
// Step 3: Construct the OCSP request
OCSPReq request = new OcspRequestBuilder().certificate(certificate).issuer(issuer).build();
// Step 4: Do the request to the CA's OCSP responder
OCSPResp response = OcspUtils.request(uri, request, 5L, TimeUnit.SECONDS);
if (response.getStatus() != OCSPResponseStatus.SUCCESSFUL) {
throw new IllegalStateException("response-status=" + response.getStatus());
}
// Step 5: Is my certificate any good or has the CA revoked it?
BasicOCSPResp basicResponse = (BasicOCSPResp) response.getResponseObject();
SingleResp first = basicResponse.getResponses()[0];
CertificateStatus status = first.getCertStatus();
System.out.println("Status: " + (status == CertificateStatus.GOOD ? "Good" : status));
System.out.println("This Update: " + first.getThisUpdate());
System.out.println("Next Update: " + first.getNextUpdate());
if (status != null) {
throw new IllegalStateException("certificate-status=" + status);
}
BigInteger certSerial = certificate.getSerialNumber();
BigInteger ocspSerial = first.getCertID().getSerialNumber();
if (!certSerial.equals(ocspSerial)) {
throw new IllegalStateException("Bad Serials=" + certSerial + " vs. " + ocspSerial);
}
if (!OpenSsl.isAvailable()) {
throw new IllegalStateException("OpenSSL is not available!");
}
if (!OpenSsl.isOcspSupported()) {
throw new IllegalStateException("OCSP is not supported!");
}
if (privateKey == null) {
throw new IllegalStateException("Because we don't have a PrivateKey we can't continue past this point.");
}
ReferenceCountedOpenSslContext context = (ReferenceCountedOpenSslContext) SslContextBuilder.forServer(privateKey, keyCertChain).sslProvider(SslProvider.OPENSSL).enableOcsp(true).build();
try {
ServerBootstrap bootstrap = new ServerBootstrap().childHandler(newServerHandler(context, response));
// so on and so forth...
} finally {
context.release();
}
}
use of org.bouncycastle.cert.ocsp.OCSPReq in project oxAuth by GluuFederation.
the class OCSPCertificateVerifier method generateOCSPRequest.
private OCSPReq generateOCSPRequest(CertificateID certificateId) throws OCSPException, OperatorCreationException, CertificateEncodingException {
OCSPReqBuilder ocspReqGenerator = new OCSPReqBuilder();
ocspReqGenerator.addRequest(certificateId);
OCSPReq ocspReq = ocspReqGenerator.build();
return ocspReq;
}
Aggregations