org.bouncycastle.cert.ocsp.OCSPResp Java Examples

The following examples show how to use org.bouncycastle.cert.ocsp.OCSPResp. 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: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
/**
 * OCSP Response Utils
 */
private String ocspResponseToB64(OCSPResp ocspResp)
{
  if (ocspResp == null)
  {
    return null;
  }
  try
  {
    return Base64.encodeBase64String(ocspResp.getEncoded());
  }
  catch (Throwable ex)
  {
    LOGGER.debug("Could not convert OCSP Response to Base64");
    return null;
  }
}
 
Example #2
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 #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: CMSOCSPSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void addBasicOcspRespFrom_id_ri_ocsp_response() {
	final Store otherRevocationInfo = cmsSignedData.getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response);
	final Collection otherRevocationInfoMatches = otherRevocationInfo.getMatches(null);
	for (final Object object : otherRevocationInfoMatches) {
		if (object instanceof ASN1Sequence) {
			final ASN1Sequence otherRevocationInfoMatch = (ASN1Sequence) object;
			final BasicOCSPResp basicOCSPResp;
			if (otherRevocationInfoMatch.size() == 4) {
				basicOCSPResp = DSSRevocationUtils.getBasicOcspResp(otherRevocationInfoMatch);
			} else {
				final OCSPResp ocspResp = DSSRevocationUtils.getOcspResp(otherRevocationInfoMatch);
				basicOCSPResp = DSSRevocationUtils.fromRespToBasic(ocspResp);
			}

			OCSPResponseBinary ocspResponseIdentifier = OCSPResponseBinary.build(basicOCSPResp);
			ocspResponseIdentifier.setAsn1ObjectIdentifier(CMSObjectIdentifiers.id_ri_ocsp_response);
			addBinary(ocspResponseIdentifier, RevocationOrigin.CMS_SIGNED_DATA);
		} else {
			LOG.warn("Unsupported object type for id_ri_ocsp_response (SHALL be an ASN1Sequence) : {}", object.getClass().getSimpleName());
		}
	}
}
 
Example #5
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 #6
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 #7
Source File: AbstractOcspRequestor.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Override
public OCSPResp ask(X509Cert issuerCert, X509Cert[] certs,
    URL responderUrl, RequestOptions requestOptions, ReqRespDebug debug)
    throws OcspResponseException, OcspRequestorException {
  Args.notNull(issuerCert, "issuerCert");
  Args.notNull(certs, "certs");
  Args.positive(certs.length, "certs.length");

  BigInteger[] serialNumbers = new BigInteger[certs.length];
  for (int i = 0; i < certs.length; i++) {
    X509Cert cert = certs[i];
    try {
      if (!X509Util.issues(issuerCert, cert)) {
        throw new IllegalArgumentException(
            "cert at index " + i + " and issuerCert do not match");
      }
    } catch (CertificateEncodingException ex) {
      throw new OcspRequestorException(ex.getMessage(), ex);
    }
    serialNumbers[i] = cert.getSerialNumber();
  }

  return ask(issuerCert, serialNumbers, responderUrl, requestOptions, debug);
}
 
Example #8
Source File: AbstractOcspRequestor.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Override
public OCSPResp ask(X509Cert issuerCert, X509Cert cert,
    URL responderUrl, RequestOptions requestOptions, ReqRespDebug debug)
    throws OcspResponseException, OcspRequestorException {
  Args.notNull(issuerCert, "issuerCert");
  Args.notNull(cert, "cert");

  try {
    if (!X509Util.issues(issuerCert, cert)) {
      throw new IllegalArgumentException("cert and issuerCert do not match");
    }
  } catch (CertificateEncodingException ex) {
    throw new OcspRequestorException(ex.getMessage(), ex);
  }

  return ask(issuerCert, new BigInteger[]{cert.getSerialNumber()}, responderUrl,
      requestOptions, debug);
}
 
