org.bouncycastle.cert.ocsp.SingleResp Java Examples

The following examples show how to use org.bouncycastle.cert.ocsp.SingleResp. 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: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Checks if OCSP revocation refers to the document signing certificate.
 * @return true if it checks false otherwise
 * @since	2.1.6
 */
public boolean isRevocationValid() {
    if (basicResp == null)
        return false;
    if (signCerts.size() < 2)
        return false;
    try {
        X509Certificate[] cs = (X509Certificate[])getSignCertificateChain();
        SingleResp sr = basicResp.getResponses()[0];
        CertificateID cid = sr.getCertID();
        X509Certificate sigcer = getSigningCertificate();
        X509Certificate isscer = cs[1];
        CertificateID tis = new CertificateID(
           new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(isscer), sigcer.getSerialNumber());
        return tis.equals(cid);
    }
    catch (Exception ex) {
    }
    return false;
}
 
Example #2
Source File: DSSRevocationUtilsTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testGetOCSPCertificateIDAndMatch() throws IOException {
	CertificateToken certificate = DSSUtils.loadCertificate(new File("src/test/resources/citizen_ca.cer"));
	CertificateToken issuer = DSSUtils.loadCertificate(new File("src/test/resources/belgiumrs2.crt"));
	assertTrue(certificate.isSignedBy(issuer));

	CertificateID certificateID = DSSRevocationUtils.getOCSPCertificateID(certificate, issuer, DigestAlgorithm.SHA256);
	assertNotNull(certificateID);

	BasicOCSPResp basicOCSPResp = DSSRevocationUtils.loadOCSPBase64Encoded(
			"MIIHOgoBAKCCBzMwggcvBgkrBgEFBQcwAQEEggcgMIIHHDCCATOhRDBCMQswCQYDVQQGEwJERTEaMBgGA1UECgwRQnVuZGVzbmV0emFnZW50dXIxFzAVBgNVBAMMDjE0Ui1PQ1NQIDEyOlBOGA8yMDE2MDQyNjA5NDE0M1owgbUwgbIwOzAJBgUrDgMC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NNebF90aZlwsW+sFtk9xkxAWuFcSkRq+IaKz/hDhVYlSYaIBlpgjR8YIIaqtky9xakC8bs8KWdBh1DcRxgdAUfLCqHMd3PwkWEw2PmLpqLZeuHFJzb7zeAcXvvVkP");

	SingleResp[] responses = basicOCSPResp.getResponses();

	assertFalse(DSSRevocationUtils.matches(certificateID, responses[0]));
}
 
Example #3
Source File: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * fix for certId.equals methods that doesn't work very well.
 *
 * @param certId
 *            {@code CertificateID}
 * @param singleResp
 *            {@code SingleResp}
 * @return true if the certificate matches this included in
 *         {@code SingleResp}
 */
public static boolean matches(final CertificateID certId, final SingleResp singleResp) {

	final CertificateID singleRespCertID = singleResp.getCertID();
	final ASN1ObjectIdentifier singleRespCertIDHashAlgOID = singleRespCertID.getHashAlgOID();
	final byte[] singleRespCertIDIssuerKeyHash = singleRespCertID.getIssuerKeyHash();
	final byte[] singleRespCertIDIssuerNameHash = singleRespCertID.getIssuerNameHash();
	final BigInteger singleRespCertIDSerialNumber = singleRespCertID.getSerialNumber();

	final ASN1ObjectIdentifier certIdHashAlgOID = certId.getHashAlgOID();
	final byte[] certIdIssuerKeyHash = certId.getIssuerKeyHash();
	final byte[] certIdIssuerNameHash = certId.getIssuerNameHash();
	final BigInteger certIdSerialNumber = certId.getSerialNumber();

	// certId.equals fails in comparing the algoIdentifier because
	// AlgoIdentifier params in null in one case and DERNull in another case
	return singleRespCertIDHashAlgOID.equals(certIdHashAlgOID) && Arrays.equals(singleRespCertIDIssuerKeyHash, certIdIssuerKeyHash)
			&& Arrays.equals(singleRespCertIDIssuerNameHash, certIdIssuerNameHash) && singleRespCertIDSerialNumber.equals(certIdSerialNumber);
}
 
