List of usage examples for org.bouncycastle.asn1.x509 Extension Extension
public Extension(ASN1ObjectIdentifier extnId, boolean critical, ASN1OctetString value)
From source file:org.cesecore.certificates.ocsp.integrated.IntegratedOcspResponseTest.java
License:Open Source License
@Test public void testGetOcspResponseWithOcspCertificate() throws Exception { ocspResponseGeneratorTestSession.reloadOcspSigningCache(); // An OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, ocspCertificate.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq req = gen.build();/*ww w. j av a2 s . co m*/ final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); byte[] responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); OCSPResp response = new OCSPResp(responseBytes); assertEquals("Response status not zero.", response.getStatus(), 0); BasicOCSPResp basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertTrue("OCSP response was not signed correctly.", basicOcspResponse .isSignatureValid(new JcaContentVerifierProviderBuilder().build(caCertificate.getPublicKey()))); 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", ocspCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); assertEquals("Status is not null (good)", null, singleResponses[0].getCertStatus()); }
From source file:org.cesecore.certificates.ocsp.integrated.IntegratedOcspResponseTest.java
License:Open Source License
/** * Tests creating an OCSP response using the ocspCertificate, revoking it. * Tests using both SHA1 and SHA256 CertID. */// w ww .j a v a 2 s . c om @Test public void testGetOcspResponseWithRevokedCertificate() throws Exception { ocspResponseGeneratorTestSession.reloadOcspSigningCache(); // An OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, ocspCertificate.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq req = gen.build(); // Now revoke the ocspCertificate certificateStoreSession.setRevokeStatus(internalAdmin, ocspCertificate, RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED, null); final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); byte[] responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); OCSPResp response = new OCSPResp(responseBytes); assertEquals("Response status not zero.", response.getStatus(), 0); BasicOCSPResp basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertTrue("OCSP response was not signed correctly.", basicOcspResponse .isSignatureValid(new JcaContentVerifierProviderBuilder().build(caCertificate.getPublicKey()))); 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", ocspCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); Object status = singleResponses[0].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_UNSPECIFIED); // Do the same test but using SHA256 as hash algorithm for CertID gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID( new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)), caCertificate, ocspCertificate.getSerialNumber())); extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); req = gen.build(); responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); response = new OCSPResp(responseBytes); assertEquals("Response status not zero.", response.getStatus(), 0); basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertTrue("OCSP response was not signed correctly.", basicOcspResponse .isSignatureValid(new JcaContentVerifierProviderBuilder().build(caCertificate.getPublicKey()))); 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", ocspCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); status = singleResponses[0].getCertStatus(); assertTrue("Status is not RevokedStatus", status instanceof RevokedStatus); rev = (RevokedStatus) status; assertTrue("Status does not have reason", rev.hasRevocationReason()); reason = rev.getRevocationReason(); assertEquals("Wrong revocation reason", reason, RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED); }
From source file:org.cesecore.certificates.ocsp.integrated.IntegratedOcspResponseTest.java
License:Open Source License
@Test public void testGetOcspResponseWithUnavailableCertificate() throws Exception { ocspResponseGeneratorTestSession.reloadOcspSigningCache(); // An OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, ocspCertificate.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq req = gen.build();/* w ww .j ava 2 s. co m*/ // Now remove the certificate internalCertificateStoreSession.removeCertificate(ocspCertificate.getSerialNumber()); ocspResponseGeneratorTestSession.reloadOcspSigningCache(); final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); byte[] responseBytes = ocspResponseGeneratorSession.getOcspResponse(req.getEncoded(), null, "", "", new StringBuffer("http://foo.com"), auditLogger, transactionLogger).getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); OCSPResp response = new OCSPResp(responseBytes); assertEquals("Response status not zero.", response.getStatus(), 0); BasicOCSPResp basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertTrue("OCSP response was not signed correctly.", basicOcspResponse .isSignatureValid(new JcaContentVerifierProviderBuilder().build(caCertificate.getPublicKey()))); 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", ocspCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); // Set that an unknown CA is "good", and redo the test (cache is reloaded automatically) cesecoreConfigurationProxySession.setConfigurationValue("ocsp.nonexistingisgood", "true"); responseBytes = ocspResponseGeneratorSession.getOcspResponse(req.getEncoded(), null, "", "", new StringBuffer("http://foo.com"), auditLogger, transactionLogger).getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); response = new OCSPResp(responseBytes); assertEquals("Response status not zero.", response.getStatus(), 0); basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertTrue("OCSP response was not signed correctly.", basicOcspResponse .isSignatureValid(new JcaContentVerifierProviderBuilder().build(caCertificate.getPublicKey()))); 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", ocspCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); // Assert that status is null, i.e. "good" assertNull(singleResponses[0].getCertStatus()); cesecoreConfigurationProxySession.setConfigurationValue("ocsp.nonexistingisgood", "false"); }
From source file:org.cesecore.certificates.ocsp.integrated.IntegratedOcspResponseTest.java
License:Open Source License
/** * Note that this test is time dependent. Debugging it will create strange behavior. * // w w w. j av a 2 s . c o m * @throws OCSPException * @throws AuthorizationDeniedException * @throws MalformedRequestException * @throws IOException * @throws InterruptedException * @throws IllegalCryptoTokenException * @throws CADoesntExistsException * @throws CertificateEncodingException */ @Test public void testCacheUpdates() throws OCSPException, AuthorizationDeniedException, MalformedRequestException, IOException, InterruptedException, CADoesntExistsException, IllegalCryptoTokenException, CertificateEncodingException { final Integer timeToWait = 2; // Set the validity time to a single second for testing purposes. cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.SIGNING_CERTD_VALID_TIME, timeToWait.toString()); ocspResponseGeneratorTestSession.reloadOcspSigningCache(); try { // An OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, ocspCertificate.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq req = gen.build(); byte[] responseBytes; ocspResponseGeneratorTestSession.reloadOcspSigningCache(); final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); // Initial assert that status is null, i.e. "good" assertNull("Test could not run because initial ocsp response failed.", ((BasicOCSPResp) (new OCSPResp(responseBytes)).getResponseObject()).getResponses()[0] .getCertStatus()); // Erase the cert. It should still exist in the cache. caSession.removeCA(internalAdmin, testx509ca.getCAId()); responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); // Initial assert that status is null, i.e. "good" assertNull("Test could not run because cache changed before the entire test could run.", ((BasicOCSPResp) (new OCSPResp(responseBytes)).getResponseObject()).getResponses()[0] .getCertStatus()); // Now sleep and try again, Glassfish has a default "minimum-delivery-interval-in-millis" of 7 seconds, so we have // to wait that long, make it 8 seconds. We have set the timer to 2 seconds above. Thread.sleep(8 * 1000); // Since the CA is gone, expect an unauthorized response responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); OCSPResp response = new OCSPResp(responseBytes); assertEquals("Response status not OCSPRespBuilder.UNAUTHORIZED.", response.getStatus(), OCSPRespBuilder.UNAUTHORIZED); assertNull("Response should not have contained a response object.", response.getResponseObject()); } finally { // Reset sign trust valid time. cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.SIGNING_CERTD_VALID_TIME, Integer.toString(OcspConfiguration.getSigningCertsValidTimeInMilliseconds())); } }
From source file:org.cesecore.certificates.ocsp.integrated.IntegratedOcspResponseTest.java
License:Open Source License
/** * This test should use the default OCSP responder to sign the response as unknown. * //from w w w . jav a 2s .c om * @throws OCSPException * @throws AuthorizationDeniedException * @throws IOException * @throws MalformedRequestException * @throws CADoesntExistsException * @throws IllegalCryptoTokenException * @throws NoSuchProviderException * @throws CertificateEncodingException * @throws OperatorCreationException */ @Test public void testGetOcspResponseWithCertificateFromUnknownCa() throws OCSPException, AuthorizationDeniedException, IOException, MalformedRequestException, CADoesntExistsException, IllegalCryptoTokenException, NoSuchProviderException, CertificateEncodingException, OperatorCreationException { ocspResponseGeneratorTestSession.reloadOcspSigningCache(); // An OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), ocspCertificate, ocspCertificate.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq req = gen.build(); final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); byte[] responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); OCSPResp response = new OCSPResp(responseBytes); assertEquals("Response status not SUCCESSFUL.", OCSPRespBuilder.SUCCESSFUL, response.getStatus()); BasicOCSPResp basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertTrue("OCSP response was not signed correctly.", basicOcspResponse .isSignatureValid(new JcaContentVerifierProviderBuilder().build(caCertificate.getPublicKey()))); 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", ocspCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); assertTrue(singleResponses[0].getCertStatus() instanceof UnknownStatus); }
From source file:org.cesecore.certificates.ocsp.integrated.IntegratedOcspResponseTest.java
License:Open Source License
@Test public void testGetOcspResponseWithIncorrectDefaultResponder() throws OCSPException, AuthorizationDeniedException, IOException, MalformedRequestException, CADoesntExistsException, IllegalCryptoTokenException, CertificateEncodingException { // Set a fake value GlobalOcspConfiguration configuration = (GlobalOcspConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID); configuration.setOcspDefaultResponderReference("CN=FancyPants"); globalConfigurationSession.saveConfiguration(internalAdmin, configuration); ocspResponseGeneratorTestSession.reloadOcspSigningCache(); // An OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), ocspCertificate, ocspCertificate.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq req = gen.build();/*from w w w.j ava 2 s.c o m*/ final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); byte[] responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); //We're expecting back an unsigned reply saying unauthorized, as per RFC2690 Section 2.3 assertNotNull("OCSP responder replied null", responseBytes); OCSPResp response = new OCSPResp(responseBytes); assertEquals("Response status not OCSPRespBuilder.UNAUTHORIZED.", response.getStatus(), OCSPRespBuilder.UNAUTHORIZED); }
From source file:org.cesecore.certificates.ocsp.integrated.IntegratedOcspResponseTest.java
License:Open Source License
/** Tests using the default responder for external CAs for a good certificate. */ @Test//from ww w . j a v a 2s .com public void testResponseWithDefaultResponderForExternal() throws Exception { // Make sure that a default responder is set GlobalOcspConfiguration ocspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID); final String originalDefaultResponder = ocspConfiguration.getOcspDefaultResponderReference(); ocspConfiguration.setOcspDefaultResponderReference(testx509ca.getSubjectDN()); globalConfigurationSession.saveConfiguration(internalAdmin, ocspConfiguration); try { // Now, construct an external CA. final String externalCaName = "testStandAloneOcspResponseExternalCa"; final String externalCaSubjectDn = "CN=" + externalCaName; long validity = 3650L; KeyPair externalCaKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); Certificate externalCaCertificate = CertTools.genSelfCert(externalCaSubjectDn, validity, null, externalCaKeys.getPrivate(), externalCaKeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true); X509CAInfo externalCaInfo = new X509CAInfo(externalCaSubjectDn, externalCaName, CAConstants.CA_EXTERNAL, CertificateProfileConstants.CERTPROFILE_NO_PROFILE, validity, CAInfo.SELFSIGNED, null, null); CAToken token = new CAToken(externalCaInfo.getCAId(), new NullCryptoToken().getProperties()); X509CA externalCa = new X509CA(externalCaInfo); externalCa.setCAToken(token); externalCa.setCertificateChain(Arrays.asList(externalCaCertificate)); caSession.addCA(internalAdmin, externalCa); certificateStoreSession.storeCertificate(internalAdmin, externalCaCertificate, externalCaName, "1234", CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ROOTCA, CertificateProfileConstants.CERTPROFILE_NO_PROFILE, null, new Date().getTime()); ocspResponseGeneratorSession.reloadOcspSigningCache(); try { final String externalUsername = "testStandAloneOcspResponseExternalUser"; final String externalSubjectDn = "CN=" + externalUsername; // Create a certificate signed by the external CA and stuff it in the database (we can pretend it was imported) Date firstDate = new Date(); firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000)); Date lastDate = new Date(); lastDate.setTime(lastDate.getTime() + (24 * 60 * 60 * 1000)); byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); KeyPair certificateKeyPair = KeyTools.genKeys("1024", "RSA"); final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(certificateKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder( CertTools.stringToBcX500Name(externalCaSubjectDn, false), new BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(externalSubjectDn, false), pkinfo); final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA256WithRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(externalCaKeys.getPrivate()), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); X509Certificate importedCertificate = (X509Certificate) CertTools .getCertfromByteArray(certHolder.getEncoded()); certificateStoreSession.storeCertificate(internalAdmin, importedCertificate, externalUsername, "1234", CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ENDENTITY, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, new Date().getTime()); try { //Now everything is in place. Perform a request, make sure that the default responder signed it. OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), (X509Certificate) externalCaCertificate, importedCertificate.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); OCSPReq ocspRequest = gen.build(); final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); byte[] responseBytes = ocspResponseGeneratorSession.getOcspResponse(ocspRequest.getEncoded(), null, "", "", null, auditLogger, transactionLogger).getOcspResponse(); assertNotNull("OCSP responder replied null", responseBytes); OCSPResp response = new OCSPResp(responseBytes); assertEquals("Response status not zero.", OCSPResp.SUCCESSFUL, response.getStatus()); final BasicOCSPResp basicOcspResponse = (BasicOCSPResp) response.getResponseObject(); assertNotNull("Signed request generated null-response.", basicOcspResponse); assertTrue("OCSP response was not signed correctly.", basicOcspResponse.isSignatureValid(new JcaContentVerifierProviderBuilder() .build(testx509ca.getCACertificate().getPublicKey()))); 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", importedCertificate.getSerialNumber(), singleResponses[0].getCertID().getSerialNumber()); assertEquals("Status is not null (good)", null, singleResponses[0].getCertStatus()); } finally { internalCertificateStoreSession.removeCertificate(importedCertificate); } } finally { caSession.removeCA(internalAdmin, externalCa.getCAId()); internalCertificateStoreSession.removeCertificate(externalCaCertificate); } } finally { GlobalOcspConfiguration restoredOcspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID); ocspConfiguration.setOcspDefaultResponderReference(originalDefaultResponder); globalConfigurationSession.saveConfiguration(internalAdmin, restoredOcspConfiguration); } }
From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java
License:Open Source License
@Override public OcspResponseInformation getOcspResponse(final byte[] request, final X509Certificate[] requestCertificates, String remoteAddress, String remoteHost, StringBuffer requestUrl, final AuditLogger auditLogger, final TransactionLogger transactionLogger) throws MalformedRequestException, OCSPException { //Check parameters if (auditLogger == null) { throw new InvalidParameterException( "Illegal to pass a null audit logger to OcspResponseSession.getOcspResponse"); }//from w w w . j ava 2 s .c om if (transactionLogger == null) { throw new InvalidParameterException( "Illegal to pass a null transaction logger to OcspResponseSession.getOcspResponse"); } // Validate byte array. if (request.length > MAX_REQUEST_SIZE) { final String msg = intres.getLocalizedMessage("request.toolarge", MAX_REQUEST_SIZE, request.length); throw new MalformedRequestException(msg); } byte[] respBytes = null; final Date startTime = new Date(); OCSPResp ocspResponse = null; // Start logging process time after we have received the request if (transactionLogger.isEnabled()) { transactionLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME); } if (auditLogger.isEnabled()) { auditLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME); auditLogger.paramPut(AuditLogger.OCSPREQUEST, new String(Hex.encode(request))); } OCSPReq req; long maxAge = OcspConfiguration.getMaxAge(CertificateProfileConstants.CERTPROFILE_NO_PROFILE); OCSPRespBuilder responseGenerator = new OCSPRespBuilder(); try { req = translateRequestFromByteArray(request, remoteAddress, transactionLogger); // Get the certificate status requests that are inside this OCSP req Req[] ocspRequests = req.getRequestList(); if (ocspRequests.length <= 0) { String infoMsg = intres.getLocalizedMessage("ocsp.errornoreqentities"); log.info(infoMsg); throw new MalformedRequestException(infoMsg); } final int maxRequests = 100; if (ocspRequests.length > maxRequests) { String infoMsg = intres.getLocalizedMessage("ocsp.errortoomanyreqentities", maxRequests); log.info(infoMsg); throw new MalformedRequestException(infoMsg); } if (log.isDebugEnabled()) { log.debug("The OCSP request contains " + ocspRequests.length + " simpleRequests."); } if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.NUM_CERT_ID, ocspRequests.length); transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.SUCCESSFUL); } if (auditLogger.isEnabled()) { auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.SUCCESSFUL); } OcspSigningCacheEntry ocspSigningCacheEntry = null; long nextUpdate = OcspConfiguration .getUntilNextUpdate(CertificateProfileConstants.CERTPROFILE_NO_PROFILE); // Add standard response extensions Map<ASN1ObjectIdentifier, Extension> responseExtensions = getStandardResponseExtensions(req); // Look for extension OIDs final Collection<String> extensionOids = OcspConfiguration.getExtensionOids(); // Look over the status requests List<OCSPResponseItem> responseList = new ArrayList<OCSPResponseItem>(); boolean addExtendedRevokedExtension = false; Date producedAt = null; for (Req ocspRequest : ocspRequests) { CertificateID certId = ocspRequest.getCertID(); ASN1ObjectIdentifier certIdhash = certId.getHashAlgOID(); if (!OIWObjectIdentifiers.idSHA1.equals(certIdhash) && !NISTObjectIdentifiers.id_sha256.equals(certIdhash)) { throw new InvalidAlgorithmException( "CertID with SHA1 and SHA256 are supported, not: " + certIdhash.getId()); } if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.SERIAL_NOHEX, certId.getSerialNumber().toByteArray()); transactionLogger.paramPut(TransactionLogger.DIGEST_ALGOR, certId.getHashAlgOID().toString()); transactionLogger.paramPut(TransactionLogger.ISSUER_NAME_HASH, certId.getIssuerNameHash()); transactionLogger.paramPut(TransactionLogger.ISSUER_KEY, certId.getIssuerKeyHash()); } if (auditLogger.isEnabled()) { auditLogger.paramPut(AuditLogger.ISSUER_KEY, certId.getIssuerKeyHash()); auditLogger.paramPut(AuditLogger.SERIAL_NOHEX, certId.getSerialNumber().toByteArray()); auditLogger.paramPut(AuditLogger.ISSUER_NAME_HASH, certId.getIssuerNameHash()); } byte[] hashbytes = certId.getIssuerNameHash(); String hash = null; if (hashbytes != null) { hash = new String(Hex.encode(hashbytes)); } String infoMsg = intres.getLocalizedMessage("ocsp.inforeceivedrequest", certId.getSerialNumber().toString(16), hash, remoteAddress); log.info(infoMsg); // Locate the CA which gave out the certificate ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getEntry(certId); if (ocspSigningCacheEntry == null) { //Could it be that we haven't updated the OCSP Signing Cache? ocspSigningCacheEntry = findAndAddMissingCacheEntry(certId); } if (ocspSigningCacheEntry != null) { if (transactionLogger.isEnabled()) { // This will be the issuer DN of the signing certificate, whether an OCSP responder or an internal CA String issuerNameDn = CertTools .getIssuerDN(ocspSigningCacheEntry.getFullCertificateChain().get(0)); transactionLogger.paramPut(TransactionLogger.ISSUER_NAME_DN, issuerNameDn); } } else { /* * if the certId was issued by an unknown CA * * The algorithm here: * We will sign the response with the CA that issued the last certificate(certId) in the request. If the issuing CA is not available on * this server, we sign the response with the default responderId (from params in web.xml). We have to look up the ca-certificate for * each certId in the request though, as we will check for revocation on the ca-cert as well when checking for revocation on the certId. */ // We could not find certificate for this request so get certificate for default responder ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getDefaultEntry(); if (ocspSigningCacheEntry != null) { String errMsg = intres.getLocalizedMessage("ocsp.errorfindcacertusedefault", new String(Hex.encode(certId.getIssuerNameHash()))); log.info(errMsg); // If we can not find the CA, answer UnknowStatus responseList.add(new OCSPResponseItem(certId, new UnknownStatus(), nextUpdate)); if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.CERT_STATUS, OCSPResponseItem.OCSP_UNKNOWN); transactionLogger.writeln(); } continue; } else { GlobalOcspConfiguration ocspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID); String defaultResponder = ocspConfiguration.getOcspDefaultResponderReference(); String errMsg = intres.getLocalizedMessage("ocsp.errorfindcacert", new String(Hex.encode(certId.getIssuerNameHash())), defaultResponder); log.error(errMsg); // If we are responding to multiple requests, the last found ocspSigningCacheEntry will be used in the end // so even if there are not any one now, it might be later when it is time to sign the responses. // Since we only will sign the entire response once if there is at least one valid ocspSigningCacheEntry // we might as well include the unknown requests. responseList.add(new OCSPResponseItem(certId, new UnknownStatus(), nextUpdate)); continue; } } final org.bouncycastle.cert.ocsp.CertificateStatus certStatus; // Check if the cacert (or the default responderid) is revoked X509Certificate caCertificate = ocspSigningCacheEntry.getIssuerCaCertificate(); final CertificateStatus signerIssuerCertStatus = ocspSigningCacheEntry .getIssuerCaCertificateStatus(); final String caCertificateSubjectDn = CertTools.getSubjectDN(caCertificate); CertificateStatusHolder certificateStatusHolder = null; if (signerIssuerCertStatus.equals(CertificateStatus.REVOKED)) { /* * According to chapter 2.7 in RFC2560: * * 2.7 CA Key Compromise If an OCSP responder knows that a particular CA's private key has been compromised, it MAY return the revoked * state for all certificates issued by that CA. */ // If we've ended up here it's because the signer issuer certificate was revoked. certStatus = new RevokedStatus( new RevokedInfo(new ASN1GeneralizedTime(signerIssuerCertStatus.revocationDate), CRLReason.lookup(signerIssuerCertStatus.revocationReason))); infoMsg = intres.getLocalizedMessage("ocsp.signcertissuerrevoked", CertTools.getSerialNumberAsString(caCertificate), CertTools.getSubjectDN(caCertificate)); log.info(infoMsg); responseList.add(new OCSPResponseItem(certId, certStatus, nextUpdate)); if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.CERT_STATUS, OCSPResponseItem.OCSP_REVOKED); transactionLogger.writeln(); } } else { /** * Here is the actual check for the status of the sought certificate (easy to miss). Here we grab just the status if there aren't * any OIDs defined (default case), but if there are we'll probably need the certificate as well. If that's the case, we'll grab * the certificate in the same transaction. */ final CertificateStatus status; if (extensionOids.isEmpty()) { status = certificateStoreSession.getStatus(caCertificateSubjectDn, certId.getSerialNumber()); } else { certificateStatusHolder = certificateStoreSession .getCertificateAndStatus(caCertificateSubjectDn, certId.getSerialNumber()); status = certificateStatusHolder.getCertificateStatus(); } // If we have an OcspKeyBinding configured for this request, we override the default value if (ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) { nextUpdate = ocspSigningCacheEntry.getOcspKeyBinding().getUntilNextUpdate() * 1000L; } // If we have an explicit value configured for this certificate profile, we override the the current value with this value if (status.certificateProfileId != CertificateProfileConstants.CERTPROFILE_NO_PROFILE && OcspConfiguration.isUntilNextUpdateConfigured(status.certificateProfileId)) { nextUpdate = OcspConfiguration.getUntilNextUpdate(status.certificateProfileId); } // If we have an OcspKeyBinding configured for this request, we override the default value if (ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) { maxAge = ocspSigningCacheEntry.getOcspKeyBinding().getMaxAge() * 1000L; } // If we have an explicit value configured for this certificate profile, we override the the current value with this value if (status.certificateProfileId != CertificateProfileConstants.CERTPROFILE_NO_PROFILE && OcspConfiguration.isMaxAgeConfigured(status.certificateProfileId)) { maxAge = OcspConfiguration.getMaxAge(status.certificateProfileId); } final String sStatus; boolean addArchiveCutoff = false; if (status.equals(CertificateStatus.NOT_AVAILABLE)) { // No revocation info available for this cert, handle it if (log.isDebugEnabled()) { log.debug("Unable to find revocation information for certificate with serial '" + certId.getSerialNumber().toString(16) + "'" + " from issuer '" + caCertificateSubjectDn + "'"); } /* * If we do not treat non existing certificates as good or revoked * OR * we don't actually handle requests for the CA issuing the certificate asked about * then we return unknown * */ if (OcspConfigurationCache.INSTANCE.isNonExistingGood(requestUrl, ocspSigningCacheEntry.getOcspKeyBinding()) && OcspSigningCache.INSTANCE.getEntry(certId) != null) { sStatus = "good"; certStatus = null; // null means "good" in OCSP if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.CERT_STATUS, OCSPResponseItem.OCSP_GOOD); } } else if (OcspConfigurationCache.INSTANCE.isNonExistingRevoked(requestUrl, ocspSigningCacheEntry.getOcspKeyBinding()) && OcspSigningCache.INSTANCE.getEntry(certId) != null) { sStatus = "revoked"; certStatus = new RevokedStatus(new RevokedInfo(new ASN1GeneralizedTime(new Date(0)), CRLReason.lookup(CRLReason.certificateHold))); if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.CERT_STATUS, OCSPResponseItem.OCSP_REVOKED); } addExtendedRevokedExtension = true; } else { sStatus = "unknown"; certStatus = new UnknownStatus(); if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.CERT_STATUS, OCSPResponseItem.OCSP_UNKNOWN); } } } else if (status.equals(CertificateStatus.REVOKED)) { // Revocation info available for this cert, handle it sStatus = "revoked"; certStatus = new RevokedStatus( new RevokedInfo(new ASN1GeneralizedTime(status.revocationDate), CRLReason.lookup(status.revocationReason))); if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.CERT_STATUS, OCSPResponseItem.OCSP_REVOKED); } // If we have an explicit value configured for this certificate profile, we override the the current value with this value if (status.certificateProfileId != CertificateProfileConstants.CERTPROFILE_NO_PROFILE && OcspConfiguration .isRevokedUntilNextUpdateConfigured(status.certificateProfileId)) { nextUpdate = OcspConfiguration.getRevokedUntilNextUpdate(status.certificateProfileId); } // If we have an explicit value configured for this certificate profile, we override the the current value with this value if (status.certificateProfileId != CertificateProfileConstants.CERTPROFILE_NO_PROFILE && OcspConfiguration.isRevokedMaxAgeConfigured(status.certificateProfileId)) { maxAge = OcspConfiguration.getRevokedMaxAge(status.certificateProfileId); } } else { sStatus = "good"; certStatus = null; if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.CERT_STATUS, OCSPResponseItem.OCSP_GOOD); } addArchiveCutoff = checkAddArchiveCuttoff(caCertificateSubjectDn, certId); } if (log.isDebugEnabled()) { log.debug("Set nextUpdate=" + nextUpdate + ", and maxAge=" + maxAge + " for certificateProfileId=" + status.certificateProfileId); } infoMsg = intres.getLocalizedMessage("ocsp.infoaddedstatusinfo", sStatus, certId.getSerialNumber().toString(16), caCertificateSubjectDn); log.info(infoMsg); OCSPResponseItem respItem = new OCSPResponseItem(certId, certStatus, nextUpdate); if (addArchiveCutoff) { addArchiveCutoff(respItem); producedAt = new Date(); } responseList.add(respItem); if (transactionLogger.isEnabled()) { transactionLogger.writeln(); } } for (String oidstr : extensionOids) { boolean useAlways = false; if (oidstr.startsWith("*")) { oidstr = oidstr.substring(1, oidstr.length()); useAlways = true; } ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(oidstr); Extension extension = null; if (!useAlways) { // Only check if extension exists if we are not already bound to use it if (req.hasExtensions()) { extension = req.getExtension(oid); } } //If found, or if it should be used anyway if (useAlways || extension != null) { // We found an extension, call the extension class if (log.isDebugEnabled()) { log.debug("Found OCSP extension oid: " + oidstr); } OCSPExtension extObj = OcspExtensionsCache.INSTANCE.getExtensions().get(oidstr); if (extObj != null) { // Find the certificate from the certId if (certificateStatusHolder != null && certificateStatusHolder.getCertificate() != null) { X509Certificate cert = (X509Certificate) certificateStatusHolder.getCertificate(); // Call the OCSP extension Map<ASN1ObjectIdentifier, Extension> retext = extObj.process(requestCertificates, remoteAddress, remoteHost, cert, certStatus); if (retext != null) { // Add the returned X509Extensions to the responseExtension we will add to the basic OCSP response responseExtensions.putAll(retext); } else { String errMsg = intres.getLocalizedMessage("ocsp.errorprocessextension", extObj.getClass().getName(), Integer.valueOf(extObj.getLastErrorCode())); log.error(errMsg); } } } } } } if (addExtendedRevokedExtension) { // id-pkix-ocsp-extended-revoke OBJECT IDENTIFIER ::= {id-pkix-ocsp 9} final ASN1ObjectIdentifier extendedRevokedOID = new ASN1ObjectIdentifier( OCSPObjectIdentifiers.id_pkix_ocsp + ".9"); try { responseExtensions.put(extendedRevokedOID, new Extension(extendedRevokedOID, false, DERNull.INSTANCE.getEncoded())); } catch (IOException e) { throw new IllegalStateException("Could not get encodig from DERNull.", e); } } if (ocspSigningCacheEntry != null) { // Add responseExtensions Extensions exts = new Extensions(responseExtensions.values().toArray(new Extension[0])); // generate the signed response object BasicOCSPResp basicresp = signOcspResponse(req, responseList, exts, ocspSigningCacheEntry, producedAt); ocspResponse = responseGenerator.build(OCSPRespBuilder.SUCCESSFUL, basicresp); if (auditLogger.isEnabled()) { auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.SUCCESSFUL); } if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.SUCCESSFUL); } } else { // Only unknown CAs in requests and no default responder's cert, return an unsigned response if (log.isDebugEnabled()) { log.debug(intres.getLocalizedMessage("ocsp.errornocacreateresp")); } ocspResponse = responseGenerator.build(OCSPRespBuilder.UNAUTHORIZED, null); if (auditLogger.isEnabled()) { auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.UNAUTHORIZED); } if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.UNAUTHORIZED); } } } catch (SignRequestException e) { if (transactionLogger.isEnabled()) { transactionLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME); } if (auditLogger.isEnabled()) { auditLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME); } String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); log.info(errMsg); // No need to log the full exception here // RFC 2560: responseBytes are not set on error. ocspResponse = responseGenerator.build(OCSPRespBuilder.SIG_REQUIRED, null); if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.SIG_REQUIRED); transactionLogger.writeln(); } if (auditLogger.isEnabled()) { auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.SIG_REQUIRED); } } catch (SignRequestSignatureException e) { if (transactionLogger.isEnabled()) { transactionLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME); } if (auditLogger.isEnabled()) { auditLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME); } String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); log.info(errMsg); // No need to log the full exception here // RFC 2560: responseBytes are not set on error. ocspResponse = responseGenerator.build(OCSPRespBuilder.UNAUTHORIZED, null); if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.UNAUTHORIZED); transactionLogger.writeln(); } if (auditLogger.isEnabled()) { auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.UNAUTHORIZED); } } catch (InvalidAlgorithmException e) { if (transactionLogger.isEnabled()) { transactionLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME); } if (auditLogger.isEnabled()) { auditLogger.paramPut(PatternLogger.PROCESS_TIME, PatternLogger.PROCESS_TIME); } String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); log.info(errMsg); // No need to log the full exception here // RFC 2560: responseBytes are not set on error. ocspResponse = responseGenerator.build(OCSPRespBuilder.MALFORMED_REQUEST, null); if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.STATUS, OCSPRespBuilder.MALFORMED_REQUEST); transactionLogger.writeln(); } if (auditLogger.isEnabled()) { auditLogger.paramPut(AuditLogger.STATUS, OCSPRespBuilder.MALFORMED_REQUEST); } } catch (NoSuchAlgorithmException e) { ocspResponse = processDefaultError(responseGenerator, transactionLogger, auditLogger, e); } catch (CertificateException e) { ocspResponse = processDefaultError(responseGenerator, transactionLogger, auditLogger, e); } catch (CryptoTokenOfflineException e) { ocspResponse = processDefaultError(responseGenerator, transactionLogger, auditLogger, e); } try { respBytes = ocspResponse.getEncoded(); if (auditLogger.isEnabled()) { auditLogger.paramPut(AuditLogger.OCSPRESPONSE, new String(Hex.encode(respBytes))); auditLogger.writeln(); auditLogger.flush(); } if (transactionLogger.isEnabled()) { transactionLogger.flush(); } if (OcspConfiguration.getLogSafer()) { // See if the Errorhandler has found any problems if (hasErrorHandlerFailedSince(startTime)) { log.info("ProbableErrorhandler reported error, cannot answer request"); // RFC 2560: responseBytes are not set on error. ocspResponse = responseGenerator.build(OCSPRespBuilder.INTERNAL_ERROR, null); } // See if the Appender has reported any problems if (!CanLogCache.INSTANCE.canLog()) { log.info("SaferDailyRollingFileAppender reported error, cannot answer request"); // RFC 2560: responseBytes are not set on error. ocspResponse = responseGenerator.build(OCSPRespBuilder.INTERNAL_ERROR, null); } } } catch (IOException e) { log.error("Unexpected IOException caught.", e); if (transactionLogger.isEnabled()) { transactionLogger.flush(); } if (auditLogger.isEnabled()) { auditLogger.flush(); } } return new OcspResponseInformation(ocspResponse, maxAge); }
From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java
License:Open Source License
@Test public void testGetOcspResponseWithIncorrectDefaultResponder() throws Exception { // Set a fake value GlobalOcspConfiguration ocspConfiguration = (GlobalOcspConfiguration) globalConfigurationSession .getCachedConfiguration(GlobalOcspConfiguration.OCSP_CONFIGURATION_ID); ocspConfiguration.setOcspDefaultResponderReference("CN=FancyPants"); globalConfigurationSession.saveConfiguration(authenticationToken, ocspConfiguration); cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.SIGNATUREREQUIRED, "true"); // An OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), ocspSigningCertificate, ocspSigningCertificate.getSerialNumber())); Extension[] extensions = new Extension[1]; extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); //Create a signed request in order to test all aspects KeyPair keys = KeyTools.genKeys("512", "RSA"); // Issue a certificate to a test user final String endEntityName = "testGetOcspResponseWithIncorrectDefaultResponder"; final EndEntityInformation user = new EndEntityInformation(endEntityName, "CN=" + endEntityName, x509ca.getCAId(), null, null, new EndEntityType(EndEntityTypes.ENDUSER), 1, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityConstants.TOKEN_USERGEN, 0, null); user.setStatus(EndEntityConstants.STATUS_NEW); user.setPassword("foo123"); final SimpleRequestMessage certreq = new SimpleRequestMessage(keys.getPublic(), user.getUsername(), user.getPassword());//from ww w .j av a2 s.c o m final X509ResponseMessage resp = (X509ResponseMessage) certificateCreateSession.createCertificate( authenticationToken, user, certreq, X509ResponseMessage.class, signSession.fetchCertGenParams()); final X509Certificate ocspTestCert = (X509Certificate) resp.getCertificate(); X509CertificateHolder chain[] = new JcaX509CertificateHolder[2]; chain[0] = new JcaX509CertificateHolder(ocspTestCert); chain[1] = new JcaX509CertificateHolder(caCertificate); gen.setRequestorName(chain[0].getSubject()); OCSPReq req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), 20480), chain); //Now delete the original CA, making this test completely standalone. OcspTestUtils.deleteCa(authenticationToken, x509ca); activateKeyBinding(internalKeyBindingId); ocspResponseGeneratorSession.reloadOcspSigningCache(); try { final int localTransactionId = TransactionCounter.INSTANCE.getTransactionNumber(); // Create the transaction logger for this transaction. TransactionLogger transactionLogger = new TransactionLogger(localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); // Create the audit logger for this transaction. AuditLogger auditLogger = new AuditLogger("", localTransactionId, GuidHolder.INSTANCE.getGlobalUid(), ""); byte[] responseBytes = ocspResponseGeneratorSession .getOcspResponse(req.getEncoded(), null, "", "", null, auditLogger, transactionLogger) .getOcspResponse(); //We're expecting back an unsigned reply saying unauthorized, as per RFC2690 Section 2.3 assertNotNull("OCSP responder replied null", responseBytes); OCSPResp response = new OCSPResp(responseBytes); assertEquals("Response status not OCSPRespBuilder.UNAUTHORIZED.", response.getStatus(), OCSPRespBuilder.UNAUTHORIZED); assertNull("Response should not have contained a response object.", response.getResponseObject()); } finally { try { if (ocspTestCert != null) internalCertificateStoreSession.removeCertificate(ocspTestCert); } catch (Exception e) { //NOPMD: Ignore } cesecoreConfigurationProxySession.setConfigurationValue(OcspConfiguration.SIGNATUREREQUIRED, "false"); } }
From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java
License:Open Source License
/** * Build an OCSP request, that will optionally be signed if authentication parameters are specified * /*w w w .j a va 2s . c o m*/ * @param ocspAuthenticationCertificate signing certificate * @param ocspAuthenticationPrivateKey private key to sign with * @param caCertificate issuer of the queried certificate * @param certificateSerialnumber serial number of the certificate to be queried * @return * @throws Exception */ private OCSPReq buildOcspRequest(final X509Certificate ocspAuthenticationCertificate, final PrivateKey ocspAuthenticationPrivateKey, final X509Certificate caCertificate, final BigInteger certificateSerialnumber) throws Exception { final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder(); if (ocspAuthenticationCertificate != null) { // Signed requests are required to have an OCSPRequest.TBSRequest.requestorName ocspReqBuilder.setRequestorName(new X500Name(ocspAuthenticationCertificate.getSubjectDN().getName())); } ocspReqBuilder.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, certificateSerialnumber)); ocspReqBuilder.setRequestExtensions( new Extensions(new Extension[] { new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())) })); if (ocspAuthenticationCertificate != null && ocspAuthenticationPrivateKey != null) { // Create a signed request final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(AlgorithmConstants.SIGALG_SHA1_WITH_RSA) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(ocspAuthenticationPrivateKey), 20480); return ocspReqBuilder.build(signer, new X509CertificateHolder[] { new X509CertificateHolder(ocspAuthenticationCertificate.getEncoded()) }); } else { // Create an unsigned request return ocspReqBuilder.build(); } }