List of usage examples for org.bouncycastle.cert.ocsp BasicOCSPResp getResponses
public SingleResp[] getResponses()
From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java
License:Open Source License
private void validateSuccessfulResponse(final BasicOCSPResp basicOcspResponse, final PublicKey publicKey) throws Exception { assertNotNull("Signed request generated null-response.", basicOcspResponse); assertTrue("OCSP response was not signed correctly.", basicOcspResponse.isSignatureValid(new JcaContentVerifierProviderBuilder().build(publicKey))); final SingleResp[] singleResponses = basicOcspResponse.getResponses(); assertEquals("Delivered some thing else than one and exactly one response.", 1, singleResponses.length); assertEquals("Response cert did not match up with request cert", ocspSigningCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); assertEquals("Status is not null (good)", null, singleResponses[0].getCertStatus()); }
From source file:org.cesecore.util.PKIXCertRevocationStatusChecker.java
License:Open Source License
/** * Sends an OCSP request, gets a response and verifies the response as much as possible before returning it to the caller. * // w ww. j a v a 2s. c om * @return The OCSP response, or null of no correct response could be obtained. */ private SingleResp getOCSPResponse(final String ocspurl, final OCSPReq ocspRequest, final Certificate cert, final byte[] nonce, int expectedOcspRespCode, int expectedHttpRespCode) { if (log.isDebugEnabled()) { log.debug("Sending OCSP request to " + ocspurl + " regarding certificate with SubjectDN: " + CertTools.getSubjectDN(cert) + " - IssuerDN: " + CertTools.getIssuerDN(cert)); } //----------------------- Open connection and send the request --------------// OCSPResp response = null; HttpURLConnection con = null; try { final URL url = new URL(ocspurl); con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); // POST it con.setRequestProperty("Content-Type", "application/ocsp-request"); OutputStream os = con.getOutputStream(); os.write(ocspRequest.getEncoded()); os.close(); final int httpRespCode = ((HttpURLConnection) con).getResponseCode(); if (httpRespCode != expectedHttpRespCode) { log.info("HTTP response from OCSP request was " + httpRespCode + ". Expected " + expectedHttpRespCode); handleContentOfErrorStream(con.getErrorStream()); return null; // if it is an http error code we don't need to test any more } InputStream is = con.getInputStream(); response = new OCSPResp(IOUtils.toByteArray(is)); is.close(); } catch (IOException e) { log.info("Unable to get an OCSP response. " + e.getLocalizedMessage()); if (con != null) { handleContentOfErrorStream(con.getErrorStream()); } return null; } // ------------ Verify the response signature --------------// BasicOCSPResp brep = null; try { brep = (BasicOCSPResp) response.getResponseObject(); if ((expectedOcspRespCode != OCSPRespBuilder.SUCCESSFUL) && (brep != null)) { log.warn("According to RFC 2560, responseBytes are not set on error, but we got some."); return null; // it messes up testing of invalid signatures... but is needed for the unsuccessful responses } if (brep == null) { log.warn("Cannot extract OCSP response object. OCSP response status: " + response.getStatus()); return null; } X509CertificateHolder[] chain = brep.getCerts(); boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder() .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(chain[0])); if (!verify) { log.warn("OCSP response signature was not valid"); return null; } } catch (OCSPException | OperatorCreationException | CertificateException e) { if (log.isDebugEnabled()) { log.debug("Failed to obtain or verify OCSP response. " + e.getLocalizedMessage()); } return null; } // ------------- Verify the nonce ---------------// byte[] noncerep; try { noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue().getEncoded(); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to read extension from OCSP response. " + e.getLocalizedMessage()); } return null; } if (noncerep == null) { log.warn("Sent an OCSP request containing a nonce, but the OCSP response does not contain a nonce"); return null; } try { ASN1InputStream ain = new ASN1InputStream(noncerep); ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject()); ain.close(); if (!Arrays.equals(nonce, oct.getOctets())) { log.warn("The nonce in the OCSP request and the OCSP response do not match"); return null; } } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to read extension from OCSP response. " + e.getLocalizedMessage()); } return null; } // ------------ Extract the single response and verify that it concerns a cert with the right serialnumber ----// SingleResp[] singleResps = brep.getResponses(); if ((singleResps == null) || (singleResps.length == 0)) { if (log.isDebugEnabled()) { log.debug("The OCSP response object contained no responses."); } return null; } SingleResp singleResponse = singleResps[0]; CertificateID certId = singleResponse.getCertID(); if (!certId.getSerialNumber().equals(CertTools.getSerialNumber(cert))) { if (log.isDebugEnabled()) { log.debug( "Certificate serialnumber in response does not match certificate serialnumber in request."); } return null; } // ------------ Return the single response ---------------// return singleResponse; }
From source file:org.codice.ddf.security.ocsp.checker.OcspChecker.java
License:Open Source License
/** * Gets the {@link CertificateStatus} from the given {@param ocspResponse}. * * @param ocspResponse - the {@link OCSPResp} to get the {@link CertificateStatus} from. * @return the {@link CertificateStatus} from the given {@param ocspResponse}. Returns an {@link * UnknownStatus} if the status could not be found. *///from ww w .j a v a 2s. co m private CertificateStatus getStatusFromOcspResponse(OCSPResp ocspResponse) { try { BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); if (basicResponse == null) { return new UnknownStatus(); } SingleResp[] singleResps = basicResponse.getResponses(); if (singleResps == null) { return new UnknownStatus(); } SingleResp response = Arrays.stream(singleResps).findFirst().orElse(null); if (response == null) { return new UnknownStatus(); } return response.getCertStatus(); } catch (OCSPException e) { return new UnknownStatus(); } }
From source file:org.digidoc4j.impl.bdoc.ocsp.SKOnlineOCSPSource.java
License:GNU General Public License
@Override public OCSPToken getOCSPToken(CertificateToken certificateToken, CertificateToken issuerCertificateToken) { logger.debug("Getting OCSP token"); if (dataLoader == null) { throw new RuntimeException("Data loader is null"); }/*from w w w .jav a 2 s . c o m*/ try { final String dssIdAsString = certificateToken.getDSSIdAsString(); if (logger.isTraceEnabled()) { logger.trace("--> OnlineOCSPSource queried for " + dssIdAsString); } final String ocspUri = getAccessLocation(); logger.debug("Getting OCSP token from URI: " + ocspUri); if (ocspUri == null) { return null; } Extension nonceExtension = createNonce(); final byte[] content = buildOCSPRequest(certificateToken, issuerCertificateToken, nonceExtension); final byte[] ocspRespBytes = dataLoader.post(ocspUri, content); final OCSPResp ocspResp = new OCSPResp(ocspRespBytes); BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject(); if (basicOCSPResp == null) { logger.error("OCSP response is empty"); return null; } checkNonce(basicOCSPResp, nonceExtension); Date bestUpdate = null; SingleResp bestSingleResp = null; final CertificateID certId = DSSRevocationUtils.getOCSPCertificateID(certificateToken, issuerCertificateToken); for (final SingleResp singleResp : basicOCSPResp.getResponses()) { if (DSSRevocationUtils.matches(certId, singleResp)) { final Date thisUpdate = singleResp.getThisUpdate(); if (bestUpdate == null || thisUpdate.after(bestUpdate)) { bestSingleResp = singleResp; bestUpdate = thisUpdate; } } } if (bestSingleResp != null) { OCSPToken ocspToken = new OCSPToken(); ocspToken.setBasicOCSPResp(basicOCSPResp); ocspToken.setBestSingleResp(bestSingleResp); ocspToken.setSourceURL(ocspUri); certificateToken.addRevocationToken(ocspToken); return ocspToken; } } catch (OCSPException e) { logger.error("OCSP error: " + e.getMessage(), e); } catch (IOException e) { throw new DSSException(e); } return null; }
From source file:org.ejbca.core.protocol.ocsp.extension.unid.OCSPUnidResponse.java
License:Open Source License
public int getStatus() { if (resp == null) { return OCSPUnidResponse.OCSP_UNKNOWN; }//from w ww.j a v a2s .c o m try { BasicOCSPResp brep; brep = (BasicOCSPResp) resp.getResponseObject(); SingleResp[] singleResps = brep.getResponses(); SingleResp singleResp = singleResps[0]; Object status = singleResp.getCertStatus(); if (status == null) { return OCSPUnidResponse.OCSP_GOOD; } if (status instanceof RevokedStatus) { return OCSPUnidResponse.OCSP_REVOKED; } if (status instanceof UnknownStatus) { return OCSPUnidResponse.OCSP_UNKNOWN; } } catch (OCSPException e) { // Ignore, default return } return OCSPUnidResponse.OCSP_UNKNOWN; }
From source file:org.ejbca.core.protocol.ocsp.OcspJunitHelper.java
License:Open Source License
/** * * @param ocspPackage/*from w ww .j ava 2 s .co m*/ * @param nonce * @param respCode expected response code, OK = 0, if not 0, response checking will not continue after response code is checked. * @param httpCode, normally 200 for OK or OCSP error. Can be 400 is more than 1 million bytes is sent for example * @return a SingleResp or null if respCode != 0 * @throws IOException * @throws OCSPException * @throws NoSuchProviderException * @throws CertificateException on parsing errors. * @throws OperatorCreationException */ protected SingleResp[] sendOCSPPost(byte[] ocspPackage, String nonce, int respCode, int httpCode) throws IOException, OCSPException, NoSuchProviderException, OperatorCreationException, CertificateException { // POST the OCSP request URL url = new URL(this.sBaseURL + this.urlEnding); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); // POST it con.setRequestProperty("Content-Type", "application/ocsp-request"); OutputStream os = con.getOutputStream(); os.write(ocspPackage); os.close(); assertEquals("Response code", httpCode, con.getResponseCode()); if (con.getResponseCode() != 200) { return null; // if it is an http error code we don't need to test any more } // Some appserver (Weblogic) responds with "application/ocsp-response; charset=UTF-8" assertNotNull("No Content-Type in reply.", con.getContentType()); assertTrue(con.getContentType().startsWith("application/ocsp-response")); OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream())); assertEquals("Response status not the expected.", respCode, response.getStatus()); if (respCode != 0) { assertNull("According to RFC 2560, responseBytes are not set on error.", response.getResponseObject()); return null; // it messes up testing of invalid signatures... but is needed for the unsuccessful responses } BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject(); X509CertificateHolder[] chain = brep.getCerts(); assertNotNull( "No certificate chain returned in response (chain == null), is ocsp.includesignercert=false in ocsp.properties?. It should be set to default value for test to run.", chain); boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(chain[0])); assertTrue("Response failed to verify.", verify); // Check nonce (if we sent one) if (nonce != null) { byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue() .getEncoded(); assertNotNull(noncerep); ASN1InputStream ain = new ASN1InputStream(noncerep); ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject()); ain.close(); assertEquals(nonce, new String(oct.getOctets())); } SingleResp[] singleResps = brep.getResponses(); return singleResps; }
From source file:org.ejbca.core.protocol.ocsp.ProtocolLookupServerHttpTest.java
License:Open Source License
/** * Tests ocsp message with good status and a valid unid * /*from ww w . j a va2 s . co m*/ * @throws Exception error */ @Test public void test01OcspGoodWithFnr() throws Exception { // Make user that we know... boolean userExists = false; try { endEntityManagementSession.addUser(admin, "unidtest", "foo123", "C=SE,O=AnaTom,surname=Jansson,serialNumber=123456789,CN=UNIDTest", null, "unidtest@anatom.se", false, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.TOKEN_SOFT_PEM, 0, caid); log.debug( "created user: unidtest, foo123, C=SE, O=AnaTom,surname=Jansson,serialNumber=123456789, CN=UNIDTest"); } catch (EndEntityExistsException e) { userExists = true; } if (userExists) { log.debug("User unidtest already exists."); EndEntityInformation userData = new EndEntityInformation("unidtest", "C=SE,O=AnaTom,surname=Jansson,serialNumber=123456789,CN=UNIDTest", caid, null, "unidtest@anatom.se", EndEntityConstants.STATUS_NEW, EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, null, SecConst.TOKEN_SOFT_PEM, 0, null); userData.setPassword("foo123"); endEntityManagementSession.changeUser(admin, userData, false); log.debug("Reset status to NEW"); } // Generate certificate for the new user // user that we know exists... ocspTestCert = (X509Certificate) signSession.createCertificate(admin, "unidtest", "foo123", new PublicKeyWrapper(keys.getPublic())); assertNotNull("Failed to create certificate", ocspTestCert); // And an OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, ocspTestCert.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(FnrFromUnidExtension.FnrFromUnidOid, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq req = gen.build(); // Send the request and receive a BasicResponse BasicOCSPResp brep = sendOCSPPost(req.getEncoded(), true); assertEquals(getFnr(brep), "654321"); SingleResp[] singleResps = brep.getResponses(); assertEquals("No of SingResps should be 1.", singleResps.length, 1); SingleResp singleResp = singleResps[0]; CertificateID certId = singleResp.getCertID(); assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), ocspTestCert.getSerialNumber()); Object status = singleResp.getCertStatus(); assertEquals("Status is not null (good)", status, null); }
From source file:org.ejbca.core.protocol.ocsp.ProtocolLookupServerHttpTest.java
License:Open Source License
/** * Tests ocsp message with bad status and a valid unid * // ww w . ja va 2s. co m * @throws Exception error */ @Test public void test02OcspBadWithFnr() throws Exception { revocationSession.revokeCertificate(admin, ocspTestCert, null, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE, null); // And an OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, ocspTestCert.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(FnrFromUnidExtension.FnrFromUnidOid, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq req = gen.build(); // Send the request and receive a BasicResponse BasicOCSPResp brep = sendOCSPPost(req.getEncoded(), true); // When a certificate is revoked the FNR must not be returned assertEquals(getFnr(brep), null); SingleResp[] singleResps = brep.getResponses(); assertEquals("No of SingResps should be 1.", singleResps.length, 1); SingleResp singleResp = singleResps[0]; CertificateID certId = singleResp.getCertID(); assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), ocspTestCert.getSerialNumber()); Object status = singleResp.getCertStatus(); assertTrue("Status is not RevokedStatus", status instanceof RevokedStatus); RevokedStatus rev = (RevokedStatus) status; assertTrue("Status does not have reason", rev.hasRevocationReason()); int reason = rev.getRevocationReason(); assertEquals("Wrong revocation reason", reason, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE); }
From source file:org.ejbca.core.protocol.ocsp.ProtocolLookupServerHttpTest.java
License:Open Source License
/** * Tests ocsp message with good status and invalid unid * //from www . j a v a 2s .c o m * @throws Exception error */ @Test public void test03OcspGoodWithNoFnr() throws Exception { // Change uses to a Unid that we don't have mapping for EndEntityInformation userData = new EndEntityInformation("unidtest", "C=SE,O=AnaTom,surname=Jansson,serialNumber=123456789,CN=UNIDTest", caid, null, "unidtest@anatom.se", EndEntityConstants.STATUS_NEW, EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, null, SecConst.TOKEN_SOFT_PEM, 0, null); userData.setPassword("foo123"); endEntityManagementSession.changeUser(admin, userData, false); log.debug("Reset status to NEW"); // Generate certificate for the new/changed user ocspTestCert = (X509Certificate) signSession.createCertificate(admin, "unidtest", "foo123", new PublicKeyWrapper(keys.getPublic())); assertNotNull("Failed to create certificate", ocspTestCert); // And an OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, ocspTestCert.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(FnrFromUnidExtension.FnrFromUnidOid, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq req = gen.build(); // Send the request and receive a BasicResponse BasicOCSPResp brep = sendOCSPPost(req.getEncoded(), true); assertEquals(getFnr(brep), null); SingleResp[] singleResps = brep.getResponses(); assertEquals("No of SingResps should be 1.", singleResps.length, 1); SingleResp singleResp = singleResps[0]; CertificateID certId = singleResp.getCertID(); assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), ocspTestCert.getSerialNumber()); Object status = singleResp.getCertStatus(); assertEquals("Status is not null (good)", status, null); }
From source file:org.ejbca.core.protocol.ocsp.ProtocolLookupServerHttpTest.java
License:Open Source License
/** * Tests ocsp message with good status but no serialNnumber in the DN * /* ww w . java 2 s.com*/ * @throws Exception error */ @Test public void test04OcspGoodNoSerialNo() throws Exception { // Change uses to not have any serialNumber EndEntityInformation userData = new EndEntityInformation("unidtest", "C=SE,O=AnaTom,surname=Jansson,serialNumber=123456789,CN=UNIDTest", caid, null, "unidtest@anatom.se", EndEntityConstants.STATUS_NEW, EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, null, SecConst.TOKEN_SOFT_PEM, 0, null); userData.setPassword("foo123"); endEntityManagementSession.changeUser(admin, userData, false); log.debug("Reset status to NEW"); // Generate certificate for the new/changed user ocspTestCert = (X509Certificate) signSession.createCertificate(admin, "unidtest", "foo123", new PublicKeyWrapper(keys.getPublic())); assertNotNull("Failed to create certificate", ocspTestCert); // And an OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, ocspTestCert.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(FnrFromUnidExtension.FnrFromUnidOid, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq req = gen.build(); // Send the request and receive a BasicResponse BasicOCSPResp brep = sendOCSPPost(req.getEncoded(), true); assertEquals(getFnr(brep), null); SingleResp[] singleResps = brep.getResponses(); assertEquals("No of SingResps should be 1.", singleResps.length, 1); SingleResp singleResp = singleResps[0]; CertificateID certId = singleResp.getCertID(); assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), ocspTestCert.getSerialNumber()); Object status = singleResp.getCertStatus(); assertEquals("Status is not null (good)", status, null); }