List of usage examples for org.bouncycastle.cert.ocsp BasicOCSPResp getResponses
public SingleResp[] getResponses()
From source file:org.ejbca.core.protocol.ocsp.ProtocolLookupServerHttpTest.java
License:Open Source License
/** * test a lookup message from an untrusted requestor, should not work * // w w w . ja va2 s .c o m * @throws Exception */ @Test public void test05HttpsNotAuthorized() throws Exception { // Change uses to a Unid that is OK 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"); userData.setStatus(EndEntityConstants.STATUS_NEW); 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(), false); 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
/** * test a lookup request with regular http, should not work * /*w w w .ja va 2 s . c o m*/ * @throws Exception */ @Test public void test06HttpNotAuthorized() throws Exception { // Change to use plain http, we should be able to get a OCSP response, but the FNR mapping // will not be returned bacuse it requires https with client authentication httpReqPath = "http://127.0.0.1:8080/ejbca"; // Change uses to a Unid that is OK 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.ProtocolOcspHttpPerfTest.java
License:Open Source License
private SingleResp sendOCSPPost(byte[] ocspPackage, String nonce) throws IOException, OCSPException, NoSuchProviderException, OperatorCreationException, CertificateException { // POST the OCSP request URL url = new URL(httpReqPath + '/' + resourceOcsp); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true);//ww w . j a v a 2s .c o m con.setRequestMethod("POST"); // POST it con.setRequestProperty("Content-Type", "application/ocsp-request"); OutputStream os = con.getOutputStream(); os.write(ocspPackage); os.close(); assertEquals("Response code", 200, con.getResponseCode()); assertEquals("Content-Type", "application/ocsp-response", con.getContentType()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This works for small requests, and OCSP requests are small InputStream in = con.getInputStream(); int b = in.read(); while (b != -1) { baos.write(b); b = in.read(); } baos.flush(); in.close(); byte[] respBytes = baos.toByteArray(); OCSPResp response = new OCSPResp(respBytes); assertEquals("Response status not zero.", response.getStatus(), 0); BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject(); X509CertificateHolder[] chain = brep.getCerts(); 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(); assertEquals("No of SingResps should be 1.", singleResps.length, 1); SingleResp singleResp = singleResps[0]; return singleResp; }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpStandaloneTest.java
License:Open Source License
private void testVerifyHttpGetHeaders(X509Certificate caCertificate, BigInteger serialNumber) throws Exception { // An OCSP request, ocspTestCert is already created in earlier tests OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, serialNumber)); OCSPReq req = gen.build();/*from w w w.j av a 2 s . co m*/ String reqString = new String(Base64.encode(req.getEncoded(), false)); URL url = new URL(httpReqPath + '/' + resourceOcsp + '/' + URLEncoder.encode(reqString, "UTF-8")); log.debug("OCSP Request: " + url.toExternalForm()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); assertEquals( "Response code did not match. (Make sure you allow encoded slashes in your appserver.. add -Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true in Tomcat)", 200, con.getResponseCode()); // Some appserver (Weblogic) responds with // "application/ocsp-response; charset=UTF-8" assertNotNull(con.getContentType()); assertTrue(con.getContentType().startsWith("application/ocsp-response")); OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream())); assertEquals("Response status not the expected.", OCSPRespBuilder.SUCCESSFUL, response.getStatus()); BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject(); // Just output the headers to stdout so we can visually inspect them if // something goes wrong Set<String> keys = con.getHeaderFields().keySet(); for (String field : keys) { List<String> values = con.getHeaderFields().get(field); for (String value : values) { log.info(field + ": " + value); } } String eTag = con.getHeaderField("ETag"); assertNotNull( "RFC 5019 6.2: No 'ETag' HTTP header present as it SHOULD. (Make sure ocsp.untilNextUpdate and ocsp.maxAge are configured for this test)", eTag); assertTrue("ETag is messed up.", ("\"" + new String( Hex.encode(MessageDigest.getInstance("SHA-1", "BC").digest(response.getEncoded()))) + "\"") .equals(eTag)); long date = con.getHeaderFieldDate("Date", -1); assertTrue("RFC 5019 6.2: No 'Date' HTTP header present as it SHOULD.", date != -1); long lastModified = con.getHeaderFieldDate("Last-Modified", -1); assertTrue("RFC 5019 6.2: No 'Last-Modified' HTTP header present as it SHOULD.", lastModified != -1); // assertTrue("Last-Modified is after response was sent", // lastModified<=date); This will not hold on JBoss AS due to the // caching of the Date-header long expires = con.getExpiration(); assertTrue("Expires is before response was sent", expires >= date); assertTrue("RFC 5019 6.2: No 'Expires' HTTP header present as it SHOULD.", expires != 0); String cacheControl = con.getHeaderField("Cache-Control"); assertNotNull("RFC 5019 6.2: No 'Cache-Control' HTTP header present as it SHOULD.", cacheControl); assertTrue("RFC 5019 6.2: No 'public' HTTP header Cache-Control present as it SHOULD.", cacheControl.contains("public")); assertTrue("RFC 5019 6.2: No 'no-transform' HTTP header Cache-Control present as it SHOULD.", cacheControl.contains("no-transform")); assertTrue("RFC 5019 6.2: No 'must-revalidate' HTTP header Cache-Control present as it SHOULD.", cacheControl.contains("must-revalidate")); Matcher matcher = Pattern.compile(".*max-age\\s*=\\s*(\\d+).*").matcher(cacheControl); assertTrue("RFC 5019 6.2: No 'max-age' HTTP header Cache-Control present as it SHOULD.", matcher.matches()); int maxAge = Integer.parseInt(matcher.group(1)); log.debug("maxAge=" + maxAge + " (expires-lastModified)/1000=" + ((expires - lastModified) / 1000)); assertTrue( "thisUpdate and nextUpdate should not be the same (Make sure ocsp.untilNextUpdate and ocsp.maxAge are configured for this test)", expires != lastModified); assertTrue("RFC 5019 6.2: [maxAge] SHOULD be 'later than thisUpdate but earlier than nextUpdate'.", maxAge < (expires - lastModified) / 1000); // assertTrue("Response cannot be produced after it was sent.", // brep.getProducedAt().getTime() <= date); This might not hold on JBoss // AS due to the caching of the Date-header X509CertificateHolder[] chain = brep.getCerts(); boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(chain[0])); assertTrue("Response failed to verify.", verify); assertNull("No nonce should be present.", brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce)); SingleResp[] singleResps = brep.getResponses(); assertNotNull("SingleResps should not be null.", singleResps); assertTrue("Expected a single SingleResp in the repsonse.", singleResps.length == 1); assertEquals("Serno in response does not match serno in request.", singleResps[0].getCertID().getSerialNumber(), serialNumber); assertEquals("Status is not null (null is 'good')", singleResps[0].getCertStatus(), null); assertTrue( "RFC 5019 6.2: Last-Modified SHOULD 'be the same as the thisUpdate timestamp in the request itself'", singleResps[0].getThisUpdate().getTime() == lastModified); assertTrue("RFC 5019 6.2: Expires SHOULD 'be the same as the nextUpdate timestamp in the request itself'", singleResps[0].getNextUpdate().getTime() == expires); assertTrue("Response cannot be produced before it was last modified..", brep.getProducedAt().getTime() >= singleResps[0].getThisUpdate().getTime()); }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpStandaloneTest.java
License:Open Source License
private void testNextUpdateThisUpdate(X509Certificate caCertificate, BigInteger serialNumber) throws Exception { // And an OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, serialNumber)); OCSPReq req = gen.build();/*from w w w.j av a 2 s.c om*/ // POST the request and receive a singleResponse URL url = new URL(httpReqPath + '/' + resourceOcsp); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/ocsp-request"); OutputStream os = con.getOutputStream(); os.write(req.getEncoded()); os.close(); assertEquals("Response code", 200, con.getResponseCode()); // Some appserver (Weblogic) responds with // "application/ocsp-response; charset=UTF-8" assertNotNull(con.getContentType()); assertTrue(con.getContentType().startsWith("application/ocsp-response")); OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream())); assertEquals("Response status not the expected.", 0, response.getStatus()); BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject(); X509CertificateHolder[] chain = brep.getCerts(); boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(chain[0])); assertTrue("Response failed to verify.", verify); SingleResp[] singleResps = brep.getResponses(); assertEquals("No of SingResps should be 1.", 1, singleResps.length); CertificateID certId = singleResps[0].getCertID(); assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), serialNumber); assertNull("Status is not null.", singleResps[0].getCertStatus()); Date thisUpdate = singleResps[0].getThisUpdate(); Date nextUpdate = singleResps[0].getNextUpdate(); Date producedAt = brep.getProducedAt(); assertNotNull("thisUpdate was not set.", thisUpdate); assertNotNull("nextUpdate was not set. (This test requires ocsp.untilNextUpdate to be configured.)", nextUpdate); assertNotNull("producedAt was not set.", producedAt); assertTrue("nextUpdate cannot be before thisUpdate.", !nextUpdate.before(thisUpdate)); assertTrue("producedAt cannot be before thisUpdate.", !producedAt.before(thisUpdate)); }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
License:Open Source License
/** * This test tests that the OCSP response contains the extension "id-pkix-ocsp-extended-revoke" in case the * status of an unknown cert is returned as revoked. * /* www. j ava2 s . co m*/ * @throws Exception */ @Test public void testExtendedRevokedExtension() throws Exception { OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, new BigInteger("1"))); OCSPReq req = gen.build(); BasicOCSPResp response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200); assertNotNull("Could not retrieve response, test could not continue.", response); assertTrue(response.getResponses()[0].getCertStatus() instanceof UnknownStatus); // RFC 6960: id-pkix-ocsp-extended-revoke OBJECT IDENTIFIER ::= {id-pkix-ocsp 9} Extension responseExtension = response .getExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp + ".9")); assertNull("Wrong extension sent with reply", responseExtension); final Map<String, String> map = new HashMap<String, String>(); map.put(OcspConfiguration.NONE_EXISTING_IS_REVOKED, "true"); this.helper.alterConfig(map); gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, new BigInteger("1"))); req = gen.build(); response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200); assertNotNull("Could not retrieve response, test could not continue.", response); assertTrue(response.getResponses()[0].getCertStatus() instanceof RevokedStatus); responseExtension = response .getExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp + ".9")); assertNotNull("No extension sent with reply", responseExtension); assertEquals(DERNull.INSTANCE, responseExtension.getParsedValue()); }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
License:Open Source License
/** * This test tests that the OCSP response contains the extension "id_pkix_ocsp_archive_cutoff" if "ocsp.expiredcert.retentionperiod" * is set in the condfiguration file//from ww w . j ava 2s.com * * @throws Exception */ @Test public void testExpiredCertArchiveCutoffExtension() throws Exception { final String username = "expiredCertUsername"; String cpname = "ValidityCertProfile"; String eepname = "ValidityEEProfile"; X509Certificate xcert = null; CertificateProfileSessionRemote certProfSession = EjbRemoteHelper.INSTANCE .getRemoteSession(CertificateProfileSessionRemote.class); EndEntityProfileSessionRemote eeProfSession = EjbRemoteHelper.INSTANCE .getRemoteSession(EndEntityProfileSessionRemote.class); try { if (certProfSession.getCertificateProfile(cpname) == null) { final CertificateProfile cp = new CertificateProfile( CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); cp.setAllowValidityOverride(true); try { certProfSession.addCertificateProfile(admin, cpname, cp); } catch (CertificateProfileExistsException e) { log.error("Certificate profile exists: ", e); } } final int cpId = certProfSession.getCertificateProfileId(cpname); if (eeProfSession.getEndEntityProfile(eepname) == null) { final EndEntityProfile eep = new EndEntityProfile(true); eep.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, "" + cpId); try { eeProfSession.addEndEntityProfile(admin, eepname, eep); } catch (EndEntityProfileExistsException e) { log.error("Could not create end entity profile.", e); } } final int eepId = eeProfSession.getEndEntityProfileId(eepname); if (!endEntityManagementSession.existsUser(username)) { endEntityManagementSession.addUser(admin, username, "foo123", "CN=expiredCertUsername", null, "ocsptest@anatom.se", false, eepId, cpId, EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.TOKEN_SOFT_PEM, 0, caid); log.debug("created user: expiredCertUsername, foo123, CN=expiredCertUsername"); } else { log.debug("User expiredCertUsername already exists."); EndEntityInformation userData = new EndEntityInformation(username, "CN=expiredCertUsername", caid, null, "ocsptest@anatom.se", EndEntityConstants.STATUS_NEW, EndEntityTypes.ENDUSER.toEndEntityType(), eepId, cpId, 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 KeyPair keys = KeyTools.genKeys("512", "RSA"); long now = (new Date()).getTime(); long notAfter = now + 1000; xcert = (X509Certificate) signSession.createCertificate(admin, username, "foo123", new PublicKeyWrapper(keys.getPublic()), -1, new Date(), new Date(notAfter)); assertNotNull("Failed to create new certificate", xcert); Thread.sleep(2000L); // wait for the certificate to expire // -------- Testing with default config value OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, xcert.getSerialNumber())); OCSPReq req = gen.build(); BasicOCSPResp response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200); assertNotNull("Could not retrieve response, test could not continue.", response); SingleResp resp = response.getResponses()[0]; Extension singleExtension = resp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff); assertNotNull("No extension sent with reply", singleExtension); ASN1GeneralizedTime extvalue = ASN1GeneralizedTime.getInstance(singleExtension.getParsedValue()); long expectedValue = (new Date()).getTime() - (31536000L * 1000); long actualValue = extvalue.getDate().getTime(); long diff = expectedValue - actualValue; assertTrue("Wrong archive cutoff value.", diff < 60000); // -------- Send a request where id_pkix_ocsp_archive_cutoff SHOULD NOT be used // set ocsp configuration Map<String, String> map = new HashMap<String, String>(); map.put(OcspConfiguration.EXPIREDCERT_RETENTIONPERIOD, "-1"); this.helper.alterConfig(map); gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, xcert.getSerialNumber())); req = gen.build(); response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200); assertNotNull("Could not retrieve response, test could not continue.", response); resp = response.getResponses()[0]; singleExtension = resp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff); assertNull("The wrong extension was sent with reply", singleExtension); // ------------ Send a request where id_pkix_ocsp_archive_cutoff SHOULD be used // set ocsp configuration map = new HashMap<String, String>(); map.put(OcspConfiguration.EXPIREDCERT_RETENTIONPERIOD, "63072000"); // 2 years this.helper.alterConfig(map); gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, xcert.getSerialNumber())); req = gen.build(); response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200); assertNotNull("Could not retrieve response, test could not continue.", response); resp = response.getResponses()[0]; singleExtension = resp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff); assertNotNull("No extension sent with reply", singleExtension); extvalue = ASN1GeneralizedTime.getInstance(singleExtension.getParsedValue()); expectedValue = (new Date()).getTime() - (63072000L * 1000); actualValue = extvalue.getDate().getTime(); diff = expectedValue - actualValue; assertTrue("Wrong archive cutoff value.", diff < 60000); } finally { endEntityManagementSession.revokeAndDeleteUser(admin, username, CRLReason.unspecified); eeProfSession.removeEndEntityProfile(admin, eepname); certProfSession.removeCertificateProfile(admin, cpname); } }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspTestBase.java
License:Open Source License
/** * Just verify that a simple GET works./* w w w . ja va 2s . c o m*/ */ protected void test13GetRequests() throws Exception { // NOPMD, this is not a test class itself loadUserCert(this.caid); // See if the OCSP Servlet can read non-encoded requests final String plainReq = httpReqPath + '/' + resourceOcsp + '/' + "MGwwajBFMEMwQTAJBgUrDgMCGgUABBRBRfilzPB+Aevx0i1AoeKTkrHgLgQUFJw5gwk9BaEgsX3pzsRF9iso29ICCCzdx5N0v9XwoiEwHzAdBgkrBgEFBQcwAQIEECrZswo/a7YW+hyi5Sn85fs="; URL url = new URL(plainReq); log.info(url.toString()); // Dump the exact string we use for access HttpURLConnection con = (HttpURLConnection) url.openConnection(); assertEquals("Response code did not match. ", 200, con.getResponseCode()); assertNotNull(con.getContentType()); assertTrue(con.getContentType().startsWith("application/ocsp-response")); OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream())); assertNotNull("Response should not be null.", response); assertTrue("Should not be concidered malformed.", OCSPRespBuilder.MALFORMED_REQUEST != response.getStatus()); final String dubbleSlashNonEncReq = httpReqPath + '/' + resourceOcsp + '/' + "MGwwajBFMEMwQTAJBgUrDgMCGgUABBRBRfilzPB%2BAevx0i1AoeKTkrHgLgQUFJw5gwk9BaEgsX3pzsRF9iso29ICCAvB//HJyKqpoiEwHzAdBgkrBgEFBQcwAQIEEOTzT2gv3JpVva22Vj8cuKo%3D"; url = new URL(dubbleSlashNonEncReq); log.info(url.toString()); // Dump the exact string we use for access con = (HttpURLConnection) url.openConnection(); assertEquals("Response code did not match. ", 200, con.getResponseCode()); assertNotNull(con.getContentType()); assertTrue(con.getContentType().startsWith("application/ocsp-response")); response = new OCSPResp(IOUtils.toByteArray(con.getInputStream())); assertNotNull("Response should not be null.", response); assertTrue("Should not be concidered malformed.", OCSPRespBuilder.MALFORMED_REQUEST != response.getStatus()); // An OCSP request, ocspTestCert is already created in earlier tests OCSPReqBuilder gen = new OCSPReqBuilder(); loadUserCert(this.caid); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, ocspTestCert.getSerialNumber())); OCSPReq req = gen.build(); BasicOCSPResp brep = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200); SingleResp[] singleResps = brep.getResponses(); assertNotNull("SingleResps should not be null.", singleResps); CertificateID certId = singleResps[0].getCertID(); assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), ocspTestCert.getSerialNumber()); Object status = singleResps[0].getCertStatus(); assertEquals("Status is not null (null is 'good')", null, status); }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspTestBase.java
License:Open Source License
/** * Send multiple requests in one GET request. RFC 5019 2.1.1 prohibits * clients from this, but the server should be RFC 2560 compatible and * support this as long as the total request URL is smaller than 256 bytes. *//*w w w . j a va2 s . co m*/ protected void test15MultipleGetRequests() throws Exception { // NOPMD, this is not a test class itself loadUserCert(this.caid); this.helper.reloadKeys(); // An OCSP request, ocspTestCert is already created in earlier tests OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, ocspTestCert.getSerialNumber())); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, new BigInteger("1"))); OCSPReq req = gen.build(); BasicOCSPResp brep = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200); SingleResp[] singleResps = brep.getResponses(); assertNotNull("SingleResps should not be null.", singleResps); assertEquals("Serno in response does not match serno in request.", singleResps[0].getCertID().getSerialNumber(), ocspTestCert.getSerialNumber()); assertTrue("Serno in response does not match serno in request.", singleResps[1].getCertID().getSerialNumber().toString().equals("1")); assertEquals("Status is not null (null is 'good')", null, singleResps[0].getCertStatus()); assertTrue("Status is not unknown", singleResps[1].getCertStatus() instanceof UnknownStatus); }
From source file:org.jivesoftware.openfire.net.OCSPChecker.java
License:Open Source License
@Override public void check(Certificate cert, Collection<String> unresolvedCritExts) throws CertPathValidatorException { Log.debug("OCSPChecker: check called"); InputStream in = null;//from w ww . j av a 2 s . com OutputStream out = null; try { // Examine OCSP properties X509Certificate responderCert = null; boolean haveResponderCert = true; //defaults to issuers cert X500Principal responderSubjectName = null; boolean haveIssuerCert = false; // If we set the subject name, we need to find the certificate if (ocspServerSubject != null) { haveResponderCert = false; responderSubjectName = new X500Principal(ocspServerSubject); } X509Certificate issuerCert = null; X509Certificate currCert = (X509Certificate) cert; // Set the issuer certificate if we were passed a chain if (certIndex != 0) { issuerCert = (X509Certificate) (certs[certIndex]); haveIssuerCert = true; if (haveResponderCert) { responderCert = certs[certIndex]; } } if (!haveIssuerCert || !haveResponderCert) { if (!haveResponderCert) { Log.debug("OCSPChecker: Looking for responder's certificate"); } if (!haveIssuerCert) { Log.debug("OCSPChecker: Looking for issuer's certificate"); } // Extract the anchor certs Iterator anchors = pkixParams.getTrustAnchors().iterator(); if (!anchors.hasNext()) { throw new CertPathValidatorException("Must specify at least one trust anchor"); } X500Principal certIssuerName = currCert.getIssuerX500Principal(); while (anchors.hasNext() && (!haveIssuerCert || !haveResponderCert)) { TrustAnchor anchor = (TrustAnchor) anchors.next(); X509Certificate anchorCert = anchor.getTrustedCert(); X500Principal anchorSubjectName = anchorCert.getSubjectX500Principal(); // Check if this anchor cert is the issuer cert if (!haveIssuerCert && certIssuerName.equals(anchorSubjectName)) { issuerCert = anchorCert; haveIssuerCert = true; //If we have not set the responderCert at this point, set it to the issuer if (haveResponderCert && responderCert == null) { responderCert = anchorCert; Log.debug("OCSPChecker: Responder's certificate = issuer certificate"); } } // Check if this anchor cert is the responder cert if (!haveResponderCert) { if (responderSubjectName != null && responderSubjectName.equals(anchorSubjectName)) { responderCert = anchorCert; haveResponderCert = true; } } } if (issuerCert == null) { //No trust anchor was found matching the issuer throw new CertPathValidatorException("No trusted certificate for " + currCert.getIssuerDN()); } // Check cert stores if responder cert has not yet been found if (!haveResponderCert) { Log.debug("OCSPChecker: Searching cert stores for responder's certificate"); if (responderSubjectName != null) { X509CertSelector filter = new X509CertSelector(); filter.setSubject(responderSubjectName.getName()); List<CertStore> certStores = pkixParams.getCertStores(); for (CertStore certStore : certStores) { Iterator i = certStore.getCertificates(filter).iterator(); if (i.hasNext()) { responderCert = (X509Certificate) i.next(); haveResponderCert = true; break; } } } } } // Could not find the responder cert if (!haveResponderCert) { throw new CertPathValidatorException("Cannot find the responder's certificate."); } // Construct an OCSP Request OCSPReqBuilder gen = new OCSPReqBuilder(); CertificateID certID = new CertificateID( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1), new X509CertificateHolder(issuerCert.getEncoded()), currCert.getSerialNumber()); gen.addRequest(certID); OCSPReq ocspRequest = gen.build(); URL url; if (ocspServerUrl != null) { try { url = new URL(ocspServerUrl); } catch (MalformedURLException e) { throw new CertPathValidatorException(e); } } else { throw new CertPathValidatorException("Must set OCSP Server URL"); } HttpURLConnection con = (HttpURLConnection) url.openConnection(); Log.debug("OCSPChecker: connecting to OCSP service at: " + url); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/ocsp-request"); con.setRequestProperty("Accept", "application/ocsp-response"); byte[] bytes = ocspRequest.getEncoded(); con.setRequestProperty("Content-length", String.valueOf(bytes.length)); out = con.getOutputStream(); out.write(bytes); out.flush(); // Check the response if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { Log.debug("OCSPChecker: Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage()); } in = con.getInputStream(); OCSPResp ocspResponse = new OCSPResp(in); BigInteger serialNumber = currCert.getSerialNumber(); BasicOCSPResp brep = (BasicOCSPResp) ocspResponse.getResponseObject(); try { if (!brep.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC") .build(responderCert.getPublicKey()))) { throw new CertPathValidatorException("OCSP response is not verified"); } } catch (Exception e) { throw new CertPathValidatorException("OCSP response could not be verified (" + e.getMessage() + ")", null, cp, certIndex); } SingleResp[] singleResp = brep.getResponses(); boolean foundResponse = false; for (SingleResp resp : singleResp) { CertificateID respCertID = resp.getCertID(); if (respCertID.equals(certID)) { Object status = resp.getCertStatus(); if (status == CertificateStatus.GOOD) { Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: good"); foundResponse = true; break; } else if (status instanceof org.bouncycastle.cert.ocsp.RevokedStatus) { Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: revoked"); throw new CertPathValidatorException("Certificate has been revoked", null, cp, certIndex); } else if (status instanceof org.bouncycastle.cert.ocsp.UnknownStatus) { Log.debug("OCSPChecker: Status of certificate (with serial number " + serialNumber.toString() + ") is: unknown"); throw new CertPathValidatorException("Certificate's revocation status is unknown", null, cp, certIndex); } else { Log.debug("Status of certificate (with serial number " + serialNumber.toString() + ") is: not recognized"); throw new CertPathValidatorException("Unknown OCSP response for certificate", null, cp, certIndex); } } } // Check that response applies to the cert that was supplied if (!foundResponse) { throw new CertPathValidatorException("No certificates in the OCSP response match the " + "certificate supplied in the OCSP request."); } } catch (CertPathValidatorException cpve) { throw cpve; } catch (Exception e) { throw new CertPathValidatorException(e); } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { throw new CertPathValidatorException(ioe); } } if (out != null) { try { out.close(); } catch (IOException ioe) { throw new CertPathValidatorException(ioe); } } } }