Java Code Examples for org.bouncycastle.cert.ocsp.OCSPResp#getResponseObject()

The following examples show how to use org.bouncycastle.cert.ocsp.OCSPResp#getResponseObject() . 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: OnlineOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private BigInteger getEmbeddedNonceValue(final OCSPResp ocspResp) {
	try {
		BasicOCSPResp basicOCSPResp = (BasicOCSPResp)ocspResp.getResponseObject();
		
		Extension extension = basicOCSPResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
		ASN1OctetString extnValue = extension.getExtnValue();
		ASN1Primitive value;
		try {
			value = ASN1Primitive.fromByteArray(extnValue.getOctets());
		} catch (IOException ex) {
			throw new OCSPException("Invalid encoding of nonce extension value in OCSP response", ex);
		}
		if (value instanceof DEROctetString) {
			return new BigInteger(((DEROctetString) value).getOctets());
		}
		throw new OCSPException("Nonce extension value in OCSP response is not an OCTET STRING");
	} catch (Exception e) {
		throw new DSSException(String.format("Unable to extract the nonce from the OCSPResponse! Reason : [%s]", e.getMessage()), e);
	}
}
 
Example 2
Source File: JdbcCacheOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected OCSPToken buildRevocationTokenFromResult(ResultSet rs, CertificateToken certificateToken, CertificateToken issuerCert) {
	try {
		final byte[] data = rs.getBytes(SQL_FIND_QUERY_DATA);
		final String url = rs.getString(SQL_FIND_QUERY_LOC);
		
		final OCSPResp ocspResp = new OCSPResp(data);
		BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResp.getResponseObject();
		SingleResp latestSingleResponse = DSSRevocationUtils.getLatestSingleResponse(basicResponse, certificateToken, issuerCert);
		OCSPToken ocspToken = new OCSPToken(basicResponse, latestSingleResponse, certificateToken, issuerCert);
		ocspToken.setSourceURL(url);
		ocspToken.setExternalOrigin(RevocationOrigin.CACHED);
		return ocspToken;
	} catch (SQLException | IOException | OCSPException e) {
		throw new RevocationException("An error occurred during an attempt to obtain a revocation token");
	}
}
 
Example 3
Source File: PAdESOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void collectOCSPArchivalValues(AttributeTable attributes) {
	final ASN1Encodable attValue = DSSASN1Utils.getAsn1Encodable(attributes, OID.adbe_revocationInfoArchival);
	if (attValue !=null) {	
		RevocationInfoArchival revocationArchival = PAdESUtils.getRevocationInfoArchivals(attValue);
		if (revocationArchival != null) {
			for (final OCSPResponse ocspResponse : revocationArchival.getOcspVals()) {
				final OCSPResp ocspResp = new OCSPResp(ocspResponse);
				try {
					BasicOCSPResp basicOCSPResponse = (BasicOCSPResp) ocspResp.getResponseObject();
					addBinary(OCSPResponseBinary.build(basicOCSPResponse), RevocationOrigin.ADBE_REVOCATION_INFO_ARCHIVAL);
				} catch (OCSPException e) {
					LOG.warn("Error while extracting OCSPResponse from Revocation Info Archivals (ADBE) : {}", e.getMessage());
				}					
			}
		}
	}
}
 
Example 4
Source File: DSSDictionaryExtractionUtils.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static Map<Long, BasicOCSPResp> getOCSPsFromArray(PdfDict dict, String dictionaryName, String arrayName) {
	Map<Long, BasicOCSPResp> ocspMap = new HashMap<>();
	PdfArray ocspArray = dict.getAsArray(arrayName);
	if (ocspArray != null) {
		LOG.debug("There are {} OCSPs in the '{}' dictionary", ocspArray.size(), dictionaryName);
		for (int ii = 0; ii < ocspArray.size(); ii++) {
			try {
				final long objectNumber = ocspArray.getObjectNumber(ii);
				if (!ocspMap.containsKey(objectNumber)) {
					final OCSPResp ocspResp = new OCSPResp(ocspArray.getBytes(ii));
					final BasicOCSPResp responseObject = (BasicOCSPResp) ocspResp.getResponseObject();
					ocspMap.put(objectNumber, responseObject);
				}
			} catch (Exception e) {
				LOG.debug("Unable to read OCSP '{}' from the '{}' dictionary : {}", ii, dictionaryName, e.getMessage(), e);
			}
		}
	} else {
		LOG.debug("No OCSPs found in the '{}' dictionary", dictionaryName);
	}
	return ocspMap;
}
 