Example #4
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 #5
Source File: OCSPToken.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * The default constructor to instantiate an OCSPToken with BasicOCSPResp only
 * 
 * @param basicOCSPResp    {@link BasicOCSPResp} containing the response
 *                         binaries
 * @param latestSingleResp {@link SingleResp} to be used with the current
 *                         certificate
 * @param certificate      {@link CertificateToken} to which the revocation data
 *                         is provided for
 * @param issuer           {@link CertificateToken} issued the
 *                         {@code certificateToken}
 */
public OCSPToken(final BasicOCSPResp basicOCSPResp, final SingleResp latestSingleResp, final CertificateToken certificate, CertificateToken issuer) {
	Objects.requireNonNull(basicOCSPResp, "The OCSP Response must be defined!");
	Objects.requireNonNull(certificate, "The related certificate token cannot be null!");
	this.basicOCSPResp = basicOCSPResp;
	this.productionDate = basicOCSPResp.getProducedAt();
	this.relatedCertificate = certificate;
	this.latestSingleResp = latestSingleResp;

	if (latestSingleResp != null) {
		this.thisUpdate = latestSingleResp.getThisUpdate();
		this.nextUpdate = latestSingleResp.getNextUpdate();
		extractStatusInfo(latestSingleResp);
		extractArchiveCutOff(latestSingleResp);
		extractCertHashExtension(latestSingleResp);
	}
	
	checkSignatureValidity(issuer);
}
 
Example #6
Source File: OfflineOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public List<RevocationToken<OCSP>> getRevocationTokens(CertificateToken certificate, CertificateToken issuer) {
	Objects.requireNonNull(certificate, "The certificate to be verified cannot be null");
	Objects.requireNonNull(issuer, "The issuer of the certificate to be verified cannot be null");

	List<RevocationToken<OCSP>> result = new ArrayList<>();
	final Set<EncapsulatedRevocationTokenIdentifier> collectedBinaries = getAllRevocationBinaries();
	LOG.trace("--> OfflineOCSPSource queried for {} contains: {} element(s).", certificate.getDSSIdAsString(), collectedBinaries.size());
	for (EncapsulatedRevocationTokenIdentifier binary : collectedBinaries) {
		OCSPResponseBinary ocspBinary = (OCSPResponseBinary) binary;
		BasicOCSPResp basicOCSPResp = ocspBinary.getBasicOCSPResp();
		SingleResp latestSingleResponse = DSSRevocationUtils.getLatestSingleResponse(basicOCSPResp, certificate, issuer);
		if (latestSingleResponse != null) {
			OCSPToken ocspToken = new OCSPToken(basicOCSPResp, latestSingleResponse, certificate, issuer);
			addRevocation(ocspToken, ocspBinary);
			result.add(ocspToken);
		}
	}
	LOG.trace("--> OfflineOCSPSource found result(s) : {}", result.size());
	return result;
}
 
Example #7
Source File: OCSPToken.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * This method extracts the CertHash extension if present
 * 
 * Common PKI Part 4: Operational Protocols
 * 3.1.2 Common PKI Private OCSP Extensions
 * 
 * CertHash ::= SEQUENCE {
 * hashAlgorithm AlgorithmIdentifier,
 * certificateHash OCTET STRING }
 * 
 * @param bestSingleResp
 *            the related SingleResponse
 */
private void extractCertHashExtension(SingleResp bestSingleResp) {
	Extension extension = bestSingleResp.getExtension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash);
	if (extension != null) {
		try {
			CertHash asn1CertHash = CertHash.getInstance(extension.getParsedValue());
			DigestAlgorithm digestAlgo = DigestAlgorithm.forOID(asn1CertHash.getHashAlgorithm().getAlgorithm().getId());
			Digest certHash = new Digest(digestAlgo, asn1CertHash.getCertificateHash());

			certHashPresent = true;
			byte[] expectedDigest = relatedCertificate.getDigest(certHash.getAlgorithm());
			byte[] foundDigest = certHash.getValue();
			certHashMatch = Arrays.equals(expectedDigest, foundDigest);

		} catch (Exception e) {
			LOG.warn("Unable to extract id_isismtt_at_certHash : {}", e.getMessage());
		}
	}
}
 