Example #9
Source File: OcspQa.java    From xipki with Apache License 2.0 6 votes vote down vote up
public ValidationResult checkOcsp(OCSPResp response, OcspError expectedOcspError) {
  Args.notNull(response, "response");
  Args.notNull(expectedOcspError, "expectedOcspError");

  List<ValidationIssue> resultIssues = new LinkedList<ValidationIssue>();

  int status = response.getStatus();

  // Response status
  ValidationIssue issue = new ValidationIssue("OCSP.STATUS", "response.status");
  resultIssues.add(issue);
  if (status != expectedOcspError.getStatus()) {
    issue.setFailureMessage("is '" + Unsuccessful.getStatusText(status) + "', but expected '"
        + Unsuccessful.getStatusText(expectedOcspError.getStatus()) + "'");
  }

  return new ValidationResult(resultIssues);
}
 
Example #10
Source File: OcspServerExample.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static ChannelInitializer<Channel> newServerHandler(final ReferenceCountedOpenSslContext context,
        final OCSPResp response) {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            SslHandler sslHandler = context.newHandler(ch.alloc());

            if (response != null) {
                ReferenceCountedOpenSslEngine engine
                    = (ReferenceCountedOpenSslEngine) sslHandler.engine();

                engine.setOcspResponse(response.getEncoded());
            }

            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(sslHandler);

            // so on and so forth...
        }
    };
}
 
Example #11
Source File: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Convert a BasicOCSPResp in OCSPResp (connection status is set to
 * SUCCESSFUL).
 *
 * @param basicOCSPRespBinary
 *            the binary of BasicOCSPResp
 * @return an instance of OCSPResp
 */
public static OCSPResp fromBasicToResp(final byte[] basicOCSPRespBinary) {
	final OCSPResponseStatus responseStatus = new OCSPResponseStatus(OCSPResponseStatus.SUCCESSFUL);
	final DEROctetString derBasicOCSPResp = new DEROctetString(basicOCSPRespBinary);
	final ResponseBytes responseBytes = new ResponseBytes(OCSPObjectIdentifiers.id_pkix_ocsp_basic, derBasicOCSPResp);
	final OCSPResponse ocspResponse = new OCSPResponse(responseStatus, responseBytes);
	// !!! todo to be checked: System.out.println("===> RECREATED: " +
	// ocspResp.hashCode());
	return new OCSPResp(ocspResponse);
}
 
Example #12
Source File: OcspQa.java    From xipki with Apache License 2.0 5 votes vote down vote up
public ValidationResult checkOcsp(OCSPResp response, IssuerHash issuerHash,
    BigInteger serialNumber, byte[] encodedCert,
    OcspCertStatus expectedOcspStatus, OcspResponseOption responseOption,
    Date exptectedRevTime, boolean noSigVerify) {
  List<BigInteger> serialNumbers = new ArrayList<>(1);
  serialNumbers.add(serialNumber);

  Map<BigInteger, byte[]> encodedCerts = null;
  if (encodedCert != null) {
    encodedCerts = new HashMap<>();
    encodedCerts.put(serialNumber, encodedCert);
  }

  Map<BigInteger, OcspCertStatus> expectedOcspStatuses = null;
  if (expectedOcspStatus != null) {
    expectedOcspStatuses = new HashMap<>();
    expectedOcspStatuses.put(serialNumber, expectedOcspStatus);
  }

  Map<BigInteger, Date> exptectedRevTimes = null;
  if (exptectedRevTime != null) {
    exptectedRevTimes = new HashMap<>();
    exptectedRevTimes.put(serialNumber, exptectedRevTime);
  }

  return checkOcsp(response, issuerHash, serialNumbers, encodedCerts,
      expectedOcspStatuses, exptectedRevTimes, responseOption, noSigVerify);
}
 
Example #13
Source File: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static byte[] getEncodedFromBasicResp(final BasicOCSPResp basicOCSPResp) {
	try {
		if (basicOCSPResp != null) {
			final OCSPResp ocspResp = DSSRevocationUtils.fromBasicToResp(basicOCSPResp);
			return ocspResp.getEncoded();
		} else {
			throw new DSSException("Empty OCSP response");
		}
	} catch (IOException e) {
		throw new DSSException("OCSP encoding error: " + e.getMessage(), e);
	}
}
 