Example 5
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 6
Source File: ExternalResourcesOCSPSource.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * This method adds the OCSP basic ocspResponses to the general list.
 *
 * @param inputStream
 */
private void load(final InputStream inputStream) {
	try (InputStream is = inputStream) {
		final OCSPResp ocspResp = new OCSPResp(is);
		final BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject();
		addBinary(OCSPResponseBinary.build(basicOCSPResp), RevocationOrigin.EXTERNAL);
	} catch (Exception e) {
		throw new DSSException(e);
	}
}
 
Example 7
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 8
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 9
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 10
Source File: OnlineOCSPSource.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public OCSPToken getRevocationToken(CertificateToken certificateToken, CertificateToken issuerCertificateToken,
		List<String> alternativeUrls) {
	Objects.requireNonNull(dataLoader, "DataLoader is not provided !");

	final String dssIdAsString = certificateToken.getDSSIdAsString();
	LOG.trace("--> OnlineOCSPSource queried for {}", dssIdAsString);
	if (Utils.isCollectionNotEmpty(alternativeUrls)) {
		LOG.info("OCSP alternative urls : {}", alternativeUrls);
	}

	final List<String> ocspAccessLocations = DSSASN1Utils.getOCSPAccessLocations(certificateToken);
	if (Utils.isCollectionEmpty(ocspAccessLocations) && Utils.isCollectionEmpty(alternativeUrls)) {
		LOG.warn("No OCSP location found for {}", dssIdAsString);
		return null;
	}
	ocspAccessLocations.addAll(alternativeUrls);

	final CertificateID certId = DSSRevocationUtils.getOCSPCertificateID(certificateToken, issuerCertificateToken, certIDDigestAlgorithm);

	BigInteger nonce = null;
	if (nonceSource != null) {
		nonce = nonceSource.getNonce();
	}

	final byte[] content = buildOCSPRequest(certId, nonce);

	int nbTries = ocspAccessLocations.size();
	for (String ocspAccessLocation : ocspAccessLocations) {
		nbTries--;
		try {
			final byte[] ocspRespBytes = dataLoader.post(ocspAccessLocation, content);
			if (!Utils.isArrayEmpty(ocspRespBytes)) {
				final OCSPResp ocspResp = new OCSPResp(ocspRespBytes);
				verifyNonce(ocspResp, nonce);
				OCSPRespStatus status = OCSPRespStatus.fromInt(ocspResp.getStatus());
				if (OCSPRespStatus.SUCCESSFUL.equals(status)) {
					BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResp.getResponseObject();
					SingleResp latestSingleResponse = DSSRevocationUtils.getLatestSingleResponse(basicResponse, certificateToken, issuerCertificateToken);
					OCSPToken ocspToken = new OCSPToken(basicResponse, latestSingleResponse, certificateToken, issuerCertificateToken);
					ocspToken.setSourceURL(ocspAccessLocation);
					ocspToken.setExternalOrigin(RevocationOrigin.EXTERNAL);
					return ocspToken;
				} else {
					LOG.warn("Ignored OCSP Response from URL '{}' : status -> {}", ocspAccessLocation, status);
				}
			} else {
				LOG.warn("OCSP Data Loader for certificate {} responded with an empty byte array!", certificateToken.getDSSIdAsString());
			}
		} catch (Exception e) {
			if (nbTries == 0) {
				throw new DSSException("Unable to retrieve OCSP response", e);
			} else {
				LOG.warn("Unable to retrieve OCSP response with URL '{}' : {}", ocspAccessLocation, e.getMessage());
			}
		}
	}

	return null;
}
 
Example 11
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;
}