Example #8
Source File: OCSPToken.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void extractStatusInfo(SingleResp bestSingleResp) {
	org.bouncycastle.cert.ocsp.CertificateStatus certStatus = bestSingleResp.getCertStatus();
	if (org.bouncycastle.cert.ocsp.CertificateStatus.GOOD == certStatus) {
		if (LOG.isInfoEnabled()) {
			LOG.info("OCSP status is good");
		}
		status = CertificateStatus.GOOD;
	} else if (certStatus instanceof RevokedStatus) {
		if (LOG.isInfoEnabled()) {
			LOG.info("OCSP status revoked");
		}
		final RevokedStatus revokedStatus = (RevokedStatus) certStatus;
		status = CertificateStatus.REVOKED;
		revocationDate = revokedStatus.getRevocationTime();
		int reasonId = 0; // unspecified
		if (revokedStatus.hasRevocationReason()) {
			reasonId = revokedStatus.getRevocationReason();
		}
		reason = RevocationReason.fromInt(reasonId);
	} else if (certStatus instanceof UnknownStatus) {
		if (LOG.isInfoEnabled()) {
			LOG.info("OCSP status unknown");
		}
		status = CertificateStatus.UNKNOWN;
	} else {
		LOG.info("OCSP certificate status: {}", certStatus);
	}
}
 
Example #9
Source File: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static SingleResp getLatestSingleRespInList(List<SingleResp> singleResponses) {
	Date latest = null;
	SingleResp latestResp = null;
	for (SingleResp singleResp : singleResponses) {
		final Date thisUpdate = singleResp.getThisUpdate();
		if ((latest == null) || thisUpdate.after(latest)) {
			latestResp = singleResp;
			latest = thisUpdate;
		}
	}
	return latestResp;
}
 
Example #10
Source File: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static SingleResp getLatestSingleResponse(BasicOCSPResp basicResponse, CertificateToken certificate, CertificateToken issuer) {
	List<SingleResp> singleResponses = getSingleResponses(basicResponse, certificate, issuer);
	if (Utils.isCollectionEmpty(singleResponses)) {
		return null;
	} else if (singleResponses.size() == 1) {
		return singleResponses.get(0);
	} else {
		return getLatestSingleRespInList(singleResponses);
	}
}
 
Example #11
Source File: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static List<SingleResp> getSingleResponses(BasicOCSPResp basicResponse, CertificateToken certificate, CertificateToken issuer) {
	List<SingleResp> result = new ArrayList<>();
	SingleResp[] responses = getSingleResps(basicResponse);
	for (final SingleResp singleResp : responses) {
		DigestAlgorithm usedDigestAlgorithm = getUsedDigestAlgorithm(singleResp);
		final CertificateID certId = getOCSPCertificateID(certificate, issuer, usedDigestAlgorithm);
		if (DSSRevocationUtils.matches(certId, singleResp)) {
			result.add(singleResp);
		}
	}
	return result;
}
 
Example #12
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 #13
Source File: OCSPToken.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void extractArchiveCutOff(SingleResp bestSingleResp) {
	Extension extension = bestSingleResp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff);
	if (extension != null) {
		ASN1GeneralizedTime archiveCutOffAsn1 = (ASN1GeneralizedTime) extension.getParsedValue();
		try {
			archiveCutOff = archiveCutOffAsn1.getDate();
		} catch (ParseException e) {
			LOG.warn("Unable to extract id_pkix_ocsp_archive_cutoff : {}", e.getMessage());
		}
	}
}
 
Example #14
Source File: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static SingleResp[] getSingleResps(BasicOCSPResp basicResponse) {
	try {
		return basicResponse.getResponses();
	} catch (Exception e) {
		LOG.warn("Unable to extract SingleResp(s) : {}", e.getMessage());
		return new SingleResp[] {};
	}
}
 
Example #15
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 #16
Source File: OCSPToken.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
public SingleResp getLatestSingleResp() {
	return latestSingleResp;
}
 
Example #17
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;
}
 
Example #18
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 #19
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 #20
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 #21
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 #22
Source File: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Returns a DigestAlgorithm used in the given {@code singleResp}
 * 
 * @param singleResp {@link SingleResp} to extract the used SingleResp from
 * @return {@link SingleResp}
 */
public static DigestAlgorithm getUsedDigestAlgorithm(final SingleResp singleResp) {
	return DigestAlgorithm.forOID(singleResp.getCertID().getHashAlgOID().getId());
}