List of usage examples for java.security.cert X509Certificate getSerialNumber
public abstract BigInteger getSerialNumber();
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpStandaloneTest.java
/** * Tests the ocsp.revoked.untilNextUpdate configuration. * /*w w w . j a v a 2 s. c o m*/ * The test sets ocsp.untilNextUpdate and ocsp.revoked.untilNextUpdate to different values and then verified that the response's next update value matches * the setting of ocsp.revoked.untilNextUpdate and not ocsp.untilNextUpdate * * @throws Exception * error */ @Test public void testRevokedNextUpdate() throws Exception { ocspResponseGeneratorTestSession.reloadOcspSigningCache(); final X509Certificate ocspTestCert = getRevokedTestCert(); final String oldConfigurationValue1 = configurationSession.getConfigurationValue( "ocsp." + CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER + ".untilNextUpdate"); final String oldConfigurationValue2 = configurationSession.getConfigurationValue( "ocsp." + CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER + ".revoked.untilNextUpdate"); configurationSession.setConfigurationValue( "ocsp." + CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER + ".untilNextUpdate", "7"); configurationSession.setConfigurationValue( "ocsp." + CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER + ".revoked.untilNextUpdate", "5"); // Make sure that we run the test with a CA where this is no OcspKeyBinding OcspTestUtils.setInternalKeyBindingStatus(authenticationToken, internalKeyBindingId, InternalKeyBindingStatus.DISABLED); ocspResponseGeneratorTestSession.reloadOcspSigningCache(); try { // And an OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), getCaCert(ocspTestCert), ocspTestCert.getSerialNumber())); OCSPReq req = gen.build(); // Send the request and receive a singleResponse SingleResp[] singleResps = helper.sendOCSPPost(req.getEncoded(), null, 0, 200); assertEquals("No of SingResps should be 1.", 1, singleResps.length); SingleResp singleResp = singleResps[0]; CertificateID certId = singleResp.getCertID(); assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), ocspTestCert.getSerialNumber()); Object status = singleResp.getCertStatus(); assertTrue("Status (" + status + ") is not RevokedStatus", status instanceof RevokedStatus); RevokedStatus rev = (RevokedStatus) status; assertTrue("Status does not have reason", rev.hasRevocationReason()); Date thisUpdate = singleResp.getThisUpdate(); Date nextUpdate = singleResp.getNextUpdate(); assertNotNull("thisUpdate was not set.", thisUpdate); assertNotNull( "nextUpdate was not set. (This test requires ocsp.revoked.untilNextUpdate to be configured.)", nextUpdate); long diff = nextUpdate.getTime() - thisUpdate.getTime(); assertEquals("The nextUpdate value was not taken from ocsp.revoked.untilNextUpdate", 5000L, diff); } finally { configurationSession.setConfigurationValue( "ocsp." + CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER + ".untilNextUpdate", oldConfigurationValue1); configurationSession.setConfigurationValue( "ocsp." + CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER + ".revoked.untilNextUpdate", oldConfigurationValue2); OcspTestUtils.setInternalKeyBindingStatus(authenticationToken, internalKeyBindingId, InternalKeyBindingStatus.ACTIVE); } }
From source file:com.netscape.cmscore.usrgrp.UGSubsystem.java
/** * Converts certificate into string format. * should eventually go into the locator itself *///w w w . j a va 2 s. c om protected String getCertificateStringWithoutVersion(X509Certificate cert) { if (cert == null) { return null; } // note that it did not represent a certificate fully return "-1;" + cert.getSerialNumber().toString() + ";" + cert.getIssuerDN() + ";" + cert.getSubjectDN(); }
From source file:org.apache.hadoop.security.ssl.TestCRLValidator.java
@Test public void testValidator() throws Exception { Path caTruststore = Paths.get(BASE_DIR, "ca.truststore.jks"); Path crlPath = Paths.get(BASE_DIR, "crl.pem"); // Generate CA keypair KeyPair cakeyPair = KeyStoreTestUtil.generateKeyPair(keyAlgorithm); X509Certificate caCert = KeyStoreTestUtil.generateCertificate("CN=rootCA", cakeyPair, 60, signatureAlgorithm);/* ww w . j a v a 2 s .co m*/ // Generate CA truststore KeyStoreTestUtil.createTrustStore(caTruststore.toString(), password, "rootca", caCert); // Generate client keypair KeyPair clientKeyPair = KeyStoreTestUtil.generateKeyPair(keyAlgorithm); X509Certificate clientCert = KeyStoreTestUtil.generateSignedCertificate("CN=client", clientKeyPair, 30, signatureAlgorithm, cakeyPair.getPrivate(), caCert); /*X509Certificate clientCert = KeyStoreTestUtil.generateCertificate("CN=client", clientKeyPair, 30, signatureAlgorithm);*/ // Verify client certificate is signed by CA clientCert.verify(cakeyPair.getPublic()); // Generate CRL X509CRL crl = KeyStoreTestUtil.generateCRL(caCert, cakeyPair.getPrivate(), signatureAlgorithm, null, null); writeCRLToFile(crl, crlPath); // Validate should pass conf.set(FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER, FileBasedKeyStoresFactory.SSL_TRUSTSTORE_LOCATION_TPL_KEY), caTruststore.toString()); conf.set(FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER, FileBasedKeyStoresFactory.SSL_TRUSTSTORE_PASSWORD_TPL_KEY), password); conf.set(CommonConfigurationKeys.HOPS_CRL_OUTPUT_FILE_KEY, crlPath.toString()); CRLValidator validator = CRLValidatorFactory.getInstance().getValidator(CRLValidatorFactory.TYPE.TESTING, conf, conf); Certificate[] chain = new Certificate[2]; chain[0] = clientCert; chain[1] = caCert; // At this point the validation should pass validator.validate(chain); // Revoke client certificate and regenerate CRL crl = KeyStoreTestUtil.generateCRL(caCert, cakeyPair.getPrivate(), signatureAlgorithm, crl, clientCert.getSerialNumber()); TimeUnit.SECONDS.sleep(1); writeCRLToFile(crl, crlPath); TimeUnit.SECONDS.sleep(validator.getReloadInterval() * 2); // This time validation should fail rule.expect(CertificateException.class); validator.validate(chain); }
From source file:com.netscape.cmscore.usrgrp.UGSubsystem.java
public String getCertificateString(X509Certificate cert) { if (cert == null) { return null; }// www.j av a2 s.c o m // note that it did not represent a certificate fully return cert.getVersion() + ";" + cert.getSerialNumber().toString() + ";" + cert.getIssuerDN() + ";" + cert.getSubjectDN(); }
From source file:org.ejbca.ui.web.protocol.OCSPServletBase.java
/** Performs service of the actual OCSP request, which is contained in reqBytes. * //from w ww . ja v a 2 s.c o m * @param reqBytes the binary OCSP request bytes. This parameter must already have been checked for max or min size. */ public void serviceOCSP(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (m_log.isTraceEnabled()) { m_log.trace(">service()"); } final int localTransactionID; synchronized (this) { this.mTransactionID += 1; localTransactionID = this.mTransactionID; } final IPatternLogger transactionLogger; final IPatternLogger auditLogger; final Date startTime = new Date(); if (this.mDoTransactionLog) { transactionLogger = this.transactionLogger.getPatternLogger(); } else { transactionLogger = new DummyPatternLogger(); // Ignores everything } if (this.mDoAuditLog) { auditLogger = this.auditLogger.getPatternLogger(); } else { auditLogger = new DummyPatternLogger(); // Ignores everything } final String remoteAddress = request.getRemoteAddr(); auditLogger.paramPut(IAuditLogger.OCSPREQUEST, ""); // No request bytes yet auditLogger.paramPut(IPatternLogger.LOG_ID, new Integer(localTransactionID)); auditLogger.paramPut(IPatternLogger.SESSION_ID, this.m_SessionID); auditLogger.paramPut(IOCSPLogger.CLIENT_IP, remoteAddress); transactionLogger.paramPut(IPatternLogger.LOG_ID, new Integer(localTransactionID)); transactionLogger.paramPut(IPatternLogger.SESSION_ID, this.m_SessionID); transactionLogger.paramPut(IOCSPLogger.CLIENT_IP, remoteAddress); try { // Read configuration values affecting the response, these can be dynamically updated from properties files in file system // Read default values here for each request since may take a millisecond to read the value // These values can be changed depending on if there are different configurations for different certificate profiles // In that case it is updated once we have read the certificate status of the certificate searched for. long maxAge = OcspConfiguration.getMaxAge(SecConst.CERTPROFILE_NO_PROFILE); long nextUpdate = OcspConfiguration.getUntilNextUpdate(SecConst.CERTPROFILE_NO_PROFILE); OCSPResp ocspresp = null; OCSPRespGenerator res = new OCSPRespGenerator(); X509Certificate cacert = null; // CA-certificate used to sign response try { byte[] reqBytes = checkAndGetRequestBytes(request); // Start logging process time after we have received the request transactionLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); auditLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); auditLogger.paramPut(IAuditLogger.OCSPREQUEST, new String(Hex.encode(reqBytes))); OCSPReq req = null; try { req = new OCSPReq(reqBytes); } catch (Exception e) { // When not being able to parse the request, we want to send a MalformedRequest back throw new MalformedRequestException(e); } if (req.getRequestorName() == null) { m_log.debug("Requestorname is null"); } else { if (m_log.isDebugEnabled()) { m_log.debug("Requestorname is: " + req.getRequestorName().toString()); } transactionLogger.paramPut(ITransactionLogger.REQ_NAME, req.getRequestorName().toString()); } // Make sure our signature keys are updated loadPrivateKeys(this.data.m_adm, null); /** * check the signature if contained in request. * if the request does not contain a signature * and the servlet is configured in the way * the a signature is required we send back * 'sigRequired' response. */ if (m_log.isDebugEnabled()) { m_log.debug("Incoming OCSP request is signed : " + req.isSigned()); } if (req.isSigned()) { X509Certificate signercert = OCSPUtil.checkRequestSignature(request.getRemoteAddr(), req, this.data.m_caCertCache); String signercertIssuerName = CertTools.getIssuerDN(signercert); BigInteger signercertSerNo = CertTools.getSerialNumber(signercert); String signercertSubjectName = CertTools.getSubjectDN(signercert); transactionLogger.paramPut(ITransactionLogger.SIGN_ISSUER_NAME_DN, signercertIssuerName); transactionLogger.paramPut(ITransactionLogger.SIGN_SERIAL_NO, signercert.getSerialNumber().toByteArray()); transactionLogger.paramPut(ITransactionLogger.SIGN_SUBJECT_NAME, signercertSubjectName); transactionLogger.paramPut(IPatternLogger.REPLY_TIME, ITransactionLogger.REPLY_TIME); if (OcspConfiguration.getEnforceRequestSigning()) { // If it verifies OK, check if it is revoked final CertificateStatus status = this.data.certificateStoreSession.getStatus( CertTools.getIssuerDN(signercert), CertTools.getSerialNumber(signercert)); // If rci == null it means the certificate does not exist in database, we then treat it as ok, // because it may be so that only revoked certificates is in the (external) OCSP database. if (status.equals(CertificateStatus.REVOKED)) { String serno = signercertSerNo.toString(16); String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.revoked", signercertSubjectName, signercertIssuerName, serno); m_log.info(infoMsg); throw new SignRequestSignatureException(infoMsg); } if (m_reqRestrictSignatures) { loadTrustDir(); if (m_reqRestrictMethod == OcspConfiguration.RESTRICTONSIGNER) { if (!OCSPUtil.checkCertInList(signercert, mTrustedReqSigSigners)) { String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.notallowed", signercertSubjectName, signercertIssuerName, signercertSerNo.toString(16)); m_log.info(infoMsg); throw new SignRequestSignatureException(infoMsg); } } else if (m_reqRestrictMethod == OcspConfiguration.RESTRICTONISSUER) { X509Certificate signerca = this.data.m_caCertCache .findLatestBySubjectDN(HashID.getFromDN(signercertIssuerName)); if ((signerca == null) || (!OCSPUtil.checkCertInList(signerca, mTrustedReqSigIssuers))) { String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.notallowed", signercertSubjectName, signercertIssuerName, signercertSerNo.toString(16)); m_log.info(infoMsg); throw new SignRequestSignatureException(infoMsg); } } else { throw new Exception("m_reqRestrictMethod=" + m_reqRestrictMethod); // there must be an internal error. We do not want to send a response, just to be safe. } } } } else { if (OcspConfiguration.getEnforceRequestSigning()) { // Signature required throw new SignRequestException("Signature required"); } } // Get the certificate status requests that are inside this OCSP req Req[] requests = req.getRequestList(); transactionLogger.paramPut(ITransactionLogger.NUM_CERT_ID, requests.length); if (requests.length <= 0) { String infoMsg = intres.getLocalizedMessage("ocsp.errornoreqentities"); m_log.info(infoMsg); { // All this just so we can create an error response cacert = this.data.m_caCertCache .findLatestBySubjectDN(HashID.getFromDN(this.data.m_defaultResponderId)); } throw new MalformedRequestException(infoMsg); } int maxRequests = 100; if (requests.length > maxRequests) { String infoMsg = intres.getLocalizedMessage("ocsp.errortoomanyreqentities", maxRequests); m_log.info(infoMsg); { // All this just so we can create an error response cacert = this.data.m_caCertCache .findLatestBySubjectDN(HashID.getFromDN(this.data.m_defaultResponderId)); } throw new MalformedRequestException(infoMsg); } if (m_log.isDebugEnabled()) { m_log.debug("The OCSP request contains " + requests.length + " simpleRequests."); } // Add standard response extensions Hashtable responseExtensions = OCSPUtil.getStandardResponseExtensions(req); transactionLogger.paramPut(ITransactionLogger.STATUS, OCSPRespGenerator.SUCCESSFUL); auditLogger.paramPut(IAuditLogger.STATUS, OCSPRespGenerator.SUCCESSFUL); // Look over the status requests ArrayList responseList = new ArrayList(); for (int i = 0; i < requests.length; i++) { CertificateID certId = requests[i].getCertID(); // now some Logging transactionLogger.paramPut(ITransactionLogger.SERIAL_NOHEX, certId.getSerialNumber().toByteArray()); transactionLogger.paramPut(ITransactionLogger.DIGEST_ALGOR, certId.getHashAlgOID()); //todo, find text version of this or find out if it should be something else transactionLogger.paramPut(ITransactionLogger.ISSUER_NAME_HASH, certId.getIssuerNameHash()); transactionLogger.paramPut(ITransactionLogger.ISSUER_KEY, certId.getIssuerKeyHash()); auditLogger.paramPut(IAuditLogger.ISSUER_KEY, certId.getIssuerKeyHash()); auditLogger.paramPut(IAuditLogger.SERIAL_NOHEX, certId.getSerialNumber().toByteArray()); auditLogger.paramPut(IAuditLogger.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, request.getRemoteAddr()); m_log.info(infoMsg); boolean unknownCA = false; // if the certId was issued by an unknown CA // The algorithm here: // We will sign the response with the CA that issued the first // 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. cacert = this.data.m_caCertCache.findByOcspHash(certId); // Get the issuer of certId if (cacert == null) { // We could not find certificate for this request so get certificate for default responder cacert = this.data.m_caCertCache .findLatestBySubjectDN(HashID.getFromDN(this.data.m_defaultResponderId)); unknownCA = true; } if (cacert == null) { String errMsg = intres.getLocalizedMessage("ocsp.errorfindcacert", new String(Hex.encode(certId.getIssuerNameHash())), this.data.m_defaultResponderId); m_log.error(errMsg); continue; } if (unknownCA == true) { String errMsg = intres.getLocalizedMessage("ocsp.errorfindcacertusedefault", new String(Hex.encode(certId.getIssuerNameHash()))); m_log.info(errMsg); // If we can not find the CA, answer UnknowStatus responseList.add(new OCSPResponseItem(certId, new UnknownStatus(), nextUpdate)); transactionLogger.paramPut(ITransactionLogger.CERT_STATUS, OCSPUnidResponse.OCSP_UNKNOWN); transactionLogger.writeln(); continue; } else { transactionLogger.paramPut(ITransactionLogger.ISSUER_NAME_DN, cacert.getSubjectDN().getName()); } /* * Implement logic 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. */ final org.bouncycastle.ocsp.CertificateStatus certStatus; transactionLogger.paramPut(ITransactionLogger.CERT_STATUS, OCSPUnidResponse.OCSP_GOOD); // it seems to be correct // Check if the cacert (or the default responderid) is revoked final CertificateStatus cacertStatus = this.data.certificateStoreSession .getStatus(CertTools.getIssuerDN(cacert), CertTools.getSerialNumber(cacert)); if (!cacertStatus.equals(CertificateStatus.REVOKED)) { // Check if cert is revoked final CertificateStatus status = this.data.certificateStoreSession .getStatus(cacert.getSubjectDN().getName(), certId.getSerialNumber()); // If we have different maxAge and untilNextUpdate for different certificate profiles, we have to fetch these // values now that we have fetched the certificate status, that includes certificate profile. nextUpdate = OcspConfiguration.getUntilNextUpdate(status.certificateProfileId); maxAge = OcspConfiguration.getMaxAge(status.certificateProfileId); if (m_log.isDebugEnabled()) { m_log.debug("Set nextUpdate=" + nextUpdate + ", and maxAge=" + maxAge + " for certificateProfileId=" + status.certificateProfileId); } final String sStatus; if (status.equals(CertificateStatus.NOT_AVAILABLE)) { // No revocation info available for this cert, handle it if (m_log.isDebugEnabled()) { m_log.debug("Unable to find revocation information for certificate with serial '" + certId.getSerialNumber().toString(16) + "'" + " from issuer '" + cacert.getSubjectDN().getName() + "'"); } // If we do not treat non existing certificates as good // OR // we don't actually handle requests for the CA issuing the certificate asked about // then we return unknown if (!nonExistingIsGood(request.getRequestURL()) || this.data.m_caCertCache.findByOcspHash(certId) == null) { sStatus = "unknown"; certStatus = new UnknownStatus(); transactionLogger.paramPut(ITransactionLogger.CERT_STATUS, OCSPUnidResponse.OCSP_UNKNOWN); } else { sStatus = "good"; certStatus = null; // null means "good" in OCSP transactionLogger.paramPut(ITransactionLogger.CERT_STATUS, OCSPUnidResponse.OCSP_GOOD); } } else if (status.equals(CertificateStatus.REVOKED)) { // Revocation info available for this cert, handle it sStatus = "revoked"; certStatus = new RevokedStatus( new RevokedInfo(new DERGeneralizedTime(status.revocationDate), new CRLReason(status.revocationReason))); transactionLogger.paramPut(ITransactionLogger.CERT_STATUS, OCSPUnidResponse.OCSP_REVOKED); //1 = revoked } else { sStatus = "good"; certStatus = null; transactionLogger.paramPut(ITransactionLogger.CERT_STATUS, OCSPUnidResponse.OCSP_GOOD); } infoMsg = intres.getLocalizedMessage("ocsp.infoaddedstatusinfo", sStatus, certId.getSerialNumber().toString(16), cacert.getSubjectDN().getName()); m_log.info(infoMsg); responseList.add(new OCSPResponseItem(certId, certStatus, nextUpdate)); transactionLogger.writeln(); } else { certStatus = new RevokedStatus( new RevokedInfo(new DERGeneralizedTime(cacertStatus.revocationDate), new CRLReason(cacertStatus.revocationReason))); infoMsg = intres.getLocalizedMessage("ocsp.infoaddedstatusinfo", "revoked", certId.getSerialNumber().toString(16), cacert.getSubjectDN().getName()); m_log.info(infoMsg); responseList.add(new OCSPResponseItem(certId, certStatus, nextUpdate)); transactionLogger.paramPut(ITransactionLogger.CERT_STATUS, OCSPUnidResponse.OCSP_REVOKED); transactionLogger.writeln(); } // Look for extension OIDs Iterator iter = m_extensionOids.iterator(); while (iter.hasNext()) { String oidstr = (String) iter.next(); DERObjectIdentifier oid = new DERObjectIdentifier(oidstr); X509Extensions reqexts = req.getRequestExtensions(); if (reqexts != null) { X509Extension ext = reqexts.getExtension(oid); if (null != ext) { // We found an extension, call the extenstion class if (m_log.isDebugEnabled()) { m_log.debug("Found OCSP extension oid: " + oidstr); } IOCSPExtension extObj = (IOCSPExtension) m_extensionMap.get(oidstr); if (extObj != null) { // Find the certificate from the certId X509Certificate cert = null; cert = (X509Certificate) this.data.certificateStoreSession .findCertificateByIssuerAndSerno(this.data.m_adm, cacert.getSubjectDN().getName(), certId.getSerialNumber()); if (cert != null) { // Call the OCSP extension Hashtable retext = extObj.process(request, 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(), new Integer(extObj.getLastErrorCode())); m_log.error(errMsg); } } } } } } } // end of huge for loop if (cacert != null) { // Add responseExtensions X509Extensions exts = new X509Extensions(responseExtensions); // generate the signed response object BasicOCSPResp basicresp = signOCSPResponse(req, responseList, exts, cacert); ocspresp = res.generate(OCSPRespGenerator.SUCCESSFUL, basicresp); auditLogger.paramPut(IAuditLogger.STATUS, OCSPRespGenerator.SUCCESSFUL); transactionLogger.paramPut(ITransactionLogger.STATUS, OCSPRespGenerator.SUCCESSFUL); } else { // Only unknown CAs in requests and no default reponders cert String errMsg = intres.getLocalizedMessage("ocsp.errornocacreateresp"); m_log.error(errMsg); throw new ServletException(errMsg); } } catch (MalformedRequestException e) { transactionLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); auditLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); m_log.info(errMsg); if (m_log.isDebugEnabled()) { m_log.debug(errMsg, e); } ocspresp = res.generate(OCSPRespGenerator.MALFORMED_REQUEST, null); // RFC 2560: responseBytes are not set on error. transactionLogger.paramPut(ITransactionLogger.STATUS, OCSPRespGenerator.MALFORMED_REQUEST); transactionLogger.writeln(); auditLogger.paramPut(IAuditLogger.STATUS, OCSPRespGenerator.MALFORMED_REQUEST); } catch (SignRequestException e) { transactionLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); auditLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); m_log.info(errMsg); // No need to log the full exception here ocspresp = res.generate(OCSPRespGenerator.SIG_REQUIRED, null); // RFC 2560: responseBytes are not set on error. transactionLogger.paramPut(ITransactionLogger.STATUS, OCSPRespGenerator.SIG_REQUIRED); transactionLogger.writeln(); auditLogger.paramPut(IAuditLogger.STATUS, OCSPRespGenerator.SIG_REQUIRED); } catch (SignRequestSignatureException e) { transactionLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); auditLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); m_log.info(errMsg); // No need to log the full exception here ocspresp = res.generate(OCSPRespGenerator.UNAUTHORIZED, null); // RFC 2560: responseBytes are not set on error. transactionLogger.paramPut(ITransactionLogger.STATUS, OCSPRespGenerator.UNAUTHORIZED); transactionLogger.writeln(); auditLogger.paramPut(IAuditLogger.STATUS, OCSPRespGenerator.UNAUTHORIZED); } catch (InvalidKeyException e) { transactionLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); auditLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); m_log.info(errMsg, e); ocspresp = res.generate(OCSPRespGenerator.UNAUTHORIZED, null); // RFC 2560: responseBytes are not set on error. transactionLogger.paramPut(ITransactionLogger.STATUS, OCSPRespGenerator.UNAUTHORIZED); transactionLogger.writeln(); auditLogger.paramPut(IAuditLogger.STATUS, OCSPRespGenerator.UNAUTHORIZED); } catch (Throwable e) { transactionLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); auditLogger.paramPut(IPatternLogger.PROCESS_TIME, IPatternLogger.PROCESS_TIME); String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); m_log.error(errMsg, e); ocspresp = res.generate(OCSPRespGenerator.INTERNAL_ERROR, null); // RFC 2560: responseBytes are not set on error. transactionLogger.paramPut(ITransactionLogger.STATUS, OCSPRespGenerator.INTERNAL_ERROR); transactionLogger.writeln(); auditLogger.paramPut(IAuditLogger.STATUS, OCSPRespGenerator.INTERNAL_ERROR); } byte[] respBytes = ocspresp.getEncoded(); auditLogger.paramPut(IAuditLogger.OCSPRESPONSE, new String(Hex.encode(respBytes))); auditLogger.writeln(); auditLogger.flush(); transactionLogger.flush(); if (mDoSaferLogging) { // See if the Errorhandler has found any problems if (hasErrorHandlerFailedSince(startTime)) { m_log.info("ProbableErrorhandler reported error, cannot answer request"); ocspresp = res.generate(OCSPRespGenerator.INTERNAL_ERROR, null); // RFC 2560: responseBytes are not set on error. respBytes = ocspresp.getEncoded(); } // See if the Appender has reported any problems if (!canlog) { m_log.info("SaferDailyRollingFileAppender reported error, cannot answer request"); ocspresp = res.generate(OCSPRespGenerator.INTERNAL_ERROR, null); // RFC 2560: responseBytes are not set on error. respBytes = ocspresp.getEncoded(); } } response.setContentType("application/ocsp-response"); //response.setHeader("Content-transfer-encoding", "binary"); response.setContentLength(respBytes.length); addRfc5019CacheHeaders(request, response, ocspresp, maxAge); response.getOutputStream().write(respBytes); response.getOutputStream().flush(); } catch (OCSPException e) { String errMsg = intres.getLocalizedMessage("ocsp.errorprocessreq", e.getMessage()); m_log.error(errMsg, e); throw new ServletException(e); } catch (Exception e) { m_log.error("", e); transactionLogger.flush(); auditLogger.flush(); } if (m_log.isTraceEnabled()) { m_log.trace("<service()"); } }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
@Test public void test07SignedOcsp() throws Exception { assertTrue("This test can only be run on a full EJBCA installation.", ((HttpURLConnection) new URL(httpReqPath + '/').openConnection()).getResponseCode() == 200); // find a CA (TestCA?) create a user and generate his cert // send OCSP req to server and get good response // change status of cert to bad status // send OCSP req and get bad status // (send crap message and get good error) try {/*from ww w .j a v a2 s . c o m*/ KeyPair keys = createUserCert(caid); // 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(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())); gen.setRequestExtensions(new Extensions(extensions)); X509CertificateHolder chain[] = new X509CertificateHolder[2]; chain[0] = new JcaX509CertificateHolder(ocspTestCert); chain[1] = new JcaX509CertificateHolder(cacert); gen.setRequestorName(chain[0].getSubject()); OCSPReq req = gen.build(new JcaContentSignerBuilder("SHA1WithRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), chain); // First test with a signed OCSP request that can be verified Collection<Certificate> cacerts = new ArrayList<Certificate>(); cacerts.add(cacert); CaCertificateCache certcache = CaCertificateCache.INSTANCE; certcache.loadCertificates(cacerts); X509Certificate signer = checkRequestSignature("127.0.0.1", req, certcache); assertNotNull(signer); assertEquals(ocspTestCert.getSerialNumber().toString(16), signer.getSerialNumber().toString(16)); // Try with an unsigned request, we should get a SignRequestException req = gen.build(); boolean caught = false; try { signer = checkRequestSignature("127.0.0.1", req, certcache); } catch (SignRequestException e) { caught = true; } assertTrue(caught); // sign with a keystore where the CA-certificate is not known KeyStore store = KeyStore.getInstance("PKCS12", "BC"); ByteArrayInputStream fis = new ByteArrayInputStream(ks3); store.load(fis, "foo123".toCharArray()); Certificate[] certs = KeyTools.getCertChain(store, "privateKey"); chain[0] = new JcaX509CertificateHolder((X509Certificate) certs[0]); chain[1] = new JcaX509CertificateHolder((X509Certificate) certs[1]); PrivateKey pk = (PrivateKey) store.getKey("privateKey", "foo123".toCharArray()); req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1WithRSA").build(pk), 20480), chain); // Send the request and receive a singleResponse, this response should // throw an SignRequestSignatureException caught = false; try { signer = checkRequestSignature("127.0.0.1", req, certcache); } catch (SignRequestSignatureException e) { caught = true; } assertTrue(caught); // sign with a keystore where the signing certificate has expired store = KeyStore.getInstance("PKCS12", "BC"); fis = new ByteArrayInputStream(ksexpired); store.load(fis, "foo123".toCharArray()); certs = KeyTools.getCertChain(store, "ocspclient"); chain[0] = new JcaX509CertificateHolder((X509Certificate) certs[0]); chain[1] = new JcaX509CertificateHolder((X509Certificate) certs[1]); pk = (PrivateKey) store.getKey("ocspclient", "foo123".toCharArray()); req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1WithRSA").build(pk), 20480), chain); // Send the request and receive a singleResponse, this response should // throw an SignRequestSignatureException caught = false; try { signer = checkRequestSignature("127.0.0.1", req, certcache); } catch (SignRequestSignatureException e) { caught = true; } assertTrue(caught); } finally { endEntityManagementSession.deleteUser(admin, "ocsptest"); } }
From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java
private void signDOM(Node node, PrivateKey privateKey, Certificate origCert) { XMLSignatureFactory fac = initXMLSigFactory(); X509Certificate cert = (X509Certificate) origCert; // Create the KeyInfo containing the X509Data. KeyInfoFactory kif = fac.getKeyInfoFactory(); List<Object> x509Content = null;//new ArrayList<Object>(); List<X509Data> data = new ArrayList<X509Data>(); if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_SUBJECTDN)) { x509Content = new ArrayList<Object>(); x509Content.add(cert.getSubjectDN().getName()); // x509Content.add(cert); //x509Content.add(cert.getSubjectDN().getName()); X509Data xd = kif.newX509Data(x509Content); data.add(xd);//ww w . j av a 2 s. c o m } // if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_X500_PRINICPAL)) { // } if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_BASE64)) { x509Content = new ArrayList<Object>(); x509Content.add(cert); //x509Content.add(cert.getSubjectX500Principal().getName()); X509Data xd = kif.newX509Data(x509Content); data.add(xd); } if (map.containsKey(SIGNATURE_OPTION_CERT_INCLUSION_SERIAL)) { x509Content = new ArrayList<Object>(); X509IssuerSerial issuer = kif.newX509IssuerSerial(cert.getIssuerX500Principal().getName(), cert.getSerialNumber()); x509Content.add(issuer); X509Data xd = kif.newX509Data(x509Content); data.add(xd); } // //x509Content.add(cert); KeyInfo ki = kif.newKeyInfo(data); // Create a DOMSignContext and specify the RSA PrivateKey and // location of the resulting XMLSignature's parent element. DOMSignContext dsc = new DOMSignContext(privateKey, node); dsc.putNamespacePrefix(XML_DIGSIG_NS, "ns2"); // Create the XMLSignature, but don't sign it yet. try { SignedInfo si = initSignedInfo(fac); XMLSignature signature = fac.newXMLSignature(si, ki); // Marshal, generate, and sign the enveloped signature. signature.sign(dsc); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:be.fedict.trust.crl.CrlTrustLinker.java
private TrustLinkerResult processCrl(URI crlUri, X509Certificate childCertificate, X509Certificate certificate, Date validationDate, RevocationData revocationData, BigInteger baseCrlNumber) { LOG.debug("CRL URI: " + crlUri); X509CRL x509crl = this.crlRepository.findCrl(crlUri, certificate, validationDate); if (null == x509crl) { return null; }//from w w w .j ava 2 s . com // check CRL integrity boolean crlIntegrityResult = checkCrlIntegrity(x509crl, certificate, validationDate); if (false == crlIntegrityResult) { return null; } // check CRL signature TrustLinkerResult trustResult = TrustValidator.checkSignatureAlgorithm(x509crl.getSigAlgName()); if (!trustResult.isValid()) { return trustResult; } // we don't support indirect CRLs if (isIndirectCRL(x509crl)) { LOG.debug("indirect CRL detected"); return null; } LOG.debug("CRL number: " + getCrlNumber(x509crl)); // check delta CRL indicator against completeCrlNuber if (null != baseCrlNumber) { BigInteger crlNumber = getDeltaCrlIndicator(x509crl); if (!baseCrlNumber.equals(crlNumber)) { LOG.error("Delta CRL indicator (" + crlNumber + ") not equals base CRL number(" + baseCrlNumber + ")"); return null; } } // fill up revocation data if not null with this valid CRL if (null != revocationData) { try { revocationData.getCrlRevocationData().add(new CRLRevocationData(x509crl.getEncoded())); } catch (CRLException e) { LOG.error("CRLException: " + e.getMessage(), e); throw new RuntimeException("CRLException : " + e.getMessage(), e); } } boolean revoked = true; X509CRLEntry crlEntry = x509crl.getRevokedCertificate(childCertificate.getSerialNumber()); if (null == crlEntry) { LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal()); revoked = false; } else if (crlEntry.getRevocationDate().after(validationDate)) { LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal() + " at " + validationDate); revoked = false; } if (null != x509crl.getExtensionValue(X509Extensions.DeltaCRLIndicator.getId())) { // Delta CRL if (!revoked) return null; } else { // Base CRL, look for delta's List<URI> deltaCrlUris = getDeltaCrlUris(x509crl); if (null != deltaCrlUris) { for (URI deltaCrlUri : deltaCrlUris) { LOG.debug("delta CRL: " + deltaCrlUri.toString()); TrustLinkerResult result = processCrl(deltaCrlUri, childCertificate, certificate, validationDate, revocationData, getCrlNumber(x509crl)); if (null != result) return result; } } } if (!revoked) return new TrustLinkerResult(true); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_REVOCATION_STATUS, "certificate revoked by CRL=" + crlEntry.getSerialNumber()); }
From source file:eu.eidas.auth.engine.EIDASSAMLEngine.java
/** * Gets the alias from X.509 Certificate at keystore. * //from w w w .j a v a 2 s . com * @param keyInfo the key info * @param ownKeyStore * @param ownKeyStore * * @return the alias */ private String getAlias(final KeyInfo keyInfo, KeyStore ownKeyStore) { LOG.trace("Recover alias information"); String alias = null; try { final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0) .getX509Certificates().get(0); // Transform the KeyInfo to X509Certificate. CertificateFactory certFact; certFact = CertificateFactory.getInstance("X.509"); final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue())); final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis); final String tokenSerialNumber = cert.getSerialNumber().toString(HEXA); final X500Name tokenIssuerDN = new X500Name(cert.getIssuerDN().getName()); String aliasCert; X509Certificate certificate; boolean find = false; for (final Enumeration<String> e = ownKeyStore.aliases(); e.hasMoreElements() && !find;) { aliasCert = e.nextElement(); certificate = (X509Certificate) ownKeyStore.getCertificate(aliasCert); final String serialNum = certificate.getSerialNumber().toString(HEXA); X500Name issuerDN = new X500Name(certificate.getIssuerDN().getName()); if (serialNum.equalsIgnoreCase(tokenSerialNumber) && X500PrincipalUtil.principalEquals(issuerDN, tokenIssuerDN)) { alias = aliasCert; find = true; } } } catch (KeyStoreException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } catch (CertificateException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } catch (RuntimeException e) { LOG.info(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e.getMessage()); LOG.debug(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getAlias from certificate associated into the signing keystore: {}", e); } return alias; }
From source file:org.ejbca.core.ejb.ra.EndEntityManagementSessionBean.java
private void sendNotification(final AuthenticationToken admin, final EndEntityInformation data, final int newstatus) { if (data == null) { if (log.isDebugEnabled()) { log.debug("No UserData, no notification sent."); }/*from www . j a v a 2s. com*/ return; } final String useremail = data.getEmail(); if (log.isTraceEnabled()) { log.trace(">sendNotification: user=" + data.getUsername() + ", email=" + useremail); } // Make check if we should send notifications at all if (data.getType().contains(EndEntityTypes.SENDNOTIFICATION)) { final int profileId = data.getEndEntityProfileId(); final EndEntityProfile profile = endEntityProfileSession.getEndEntityProfileNoClone(profileId); final Collection<UserNotification> l = profile.getUserNotifications(); if (log.isDebugEnabled()) { log.debug("Number of user notifications: " + l.size()); } final Iterator<UserNotification> i = l.iterator(); String rcptemail = useremail; // Default value while (i.hasNext()) { final UserNotification not = i.next(); final Collection<String> events = not.getNotificationEventsCollection(); if (events.contains(String.valueOf(newstatus))) { if (log.isDebugEnabled()) { log.debug("Status is " + newstatus + ", notification sent for notificationevents: " + not.getNotificationEvents()); } try { if (StringUtils.equals(not.getNotificationRecipient(), UserNotification.RCPT_USER)) { rcptemail = useremail; } else if (StringUtils.contains(not.getNotificationRecipient(), UserNotification.RCPT_CUSTOM)) { rcptemail = "custom"; // Just if this fail it will // say that sending to user // with email "custom" failed. // Plug-in mechanism for retrieving custom // notification email recipient addresses if (not.getNotificationRecipient().length() < 6) { final String msg = intres.getLocalizedMessage("ra.errorcustomrcptshort", not.getNotificationRecipient()); log.error(msg); } else { final String cp = not.getNotificationRecipient().substring(7); if (StringUtils.isNotEmpty(cp)) { final ICustomNotificationRecipient plugin = (ICustomNotificationRecipient) Thread .currentThread().getContextClassLoader().loadClass(cp).newInstance(); rcptemail = plugin.getRecipientEmails(data); if (StringUtils.isEmpty(rcptemail)) { final String msg = intres.getLocalizedMessage("ra.errorcustomnoemail", not.getNotificationRecipient()); log.error(msg); } else { if (log.isDebugEnabled()) { log.debug("Custom notification recipient plugin returned email: " + rcptemail); } } } else { final String msg = intres.getLocalizedMessage("ra.errorcustomnoclasspath", not.getNotificationRecipient()); log.error(msg); } } } else { // Just a plain email address specified in the // recipient field rcptemail = not.getNotificationRecipient(); } if (StringUtils.isEmpty(rcptemail)) { final String msg = intres.getLocalizedMessage("ra.errornotificationnoemail", data.getUsername()); throw new Exception(msg); } // Get the administrators DN from the admin certificate, if one exists // When approvals is used, this will be the DN of the admin that approves the request String approvalAdminDN = null; EndEntityInformation approvalAdmin = null; if (admin instanceof X509CertificateAuthenticationToken) { final X509CertificateAuthenticationToken xtok = (X509CertificateAuthenticationToken) admin; final X509Certificate adminCert = xtok.getCertificate(); String username = certificateStoreSession.findUsernameByIssuerDnAndSerialNumber( CertTools.getIssuerDN(adminCert), adminCert.getSerialNumber()); approvalAdmin = endEntityAccessSession.findUser(new AlwaysAllowLocalAuthenticationToken( new UsernamePrincipal("EndEntityManagementSession")), username); } final UserNotificationParamGen paramGen = new UserNotificationParamGen(data, approvalAdminDN, approvalAdmin); /* * substitute any $ fields in the receipient and from * fields */ rcptemail = paramGen.interpolate(rcptemail); final String fromemail = paramGen.interpolate(not.getNotificationSender()); final String subject = paramGen.interpolate(not.getNotificationSubject()); final String message = paramGen.interpolate(not.getNotificationMessage()); MailSender.sendMailOrThrow(fromemail, Arrays.asList(rcptemail), MailSender.NO_CC, subject, message, MailSender.NO_ATTACHMENTS); final String logmsg = intres.getLocalizedMessage("ra.sentnotification", data.getUsername(), rcptemail); log.info(logmsg); } catch (Exception e) { final String msg = intres.getLocalizedMessage("ra.errorsendnotification", data.getUsername(), rcptemail); log.error(msg, e); } } else { // if (events.contains(String.valueOf(newstatus))) if (log.isDebugEnabled()) { log.debug("Status is " + newstatus + ", no notification sent for notificationevents: " + not.getNotificationEvents()); } } } } else { // if ( ((data.getType() & EndEntityTypes.USER_SENDNOTIFICATION) != 0) ) if (log.isDebugEnabled()) { log.debug("Type (" + data.getType().getHexValue() + ") does not contain EndEntityTypes.USER_SENDNOTIFICATION, no notification sent."); } } if (log.isTraceEnabled()) { log.trace("<sendNotification: user=" + data.getUsername() + ", email=" + useremail); } }