List of usage examples for org.bouncycastle.cert.ocsp BasicOCSPResp getCerts
public X509CertificateHolder[] getCerts()
From source file:org.ejbca.core.protocol.ocsp.OcspJunitHelper.java
License:Open Source License
/** * * @param ocspPackage//w ww. ja va2 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.OcspJunitHelper.java
License:Open Source License
/** * * @param ocspPackage/*w ww.j a va 2s. c om*/ * @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 BasicOCSPResp or null if not found * @throws IOException * @throws OCSPException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateException on parsing errors. * @throws OperatorCreationException */ protected BasicOCSPResp sendOCSPGet(byte[] ocspPackage, String nonce, int respCode, int httpCode, boolean shouldIncludeSignCert, X509Certificate signCert) throws IOException, OCSPException, NoSuchProviderException, NoSuchAlgorithmException, OperatorCreationException, CertificateException { // GET the OCSP request String b64 = new String(Base64.encode(ocspPackage, false)); //String urls = URLEncoder.encode(b64, "UTF-8"); // JBoss/Tomcat will not accept escaped '/'-characters by default URL url = new URL(this.sBaseURL + '/' + b64 + this.urlEnding); HttpURLConnection con = (HttpURLConnection) url.openConnection(); if (con.getResponseCode() != httpCode) { log.info("URL when request gave unexpected result: " + url.toString() + " Message was: " + con.getResponseMessage()); } assertEquals("Response code did not match. ", 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(con.getContentType()); assertTrue(con.getContentType().startsWith("application/ocsp-response")); OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream())); assertNotNull("Response should not be null.", response); 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(); final X509CertificateHolder signCertHolder; if (!shouldIncludeSignCert) { assertEquals("The signing certificate should not be included in the OCSP response ", 0, brep.getCerts().length); signCertHolder = new JcaX509CertificateHolder(signCert); } else { X509CertificateHolder[] chain = brep.getCerts(); signCertHolder = chain[0]; } boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(signCertHolder)); 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())); } return brep; }
From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java
License:Open Source License
private OCSPUnidResponse sendOCSPRequest(byte[] ocspPackage, X509Certificate knownTrustAnchor, boolean useGet) throws IOException, OCSPException, OperatorCreationException, CertificateException, UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException { final HttpURLConnection con; if (useGet) { String b64 = new String(Base64.encode(ocspPackage, false)); URL url = new URL(httpReqPath + '/' + b64); con = (HttpURLConnection) url.openConnection(); } else {/*from w w w. jav a 2 s. c o m*/ // POST the OCSP request URL url = new URL(httpReqPath); con = (HttpURLConnection) getUrlConnection(url); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); // POST it con.setRequestProperty("Content-Type", "application/ocsp-request"); OutputStream os = null; try { os = con.getOutputStream(); os.write(ocspPackage); } finally { if (os != null) { os.close(); } } } final OCSPUnidResponse ret = new OCSPUnidResponse(); ret.setHttpReturnCode(con.getResponseCode()); if (ret.getHttpReturnCode() != 200) { if (ret.getHttpReturnCode() == 401) { ret.setErrorCode(OCSPUnidResponse.ERROR_UNAUTHORIZED); } else { ret.setErrorCode(OCSPUnidResponse.ERROR_UNKNOWN); } return ret; } final OCSPResp response; { final InputStream in = con.getInputStream(); if (in != null) { try { response = new OCSPResp(IOUtils.toByteArray(in)); } finally { in.close(); } } else { response = null; } } if (response == null) { ret.setErrorCode(OCSPUnidResponse.ERROR_NO_RESPONSE); return ret; } ret.setResp(response); final BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject(); if (brep == null) { ret.setErrorCode(OCSPUnidResponse.ERROR_NO_RESPONSE); return ret; } // Compare nonces to see if the server sent the same nonce as we sent final byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue() .getEncoded(); if (noncerep != null) { ASN1InputStream ain = new ASN1InputStream(noncerep); ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject()); ain.close(); boolean eq = ArrayUtils.isEquals(this.nonce, oct.getOctets()); if (!eq) { ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_NONCE); return ret; } } final RespID id = brep.getResponderId(); final DERTaggedObject to = (DERTaggedObject) id.toASN1Object().toASN1Primitive(); final RespID respId; final X509CertificateHolder[] chain = brep.getCerts(); JcaX509CertificateConverter converter = new JcaX509CertificateConverter(); X509Certificate signerCertificate = converter.getCertificate(chain[0]); final PublicKey signerPub = signerCertificate.getPublicKey(); if (to.getTagNo() == 1) { // This is Name respId = new JcaRespID(signerCertificate.getSubjectX500Principal()); } else { // This is KeyHash respId = new JcaRespID(signerPub, SHA1DigestCalculator.buildSha1Instance()); } if (!id.equals(respId)) { // Response responderId does not match signer certificate responderId! ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERID); } if (!brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(signerPub))) { ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNATURE); return ret; } /* * Okay, at this point we have three different variables and six different possible valid use cases. These * variables are: * 1. If the OCSP reply is from a CA (integrated) or an OCSP responder (standalone) * 2. If it was from a CA, then if that CA is self signed or a subCA * 3. If the server (in the integrated case) or keybinding (standalone case) was set to include the certificate chain */ //If we have a chain, verify it if (chain.length > 1) { // end at one shortof chain.length, because the root certificate is (usually) not included in the OCSP response // TODO: improve this when we can pass in the root cert from parameter to properly validate the whole chain for (int i = 0; i + 1 < chain.length; i++) { final X509Certificate cert1 = converter.getCertificate(chain[i]); final X509Certificate cert2 = converter.getCertificate(chain[Math.min(i + 1, chain.length - 1)]); try { cert1.verify(cert2.getPublicKey()); } catch (GeneralSecurityException e) { m_log.info("Verifying problem with", e); m_log.info("Certificate to be verified: " + cert1); m_log.info("Verifying certificate: " + cert2); ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT); return ret; } } } if (CertTools.isCA(signerCertificate)) { //Verify that the signer certificate was the same as the trust anchor if (!signerCertificate.getSerialNumber().equals(knownTrustAnchor.getSerialNumber())) { m_log.info("Signing certificate for integrated OCSP was not the provided trust anchor."); ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT); return ret; } } else if (CertTools.isOCSPCert(signerCertificate)) { //If an OCSP certificate was used to sign try { signerCertificate.verify(knownTrustAnchor.getPublicKey()); } catch (GeneralSecurityException e) { m_log.info("Signing certificate was not signed by known trust anchor."); ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT); return ret; } } else { m_log.info("Signing certificate was not an OCSP certificate."); ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT); return ret; } String fnr = getFnr(brep); if (fnr != null) { ret.setFnr(fnr); } return ret; }
From source file:org.ejbca.core.protocol.ocsp.ProtocolLookupServerHttpTest.java
License:Open Source License
private BasicOCSPResp sendOCSPPost(byte[] ocspPackage, boolean trust) throws IOException, OCSPException, GeneralSecurityException, OperatorCreationException { // POST the OCSP request URL url = new URL(httpReqPath + '/' + resourceOcsp); HttpURLConnection con = (HttpURLConnection) getUrlConnection(url, trust); // we are going to do a POST con.setDoOutput(true);/*w w w . jav a2 s. co 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); return brep; }
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 .ja v a 2 s . com*/ 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 a v a 2 s . c om*/ 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 ww . ja v a2s. c o m*/ // 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 does not contain the signing cert if Ejbca is configured that way. * //from w w w . j ava2 s. com * @throws Exception */ @Test public void testSignCertNotIncludedInResponse() throws Exception { loadUserCert(this.caid); // set OCSP configuration Map<String, String> map = new HashMap<String, String>(); map.put(OcspConfiguration.INCLUDE_SIGNING_CERT, "false"); helper.alterConfig(map); // This setting is part of the OCSP signing cache so a reload of the cache is required helper.reloadKeys(); // Build the OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, ocspTestCert.getSerialNumber()), null); OCSPReq req = gen.build(); // Send and verify the OCSP request BasicOCSPResp response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200, false, cacert); assertNotNull("Could not retrieve response, test could not continue.", response); assertTrue("Response does contain certificates", response.getCerts().length == 0); }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
License:Open Source License
/** * This test tests that the OCSP response does not contain the root CA cert in the included certificate chain. * /* ww w.j a v a 2 s. c om*/ * @throws Exception */ @Test public void testRootCACertNotIncludedInResponse() throws Exception { log.trace(">testRootCACertNotIncludedInResponse()"); // Create a subCA and a subsubCA String subcaDN = "CN=SubTestCA"; createSubCA(subcaDN, caid); String subSubCaDN = "CN=SubSubTestCA"; X509Certificate subSubCaCert = createSubCA(subSubCaDN, subcaDN.hashCode()); // set OCSP configuration Map<String, String> map = new HashMap<String, String>(); map.put(OcspConfiguration.INCLUDE_CERT_CHAIN, "true"); GlobalOcspConfiguration ocspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID); ocspConfiguration.setOcspDefaultResponderReference(subSubCaDN); globalConfigurationSession.saveConfiguration(admin, ocspConfiguration); this.helper.alterConfig(map); helper.reloadKeys(); // Expects an OCSP response including a certchain that contains only the 2 subCAs and not their rootCA. try { loadUserCert(subSubCaDN.hashCode()); OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), subSubCaCert, ocspTestCert.getSerialNumber()), null); 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 contains more that 2 certificate", response.getCerts().length == 2); X509CertificateHolder[] includedCerts = response.getCerts(); assertEquals(subSubCaDN, includedCerts[0].getSubject().toString()); assertEquals(subcaDN, includedCerts[1].getSubject().toString()); } finally { try { endEntityManagementSession.deleteUser(admin, "ocsptest"); } catch (Exception e) { log.error("", e); } try { int cryptoTokenId = caSession.getCAInfo(admin, subSubCaDN.hashCode()).getCAToken() .getCryptoTokenId(); CryptoTokenTestUtils.removeCryptoToken(admin, cryptoTokenId); cryptoTokenId = caSession.getCAInfo(admin, subcaDN.hashCode()).getCAToken().getCryptoTokenId(); CryptoTokenTestUtils.removeCryptoToken(admin, cryptoTokenId); } catch (Exception e) { log.error("", e); } try { caSession.removeCA(admin, subSubCaDN.hashCode()); caSession.removeCA(admin, subcaDN.hashCode()); } catch (Exception e) { log.info("Could not remove CA with SubjectDN " + subSubCaDN); } } log.trace("<testRootCACertNotIncludedInResponse()"); }
From source file:org.jruby.ext.openssl.OCSPBasicResponse.java
License:Common Public License
@JRubyMethod(name = "verify", rest = true) public IRubyObject verify(final ThreadContext context, IRubyObject[] args) { Ruby runtime = context.runtime;//from w w w . j a v a2 s . c om int flags = 0; IRubyObject certificates = args[0]; IRubyObject store = args[1]; boolean ret = false; if (Arity.checkArgumentCount(runtime, args, 2, 3) == 3) { flags = RubyFixnum.fix2int(args[2]); } JcaContentVerifierProviderBuilder jcacvpb = new JcaContentVerifierProviderBuilder(); jcacvpb.setProvider("BC"); BasicOCSPResp basicOCSPResp = getBasicOCSPResp(); java.security.cert.Certificate signer = findSignerCert(context, asn1BCBasicOCSPResp, convertRubyCerts(certificates), flags); if (signer == null) return RubyBoolean.newBoolean(runtime, false); if ((flags & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOINTERN))) == 0 && (flags & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_TRUSTOTHER))) != 0) { flags |= RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOVERIFY)); } if ((flags & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOSIGS))) == 0) { PublicKey sPKey = signer.getPublicKey(); if (sPKey == null) return RubyBoolean.newBoolean(runtime, false); try { ContentVerifierProvider cvp = jcacvpb.build(sPKey); ret = basicOCSPResp.isSignatureValid(cvp); } catch (Exception e) { throw newOCSPError(runtime, e); } } if ((flags & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOVERIFY))) == 0) { List<X509Cert> untrustedCerts = null; if ((flags & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOCHAIN))) != 0) { } else if (basicOCSPResp.getCerts() != null && (certificates != null && !((RubyArray) certificates).isEmpty())) { untrustedCerts = getCertsFromResp(); Iterator<java.security.cert.Certificate> certIt = ((RubyArray) certificates).iterator(); while (certIt.hasNext()) { try { untrustedCerts.add(X509Cert.wrap(context, certIt.next().getEncoded())); } catch (CertificateEncodingException e) { throw newOCSPError(runtime, e); } } } else { untrustedCerts = getCertsFromResp(); } RubyArray rUntrustedCerts = RubyArray.newEmptyArray(runtime); if (untrustedCerts != null) { X509Cert[] rubyCerts = new X509Cert[untrustedCerts.size()]; rUntrustedCerts = RubyArray.newArray(runtime, untrustedCerts.toArray(rubyCerts)); } X509StoreContext ctx; try { ctx = X509StoreContext.newStoreContext(context, (X509Store) store, X509Cert.wrap(runtime, signer), rUntrustedCerts); } catch (CertificateEncodingException e) { throw newOCSPError(runtime, e); } ctx.set_purpose(context, _X509(runtime).getConstant("PURPOSE_OCSP_HELPER")); ret = ctx.verify(context).isTrue(); IRubyObject chain = ctx.chain(context); if ((flags & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOCHECKS))) > 0) { ret = true; } try { if (checkIssuer(getBasicOCSPResp(), chain)) return RubyBoolean.newBoolean(runtime, true); } catch (IOException e) { throw newOCSPError(runtime, e); } if ((flags & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOCHAIN))) != 0) { return RubyBoolean.newBoolean(runtime, ret); } else { X509Cert rootCA = (X509Cert) ((RubyArray) chain).last(); PublicKey rootKey = rootCA.getAuxCert().getPublicKey(); try { // check if self-signed and valid (trusts itself) rootCA.getAuxCert().verify(rootKey); ret = true; } catch (Exception e) { ret = false; } } } return RubyBoolean.newBoolean(runtime, ret); }