Example #14
Source File: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static byte[] getEncoded(OCSPResp ocspResp) {
	try {
		return ocspResp.getEncoded();
	} catch (IOException e) {
		throw new DSSException(e);
	}
}
 
Example #15
Source File: DSSRevocationUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Convert a BasicOCSPResp in OCSPResp (connection status is set to
 * SUCCESSFUL).
 *
 * @param basicOCSPResp
 *            the {@code BasicOCSPResp} to be converted to {@code OCSPResp}
 * @return the result of the conversion
 */
public static OCSPResp fromBasicToResp(final BasicOCSPResp basicOCSPResp) {
	try {
		final byte[] encoded = basicOCSPResp.getEncoded();
		return fromBasicToResp(encoded);
	} catch (IOException e) {
		throw new DSSException(e);
	}
}
 
Example #16
Source File: DSSRevocationUtilsTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testRevocationOCSP() throws IOException {
	BasicOCSPResp basicOCSPResp = DSSRevocationUtils.loadOCSPBase64Encoded(
			"MIIH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Q3AqClqI00OxY/GuK840FNUTf5RDt+aOgbgkTVb8n1lJBS05aQddFowA3k4fnxHtgyiR6KygYO3Fsl2MeEJCKgYlRaB0bqiN1A3hzMKXq3S7+l6yUKPnkNg5Nci6PoztZSe7z/TbbUyu8dY+CVYnjgy85AcUhT1tJwoa527ZfgNVDq/6GLLF3ZQzUNNebF90aZlwsW+sFtk9xkxAWuFcSkRq+IaKz/hDhVYlSYaIBlpgjR8YIIaqtky9xakC8bs8KWdBh1DcRxgdAUfLCqHMd3PwkWEw2PmLpqLZeuHFJzb7zeAcXvvVkP");
	assertNotNull(basicOCSPResp);

	OCSPResp ocspResp = DSSRevocationUtils.fromBasicToResp(basicOCSPResp);
	assertNotNull(ocspResp);

	BasicOCSPResp basicOCSPResp2 = DSSRevocationUtils.fromRespToBasic(ocspResp);
	assertNotNull(basicOCSPResp2);

	assertEquals(basicOCSPResp, basicOCSPResp2);
}
 
Example #17
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 #18
Source File: OCSPCertificateVerifier.java    From oxAuth with MIT License 5 votes vote down vote up
public OCSPResp requestOCSPResponse(String url, OCSPReq ocspReq) throws IOException, MalformedURLException {
	byte[] ocspReqData = ocspReq.getEncoded();

	HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
	try {
		con.setRequestProperty("Content-Type", "application/ocsp-request");
		con.setRequestProperty("Accept", "application/ocsp-response");

		con.setDoInput(true);
		con.setDoOutput(true);
		con.setUseCaches(false);

		OutputStream out = con.getOutputStream();
		try {
			IOUtils.write(ocspReqData, out);
			out.flush();
		} finally {
			IOUtils.closeQuietly(out);
		}

		byte[] responseBytes = IOUtils.toByteArray(con.getInputStream());
		OCSPResp ocspResp = new OCSPResp(responseBytes);

		return ocspResp;
	} finally {
		if (con != null) {
			con.disconnect();
		}
	}
}
 
Example #19
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 #20
Source File: OnlineOCSPSource.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void verifyNonce(final OCSPResp ocspResp, final BigInteger expectedNonceValue) {
	if (expectedNonceValue != null) {
		BigInteger receivedNonce = getEmbeddedNonceValue(ocspResp);
		if (!expectedNonceValue.equals(receivedNonce)) {
			throw new DSSException(String.format("Nonce received from OCSP response '%s' does not match a dispatched nonce '%s'.", 
					receivedNonce, expectedNonceValue));
		}
	}
}
 
Example #21
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
private OCSPResp b64ToOCSPResp(String ocspRespB64)
{
  try
  {
    return new OCSPResp(Base64.decodeBase64(ocspRespB64));
  }
  catch (Throwable ex)
  {
    LOGGER.debug("Could not cover OCSP Response from Base64 to OCSPResp object");
    return null;
  }
}
 
