org.bouncycastle.cert.ocsp.CertificateStatus Java Examples

The following examples show how to use org.bouncycastle.cert.ocsp.CertificateStatus. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OcspClientExample.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean verify(ChannelHandlerContext ctx, ReferenceCountedOpenSslEngine engine) throws Exception {
    byte[] staple = engine.getOcspResponse();
    if (staple == null) {
        throw new IllegalStateException("Server didn't provide an OCSP staple!");
    }

    OCSPResp response = new OCSPResp(staple);
    if (response.getStatus() != OCSPResponseStatus.SUCCESSFUL) {
        return false;
    }

    SSLSession session = engine.getSession();
    X509Certificate[] chain = session.getPeerCertificateChain();
    BigInteger certSerial = chain[0].getSerialNumber();

    BasicOCSPResp basicResponse = (BasicOCSPResp) response.getResponseObject();
    SingleResp first = basicResponse.getResponses()[0];

    // ATTENTION: CertificateStatus.GOOD is actually a null value! Do not use
    // equals() or you'll NPE!
    CertificateStatus status = first.getCertStatus();
    BigInteger ocspSerial = first.getCertID().getSerialNumber();
    String message = new StringBuilder()
        .append("OCSP status of ").append(ctx.channel().remoteAddress())
        .append("\n  Status: ").append(status == CertificateStatus.GOOD ? "Good" : status)
        .append("\n  This Update: ").append(first.getThisUpdate())
        .append("\n  Next Update: ").append(first.getNextUpdate())
        .append("\n  Cert Serial: ").append(certSerial)
        .append("\n  OCSP Serial: ").append(ocspSerial)
        .toString();
    System.out.println(message);

    return status == CertificateStatus.GOOD && certSerial.equals(ocspSerial);
}
 
Example #2
Source File: OCSPFuncTest.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static ETriState evalOCSPResponse (@Nonnull final OCSPResp aOCSPResponse) throws OCSPException
{
  final EOCSPResponseStatus eStatus = EOCSPResponseStatus.getFromValueOrNull (aOCSPResponse.getStatus ());
  if (eStatus == null)
    throw new OCSPException ("Unsupported status code " + aOCSPResponse.getStatus () + " received!");
  if (eStatus.isFailure ())
    throw new OCSPException ("Non-success status code " + aOCSPResponse.getStatus () + " received!");

  final Object aResponseObject = aOCSPResponse.getResponseObject ();
  if (aResponseObject instanceof BasicOCSPResp)
  {
    final BasicOCSPResp aBasicResponse = (BasicOCSPResp) aResponseObject;
    final SingleResp [] aResponses = aBasicResponse.getResponses ();
    // Assume we queried only one
    if (aResponses.length == 1)
    {
      final SingleResp aResponse = aResponses[0];
      final CertificateStatus aStatus = aResponse.getCertStatus ();
      if (aStatus == CertificateStatus.GOOD)
        return ETriState.TRUE;
      if (aStatus instanceof RevokedStatus)
        return ETriState.FALSE;
      // else status is unknown
    }
  }
  return ETriState.UNDEFINED;
}
 
Example #3
Source File: OcspServerExample.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
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 a 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);
    }

    // Step 6: Cache the OCSP response and use it as long as it's not
    // expired. The exact semantics are beyond the scope of this example.

    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();
    }
}
 
Example #4
Source File: OcspClientBouncyCastle.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @return 	a byte array
 * @see com.lowagie.text.pdf.OcspClient#getEncoded()
 */
public byte[] getEncoded() {
    try {
        OCSPReq request = generateOCSPRequest(rootCert, checkCert.getSerialNumber());
        byte[] array = request.getEncoded();
        URL urlt = new URL(url);
        HttpURLConnection con = (HttpURLConnection)urlt.openConnection();
        con.setRequestProperty("Content-Type", "application/ocsp-request");
        con.setRequestProperty("Accept", "application/ocsp-response");
        con.setDoOutput(true);
        OutputStream out = con.getOutputStream();
        DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(out));
        dataOut.write(array);
        dataOut.flush();
        dataOut.close();
        if (con.getResponseCode() / 100 != 2) {
            throw new IOException("Invalid HTTP response");
        }
        //Get Response
        InputStream in = (InputStream) con.getContent();
        OCSPResp ocspResponse = new OCSPResp(in);

        if (ocspResponse.getStatus() != 0)
            throw new IOException("Invalid status: " + ocspResponse.getStatus());
        BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject();
        if (basicResponse != null) {
            SingleResp[] responses = basicResponse.getResponses();
            if (responses.length == 1) {
                SingleResp resp = responses[0];
                Object status = resp.getCertStatus();
                if (status == CertificateStatus.GOOD) {
                    return basicResponse.getEncoded();
                }
                else if (status instanceof org.bouncycastle.cert.ocsp.RevokedStatus) {
                    throw new IOException("OCSP Status is revoked!");
                }
                else {
                    throw new IOException("OCSP Status is unknown!");
                }
            }
        }
    }
    catch (Exception ex) {
        throw new ExceptionConverter(ex);
    }
    return null;
}
 
Example #5
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
/**
 * Validates OCSP Basic OCSP response.
 *
 * @param currentTime   the current timestamp.
 * @param basicOcspResp BasicOcspResponse data.
 * @throws SFOCSPException raises if any failure occurs.
 */
private void validateBasicOcspResponse(
    Date currentTime, BasicOCSPResp basicOcspResp)
throws SFOCSPException
{
  for (SingleResp singleResps : basicOcspResp.getResponses())
  {
    checkCertUnknownTestParameter();
    CertificateStatus certStatus = singleResps.getCertStatus();
    if (certStatus != CertificateStatus.GOOD)
    {
      if (certStatus instanceof RevokedStatus)
      {
        RevokedStatus status = (RevokedStatus) certStatus;
        int reason;
        try
        {
          reason = status.getRevocationReason();
        }
        catch (IllegalStateException ex)
        {
          reason = -1;
        }
        Date revocationTime = status.getRevocationTime();
        throw new SFOCSPException(OCSPErrorCode.CERTIFICATE_STATUS_REVOKED,
                                  String.format(
                                      "The certificate has been revoked. Reason: %d, Time: %s",
                                      reason, DATE_FORMAT_UTC.format(revocationTime)));
      }
      else
      {
        // Unknown status
        throw new SFOCSPException(OCSPErrorCode.CERTIFICATE_STATUS_UNKNOWN,
                                  "Failed to validate the certificate for UNKNOWN reason.");
      }
    }

    Date thisUpdate = singleResps.getThisUpdate();
    Date nextUpdate = singleResps.getNextUpdate();
    LOGGER.debug("Current Time: {}, This Update: {}, Next Update: {}",
                 currentTime, thisUpdate, nextUpdate);
    if (!isValidityRange(currentTime, thisUpdate, nextUpdate))
    {
      throw new SFOCSPException(OCSPErrorCode.INVALID_OCSP_RESPONSE_VALIDITY,
                                String.format(
                                    "The OCSP response validity is out of range: " +
                                    "Current Time: %s, This Update: %s, Next Update: %s",
                                    DATE_FORMAT_UTC.format(currentTime),
                                    DATE_FORMAT_UTC.format(thisUpdate),
                                    DATE_FORMAT_UTC.format(nextUpdate)));
    }
  }
  LOGGER.debug("OK. Verified the certificate revocation status.");
}
 
Example #6
Source File: OCSPCertificateVerifier.java    From oxAuth with MIT License 4 votes vote down vote up
@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;
}