Example #22
Source File: OcspRef.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
OcspRef(byte[] inOcspEncoded) {
   this.ocspEncoded = ArrayUtils.clone(inOcspEncoded);

   try {
      this.ocsp = (BasicOCSPResp)(new OCSPResp(this.ocspEncoded)).getResponseObject();
   } catch (Exception var3) {
      throw new IllegalArgumentException(var3);
   }
}
 
Example #23
Source File: OcspRef.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
OcspRef(byte[] inOcspEncoded) {
   this.ocspEncoded = ArrayUtils.clone(inOcspEncoded);

   try {
      this.ocsp = (BasicOCSPResp)(new OCSPResp(this.ocspEncoded)).getResponseObject();
   } catch (Exception var3) {
      throw new IllegalArgumentException(var3);
   }
}
 
Example #24
Source File: OcspRef.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
OcspRef(byte[] inOcspEncoded) {
   this.ocspEncoded = ArrayUtils.clone(inOcspEncoded);

   try {
      this.ocsp = (BasicOCSPResp)(new OCSPResp(this.ocspEncoded)).getResponseObject();
   } catch (Exception var3) {
      throw new IllegalArgumentException(var3);
   }
}
 
Example #25
Source File: OcspRef.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
OcspRef(byte[] inOcspEncoded) {
   this.ocspEncoded = ArrayUtils.clone(inOcspEncoded);

   try {
      this.ocsp = (BasicOCSPResp)(new OCSPResp(this.ocspEncoded)).getResponseObject();
   } catch (Exception var3) {
      throw new IllegalArgumentException(var3);
   }
}
 
Example #26
Source File: OcspRef.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
OcspRef(byte[] inOcspEncoded) {
   this.ocspEncoded = ArrayUtils.clone(inOcspEncoded);

   try {
      this.ocsp = (BasicOCSPResp)(new OCSPResp(this.ocspEncoded)).getResponseObject();
   } catch (Exception var3) {
      throw new IllegalArgumentException(var3);
   }
}
 
Example #27
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 #28
Source File: AbstractOcspRequestor.java    From xipki with Apache License 2.0 4 votes vote down vote up
@Override
public OCSPResp ask(X509Cert issuerCert, BigInteger serialNumber, URL responderUrl,
    RequestOptions requestOptions, ReqRespDebug debug)
    throws OcspResponseException, OcspRequestorException {
  return ask(issuerCert, new BigInteger[]{serialNumber}, responderUrl, requestOptions, debug);
}
 
Example #29
Source File: OcspHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    final byte[] buffy = new byte[16384];
    try (InputStream requestStream = exchange.getInputStream()) {
        requestStream.read(buffy);
    }

    final OCSPReq request = new OCSPReq(buffy);
    final Req[] requested = request.getRequestList();

    final Extension nonce = request.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);

    final DigestCalculator sha1Calculator = new JcaDigestCalculatorProviderBuilder().build()
            .get(AlgorithmIdentifier.getInstance(RespID.HASH_SHA1));

    final BasicOCSPRespBuilder responseBuilder = new BasicOCSPRespBuilder(subjectPublicKeyInfo, sha1Calculator);

    if (nonce != null) {
        responseBuilder.setResponseExtensions(new Extensions(nonce));
    }

    for (final Req req : requested) {
        final CertificateID certId = req.getCertID();

        final BigInteger certificateSerialNumber = certId.getSerialNumber();
        responseBuilder.addResponse(certId, REVOKED_CERTIFICATES_STATUS.get(certificateSerialNumber));
    }

    final ContentSigner contentSigner = new BcRSAContentSignerBuilder(
            new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption),
            new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)).build(privateKey);

    final OCSPResp response = new OCSPRespBuilder().build(OCSPResp.SUCCESSFUL,
            responseBuilder.build(contentSigner, chain, new Date()));

    final byte[] responseBytes = response.getEncoded();

    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    responseHeaders.put(Headers.CONTENT_TYPE, "application/ocsp-response");

    final Sender responseSender = exchange.getResponseSender();
    responseSender.send(ByteBuffer.wrap(responseBytes));

    exchange.endExchange();
}
 
Example #30
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;
}