List of usage examples for org.bouncycastle.cert.ocsp OCSPReq getExtension
public Extension getExtension(ASN1ObjectIdentifier oid)
From source file:Controllers.OCSPController.java
License:Apache License
/** * Method to do OCSP response to client. * * @param requestBytes//from ww w. j ava2s . c om * @param mode * * @return * * @throws NotImplementedException */ private byte[] processOcspRequest(byte[] requestBytes, OCSP_PROCESS_MODE mode) throws NotImplementedException { try { // get request info OCSPReq ocspRequest = new OCSPReq(requestBytes); X509CertificateHolder[] requestCerts = ocspRequest.getCerts(); Req[] requestList = ocspRequest.getRequestList(); // setup response BasicOCSPRespBuilder responseBuilder = new BasicOCSPRespBuilder( new RespID(x509CertificateHolder.getSubject())); LOG.info("OCSP request version: " + ocspRequest.getVersionNumber() + ", Requester name: " + ocspRequest.getRequestorName() + ", is signed: " + ocspRequest.isSigned() + ", has extensions: " + ocspRequest.hasExtensions() + ", number of additional certificates: " + requestCerts.length + ", number of certificate ids to verify: " + requestList.length); int ocspResult = OCSPRespBuilder.SUCCESSFUL; switch (mode) { case AUTO: LOG.error("Auto OCSP server is not implemented in this version."); throw new NotImplementedException(); case GOOD: LOG.warn("Mocked mode, server will always return Good ocsp response"); for (Req req : requestList) { CertificateID certId = req.getCertID(); String serialNumber = "0x" + certId.getSerialNumber().toString(16); LOG.debug(String.format("Processing request for cert serial number:[%s]", serialNumber)); CertificateStatus certificateStatus = CertificateStatus.GOOD; Calendar thisUpdate = new GregorianCalendar(); Date now = thisUpdate.getTime(); thisUpdate.add(Calendar.DAY_OF_MONTH, 7); Date nexUpdate = thisUpdate.getTime(); responseBuilder.addResponse(certId, certificateStatus, now, nexUpdate, null); } break; case REVOKED: LOG.warn("Mocked mode, server will always return REVOKED ocsp response"); for (Req req : requestList) { CertificateID certId = req.getCertID(); String serialNumber = "0x" + certId.getSerialNumber().toString(16); LOG.debug(String.format("Processing request for cert serial number:[%s]", serialNumber)); Calendar cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_MONTH, -7);//Set revoked 7 days ago. CertificateStatus certificateStatus = new RevokedStatus(cal.getTime(), 16); Calendar thisUpdate = new GregorianCalendar(); Date now = thisUpdate.getTime(); thisUpdate.add(Calendar.DAY_OF_MONTH, 7); Date nexUpdate = thisUpdate.getTime(); responseBuilder.addResponse(certId, certificateStatus, now, nexUpdate, null); } break; case UNKNOWN: LOG.warn("Mocked mode, server will always return Known ocsp response"); for (Req req : requestList) { CertificateID certId = req.getCertID(); String serialNumber = "0x" + certId.getSerialNumber().toString(16); LOG.debug(String.format("Processing request for cert serial number:[%s]", serialNumber)); CertificateStatus certificateStatus = new UnknownStatus(); Calendar thisUpdate = new GregorianCalendar(); Date now = thisUpdate.getTime(); thisUpdate.add(Calendar.DAY_OF_MONTH, 7); Date nexUpdate = thisUpdate.getTime(); responseBuilder.addResponse(certId, certificateStatus, now, nexUpdate, null); } break; } // process nonce Extension extNonce = ocspRequest.getExtension(new ASN1ObjectIdentifier("1.3.6.1.5.5.7.48.1.2")); if (extNonce != null) { LOG.debug("Nonce is present in the request"); responseBuilder.setResponseExtensions(new Extensions(extNonce)); } else { LOG.info("Nonce is not present in the request"); if (bRequireNonce) { LOG.info("Nonce is required, fail the request"); ocspResult = OCSPRespBuilder.UNAUTHORIZED; } } X509CertificateHolder[] chain = { x509CertificateHolder }; ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privateKey); BasicOCSPResp ocspResponse = responseBuilder.build(signer, chain, Calendar.getInstance().getTime()); OCSPRespBuilder ocspResponseBuilder = new OCSPRespBuilder(); byte[] encoded = ocspResponseBuilder.build(ocspResult, ocspResponse).getEncoded(); LOG.info("Sending OCSP response to client, size: " + encoded.length); return encoded; } catch (Exception e) { LOG.error("Exception during processing OCSP request: " + e.getMessage()); e.printStackTrace(); } return null; }
From source file:eu.europa.esig.dss.cookbook.sources.AlwaysValidOCSPSource.java
License:Open Source License
@Override public OCSPToken getOCSPToken(CertificateToken certificateToken, CertificateToken issuerCertificateToken) { try {// w w w .jav a 2s.c om final X509Certificate cert = certificateToken.getCertificate(); final BigInteger serialNumber = cert.getSerialNumber(); X509Certificate issuerCert = issuerCertificateToken.getCertificate(); final OCSPReq ocspReq = generateOCSPRequest(issuerCert, serialNumber); final DigestCalculator digestCalculator = DSSRevocationUtils.getSHA1DigestCalculator(); final BasicOCSPRespBuilder basicOCSPRespBuilder = new JcaBasicOCSPRespBuilder(issuerCert.getPublicKey(), digestCalculator); final Extension extension = ocspReq.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); if (extension != null) { basicOCSPRespBuilder.setResponseExtensions(new Extensions(new Extension[] { extension })); } final Req[] requests = ocspReq.getRequestList(); for (int ii = 0; ii != requests.length; ii++) { final Req req = requests[ii]; final CertificateID certID = req.getCertID(); boolean isOK = true; if (isOK) { basicOCSPRespBuilder.addResponse(certID, CertificateStatus.GOOD, ocspDate, null, null); } else { Date revocationDate = DSSUtils.getDate(ocspDate, -1); basicOCSPRespBuilder.addResponse(certID, new RevokedStatus(revocationDate, CRLReason.privilegeWithdrawn)); } } final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC") .build(privateKey); final X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(issuerCert.getEncoded()); final X509CertificateHolder[] chain = { x509CertificateHolder }; BasicOCSPResp basicResp = basicOCSPRespBuilder.build(contentSigner, chain, ocspDate); final SingleResp[] responses = basicResp.getResponses(); final OCSPToken ocspToken = new OCSPToken(); ocspToken.setBasicOCSPResp(basicResp); ocspToken.setBestSingleResp(responses[0]); return ocspToken; } catch (OCSPException e) { throw new DSSException(e); } catch (IOException e) { throw new DSSException(e); } catch (CertificateEncodingException e) { throw new DSSException(e); } catch (OperatorCreationException e) { throw new DSSException(e); } }
From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java
License:Apache License
public BasicOCSPRespBuilder initOCSPRespBuilder(OCSPReq request) { SubjectPublicKeyInfo keyinfo = SubjectPublicKeyInfo .getInstance(getMCCertificate(ROOT_CERT_ALIAS).getPublicKey().getEncoded()); BasicOCSPRespBuilder respBuilder;//from w w w. j a v a2 s.c o m try { respBuilder = new BasicOCSPRespBuilder(keyinfo, new JcaDigestCalculatorProviderBuilder() .setProvider(BC_PROVIDER_NAME).build().get(CertificateID.HASH_SHA1)); // Create builder } catch (Exception e) { return null; } Extension ext = request.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); if (ext != null) { respBuilder.setResponseExtensions(new Extensions(new Extension[] { ext })); // Put the nonce back in the response } return respBuilder; }
From source file:net.maritimecloud.pki.Revocation.java
License:Apache License
/** * Generate a BasicOCSPRespBuilder./*from w ww . j a v a 2 s. co m*/ * * @param request The incoming request. * @param publicKey Public key of the issuer. * @return a BasicOCSPRespBuilder */ public static BasicOCSPRespBuilder initOCSPRespBuilder(OCSPReq request, PublicKey publicKey) { SubjectPublicKeyInfo keyinfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); BasicOCSPRespBuilder respBuilder; try { respBuilder = new BasicOCSPRespBuilder(keyinfo, new JcaDigestCalculatorProviderBuilder() .setProvider(BC_PROVIDER_NAME).build().get(CertificateID.HASH_SHA1)); // Create builder } catch (Exception e) { return null; } Extension ext = request.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); if (ext != null) { respBuilder.setResponseExtensions(new Extensions(new Extension[] { ext })); // Put the nonce back in the response } return respBuilder; }
From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java
License:Open Source License
/** * Select the preferred OCSP response sigAlg according to RFC6960 Section 4.4.7 in the following order: * // w ww. j av a 2 s . com * 1. Select an algorithm specified as a preferred signature algorithm in the client request if it is * an acceptable algorithm by EJBCA. * 2. Select the signature algorithm used to sign a certificate revocation list (CRL) issued by the * certificate issuer providing status information for the certificate specified by CertID. * (NOT APPLIED) * 3. Select the signature algorithm used to sign the OCSPRequest if it is an acceptable algorithm in EJBCA. * 4. Select a signature algorithm that has been advertised as being the default signature algorithm for * the signing service using an out-of-band mechanism. * 5. Select a mandatory or recommended signature algorithm specified for the version of OCSP in use, aka. * specified in the properties file. * * The acceptable algorithm by EJBCA are the algorithms specified in ocsp.properties file in 'ocsp.signaturealgorithm' * * @param req * @param ocspSigningCacheEntry * @param signerCert * @return */ private String getSigAlg(OCSPReq req, final OcspSigningCacheEntry ocspSigningCacheEntry, final X509Certificate signerCert) { String sigAlg = null; PublicKey pk = signerCert.getPublicKey(); // Start with the preferred signature algorithm in the OCSP request final Extension preferredSigAlgExtension = req .getExtension(new ASN1ObjectIdentifier(OCSPObjectIdentifiers.id_pkix_ocsp + ".8")); if (preferredSigAlgExtension != null) { final ASN1Sequence preferredSignatureAlgorithms = ASN1Sequence .getInstance(preferredSigAlgExtension.getParsedValue()); for (int i = 0; i < preferredSignatureAlgorithms.size(); i++) { final ASN1Encodable asn1Encodable = preferredSignatureAlgorithms.getObjectAt(i); final ASN1ObjectIdentifier algorithmOid; if (asn1Encodable instanceof ASN1ObjectIdentifier) { // Handle client requests that were adapted to EJBCA 6.1.0's implementation log.info( "OCSP request's PreferredSignatureAlgorithms did not contain an PreferredSignatureAlgorithm, but instead an algorithm OID." + " This will not be supported in a future versions of EJBCA."); algorithmOid = (ASN1ObjectIdentifier) asn1Encodable; } else { // Handle client requests that provide a proper AlgorithmIdentifier as specified in RFC 6960 + RFC 5280 final ASN1Sequence preferredSignatureAlgorithm = ASN1Sequence.getInstance(asn1Encodable); final AlgorithmIdentifier algorithmIdentifier = AlgorithmIdentifier .getInstance(preferredSignatureAlgorithm.getObjectAt(0)); algorithmOid = algorithmIdentifier.getAlgorithm(); } if (algorithmOid != null) { sigAlg = AlgorithmTools.getAlgorithmNameFromOID(algorithmOid); if (sigAlg != null && OcspConfiguration.isAcceptedSignatureAlgorithm(sigAlg) && AlgorithmTools.isCompatibleSigAlg(pk, sigAlg)) { if (log.isDebugEnabled()) { log.debug( "Using OCSP response signature algorithm extracted from OCSP request extension. " + algorithmOid); } return sigAlg; } } } } // the signature algorithm used to sign the OCSPRequest if (req.getSignatureAlgOID() != null) { sigAlg = AlgorithmTools.getAlgorithmNameFromOID(req.getSignatureAlgOID()); if (OcspConfiguration.isAcceptedSignatureAlgorithm(sigAlg) && AlgorithmTools.isCompatibleSigAlg(pk, sigAlg)) { if (log.isDebugEnabled()) { log.debug( "OCSP response signature algorithm: the signature algorithm used to sign the OCSPRequest. " + sigAlg); } return sigAlg; } } // The signature algorithm that has been advertised as being the default signature algorithm for the signing service using an // out-of-band mechanism. if (ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) { // If we have an OcspKeyBinding we use this configuration to override the default sigAlg = ocspSigningCacheEntry.getOcspKeyBinding().getSignatureAlgorithm(); if (log.isDebugEnabled()) { log.debug( "OCSP response signature algorithm: the signature algorithm that has been advertised as being the default signature algorithm " + "for the signing service using an out-of-band mechanism. " + sigAlg); } return sigAlg; } // The signature algorithm specified for the version of OCSP in use. String sigAlgs = OcspConfiguration.getSignatureAlgorithm(); sigAlg = getSigningAlgFromAlgSelection(sigAlgs, pk); if (log.isDebugEnabled()) { log.debug("Using configured signature algorithm to sign OCSP response. " + sigAlg); } return sigAlg; }
From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java
License:Open Source License
private void assertAcceptableResponseExtension(OCSPReq req) throws OcspFailureException { if (null == req) { throw new IllegalArgumentException(); }/*from w ww . j a v a 2 s . c o m*/ if (req.hasExtensions()) { final Extension acceptableResponsesExtension = req .getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_response); if (acceptableResponsesExtension != null) { // RFC 6960 4.4.3 AcceptableResponses ::= SEQUENCE OF OBJECT IDENTIFIER final ASN1Sequence sequence = ASN1Sequence .getInstance(acceptableResponsesExtension.getExtnValue().getOctets()); @SuppressWarnings("unchecked") final Enumeration<ASN1ObjectIdentifier> oids = sequence.getObjects(); boolean supportsResponseType = false; while (oids.hasMoreElements()) { final ASN1ObjectIdentifier oid = oids.nextElement(); if (oid.equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic)) { // This is the response type we support, so we are happy! Break the loop. supportsResponseType = true; if (log.isDebugEnabled()) { log.debug("Response type supported: " + oid.getId()); } break; } } if (!supportsResponseType) { final String msg = "Required response type not supported, this responder only supports id-pkix-ocsp-basic."; log.info("OCSP Request type not supported: " + msg); throw new OcspFailureException(msg); } } } }
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"); }/*ww w. j ava 2 s . c o m*/ 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.OcspResponseGeneratorSessionBean.java
License:Open Source License
/** * returns a Map of responseExtensions to be added to the BacisOCSPResponseGenerator with <code> * X509Extensions exts = new X509Extensions(table); * basicRes.setResponseExtensions(responseExtensions); * </code>/*from www . j av a2 s. c o m*/ * * @param req OCSPReq * @return a HashMap, can be empty but not null */ private Map<ASN1ObjectIdentifier, Extension> getStandardResponseExtensions(OCSPReq req) { HashMap<ASN1ObjectIdentifier, Extension> result = new HashMap<ASN1ObjectIdentifier, Extension>(); if (req.hasExtensions()) { // Table of extensions to include in the response Extension ext = req.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); if (null != ext) { result.put(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, ext); } } return result; }
From source file:org.keycloak.testsuite.forms.x509.OcspHandler.java
License:Open Source License
@Override public void handleRequest(final HttpServerExchange exchange) throws Exception { if (exchange.isInIoThread()) { exchange.dispatch(this); return;/*w w w . j a v a 2s . c o m*/ } final byte[] buffy = new byte[16384]; try (InputStream requestStream = exchange.getInputStream()) { requestStream.read(buffy); } final OCSPReq request = new OCSPReq(buffy); final Req[] requested = request.getRequestList(); final Extension nonce = request.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); final DigestCalculator sha1Calculator = new JcaDigestCalculatorProviderBuilder().build() .get(AlgorithmIdentifier.getInstance(RespID.HASH_SHA1)); final BasicOCSPRespBuilder responseBuilder = new BasicOCSPRespBuilder(subjectPublicKeyInfo, sha1Calculator); if (nonce != null) { responseBuilder.setResponseExtensions(new Extensions(nonce)); } for (final Req req : requested) { final CertificateID certId = req.getCertID(); final BigInteger certificateSerialNumber = certId.getSerialNumber(); responseBuilder.addResponse(certId, REVOKED_CERTIFICATES_STATUS.get(certificateSerialNumber)); } final ContentSigner contentSigner = new BcRSAContentSignerBuilder( new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption), new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)).build(privateKey); final OCSPResp response = new OCSPRespBuilder().build(OCSPResp.SUCCESSFUL, responseBuilder.build(contentSigner, chain, new Date())); final byte[] responseBytes = response.getEncoded(); final HeaderMap responseHeaders = exchange.getResponseHeaders(); responseHeaders.put(Headers.CONTENT_TYPE, "application/ocsp-response"); final Sender responseSender = exchange.getResponseSender(); responseSender.send(ByteBuffer.wrap(responseBytes)); exchange.endExchange(); }
From source file:org.xipki.ocsp.server.impl.OcspServer.java
License:Open Source License
public OcspRespWithCacheInfo answer(final Responder responder, final OCSPReq request, final AuditEvent auditEvent, final boolean viaGet) { ResponderOption responderOption = responder.getResponderOption(); RequestOption requestOption = responder.getRequestOption(); ResponseOption responseOption = responder.getResponseOption(); ResponderSigner signer = responder.getSigner(); AuditOption auditOption = responder.getAuditOption(); CertprofileOption certprofileOption = responder.getCertprofileOption(); int version = request.getVersionNumber(); if (requestOption.isVersionAllowed(version) == false) { String message = "invalid request version " + version; LOG.warn(message);/*from w w w. j a v a 2s.c om*/ if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.INFO, AuditStatus.FAILED, message); } return createUnsuccessfullOCSPResp(OcspResponseStatus.malformedRequest); } try { OcspRespWithCacheInfo resp = checkSignature(request, requestOption, auditEvent); if (resp != null) { return resp; } boolean couldCacheInfo = viaGet; List<Extension> responseExtensions = new ArrayList<>(2); Req[] requestList = request.getRequestList(); int n = requestList.length; Set<ASN1ObjectIdentifier> criticalExtensionOIDs = new HashSet<>(); Set<?> tmp = request.getCriticalExtensionOIDs(); if (tmp != null) { for (Object oid : tmp) { criticalExtensionOIDs.add((ASN1ObjectIdentifier) oid); } } RespID respID = new RespID(signer.getResponderId()); BasicOCSPRespBuilder basicOcspBuilder = new BasicOCSPRespBuilder(respID); ASN1ObjectIdentifier extensionType = OCSPObjectIdentifiers.id_pkix_ocsp_nonce; criticalExtensionOIDs.remove(extensionType); Extension nonceExtn = request.getExtension(extensionType); if (nonceExtn != null) { byte[] nonce = nonceExtn.getExtnValue().getOctets(); int len = nonce.length; int min = requestOption.getNonceMinLen(); int max = requestOption.getNonceMaxLen(); if (len < min || len > max) { LOG.warn("length of nonce {} not within [{},{}]", new Object[] { len, min, max }); if (auditEvent != null) { StringBuilder sb = new StringBuilder(); sb.append("length of nonce ").append(len); sb.append(" not within [").append(min).append(", ").append(max); fillAuditEvent(auditEvent, AuditLevel.INFO, AuditStatus.FAILED, sb.toString()); } return createUnsuccessfullOCSPResp(OcspResponseStatus.malformedRequest); } couldCacheInfo = false; responseExtensions.add(nonceExtn); } else if (requestOption.isNonceRequired()) { String message = "nonce required, but is not present in the request"; LOG.warn(message); if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.INFO, AuditStatus.FAILED, message); } return createUnsuccessfullOCSPResp(OcspResponseStatus.malformedRequest); } boolean includeExtendedRevokeExtension = false; long cacheThisUpdate = 0; long cacheNextUpdate = Long.MAX_VALUE; for (int i = 0; i < n; i++) { AuditChildEvent childAuditEvent = null; if (auditEvent != null) { childAuditEvent = new AuditChildEvent(); auditEvent.addChildAuditEvent(childAuditEvent); } Req req = requestList[i]; CertificateID certID = req.getCertID(); String certIdHashAlgo = certID.getHashAlgOID().getId(); HashAlgoType reqHashAlgo = HashAlgoType.getHashAlgoType(certIdHashAlgo); if (reqHashAlgo == null) { LOG.warn("unknown CertID.hashAlgorithm {}", certIdHashAlgo); if (childAuditEvent != null) { fillAuditEvent(childAuditEvent, AuditLevel.INFO, AuditStatus.FAILED, "unknown CertID.hashAlgorithm " + certIdHashAlgo); } return createUnsuccessfullOCSPResp(OcspResponseStatus.malformedRequest); } else if (requestOption.allows(reqHashAlgo) == false) { LOG.warn("CertID.hashAlgorithm {} not allowed", certIdHashAlgo); if (childAuditEvent != null) { fillAuditEvent(childAuditEvent, AuditLevel.INFO, AuditStatus.FAILED, "CertID.hashAlgorithm " + certIdHashAlgo + " not allowed"); } return createUnsuccessfullOCSPResp(OcspResponseStatus.malformedRequest); } CertStatusInfo certStatusInfo = null; CertStatusStore answeredStore = null; boolean exceptionOccurs = false; for (CertStatusStore store : responder.getStores()) { try { certStatusInfo = store.getCertStatus(reqHashAlgo, certID.getIssuerNameHash(), certID.getIssuerKeyHash(), certID.getSerialNumber(), responseOption.isIncludeCerthash(), responseOption.getCertHashAlgo(), certprofileOption); if (certStatusInfo.getCertStatus() != CertStatus.ISSUER_UNKNOWN) { answeredStore = store; break; } } catch (CertStatusStoreException e) { exceptionOccurs = true; final String message = "getCertStatus() of CertStatusStore " + store.getName(); if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage()); } LOG.debug(message, e); } } if (certStatusInfo == null) { if (childAuditEvent != null) { fillAuditEvent(childAuditEvent, AuditLevel.ERROR, AuditStatus.FAILED, "no CertStatusStore can answer the request"); } if (exceptionOccurs) { return createUnsuccessfullOCSPResp(OcspResponseStatus.tryLater); } else { certStatusInfo = CertStatusInfo.getIssuerUnknownCertStatusInfo(new Date(), null); } } else if (answeredStore != null) { if (responderOption.isInheritCaRevocation()) { CertRevocationInfo caRevInfo = answeredStore.getCARevocationInfo(reqHashAlgo, certID.getIssuerNameHash(), certID.getIssuerKeyHash()); if (caRevInfo != null) { CertStatus certStatus = certStatusInfo.getCertStatus(); boolean replaced = false; if (certStatus == CertStatus.GOOD || certStatus == CertStatus.UNKNOWN) { replaced = true; } else if (certStatus == CertStatus.REVOKED) { if (certStatusInfo.getRevocationInfo().getRevocationTime() .after(caRevInfo.getRevocationTime())) { replaced = true; } } if (replaced) { CertRevocationInfo newRevInfo; if (caRevInfo.getReason() == CRLReason.CA_COMPROMISE) { newRevInfo = caRevInfo; } else { newRevInfo = new CertRevocationInfo(CRLReason.CA_COMPROMISE, caRevInfo.getRevocationTime(), caRevInfo.getInvalidityTime()); } certStatusInfo = CertStatusInfo.getRevokedCertStatusInfo(newRevInfo, certStatusInfo.getCertHashAlgo(), certStatusInfo.getCertHash(), certStatusInfo.getThisUpdate(), certStatusInfo.getNextUpdate(), certStatusInfo.getCertprofile()); } } } } if (childAuditEvent != null) { String certprofile = certStatusInfo.getCertprofile(); String auditCertType; if (certprofile != null) { auditCertType = auditOption.getCertprofileMapping().get(certprofile); if (auditCertType == null) { auditCertType = certprofile; } } else { auditCertType = "UNKNOWN"; } childAuditEvent.addEventData(new AuditEventData("certType", auditCertType)); } // certStatusInfo could not be null in any case, since at least one store is configured Date thisUpdate = certStatusInfo.getThisUpdate(); if (thisUpdate == null) { thisUpdate = new Date(); } Date nextUpdate = certStatusInfo.getNextUpdate(); List<Extension> extensions = new LinkedList<>(); boolean unknownAsRevoked = false; CertificateStatus bcCertStatus = null; switch (certStatusInfo.getCertStatus()) { case GOOD: bcCertStatus = null; break; case ISSUER_UNKNOWN: couldCacheInfo = false; bcCertStatus = new UnknownStatus(); break; case UNKNOWN: case IGNORE: couldCacheInfo = false; if (responderOption.getMode() == OCSPMode.RFC2560) { bcCertStatus = new UnknownStatus(); } else// (ocspMode == OCSPMode.RFC6960) { unknownAsRevoked = true; includeExtendedRevokeExtension = true; bcCertStatus = new RevokedStatus(new Date(0L), CRLReason.CERTIFICATE_HOLD.getCode()); } break; case REVOKED: CertRevocationInfo revInfo = certStatusInfo.getRevocationInfo(); ASN1GeneralizedTime revTime = new ASN1GeneralizedTime(revInfo.getRevocationTime()); org.bouncycastle.asn1.x509.CRLReason _reason = null; if (responseOption.isIncludeRevReason()) { _reason = org.bouncycastle.asn1.x509.CRLReason.lookup(revInfo.getReason().getCode()); } RevokedInfo _revInfo = new RevokedInfo(revTime, _reason); bcCertStatus = new RevokedStatus(_revInfo); Date invalidityDate = revInfo.getInvalidityTime(); if (responseOption.isIncludeInvalidityDate() && invalidityDate != null && invalidityDate.equals(revTime) == false) { Extension extension = new Extension(Extension.invalidityDate, false, new ASN1GeneralizedTime(invalidityDate).getEncoded()); extensions.add(extension); } break; } byte[] certHash = certStatusInfo.getCertHash(); if (certHash != null) { ASN1ObjectIdentifier hashAlgoOid = new ASN1ObjectIdentifier( certStatusInfo.getCertHashAlgo().getOid()); AlgorithmIdentifier aId = new AlgorithmIdentifier(hashAlgoOid, DERNull.INSTANCE); CertHash bcCertHash = new CertHash(aId, certHash); byte[] encodedCertHash; try { encodedCertHash = bcCertHash.getEncoded(); } catch (IOException e) { final String message = "answer() bcCertHash.getEncoded"; if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage()); } LOG.debug(message, e); if (childAuditEvent != null) { fillAuditEvent(childAuditEvent, AuditLevel.ERROR, AuditStatus.FAILED, "CertHash.getEncoded() with IOException"); } return createUnsuccessfullOCSPResp(OcspResponseStatus.internalError); } Extension extension = new Extension(ISISMTTObjectIdentifiers.id_isismtt_at_certHash, false, encodedCertHash); extensions.add(extension); } if (certStatusInfo.getArchiveCutOff() != null) { Extension extension = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff, false, new ASN1GeneralizedTime(certStatusInfo.getArchiveCutOff()).getEncoded()); extensions.add(extension); } String certStatusText; if (bcCertStatus instanceof UnknownStatus) { certStatusText = "unknown"; } else if (bcCertStatus instanceof RevokedStatus) { certStatusText = unknownAsRevoked ? "unknown_as_revoked" : "revoked"; } else if (bcCertStatus == null) { certStatusText = "good"; } else { certStatusText = "should-not-happen"; } if (childAuditEvent != null) { childAuditEvent.setLevel(AuditLevel.INFO); childAuditEvent.setStatus(AuditStatus.SUCCESSFUL); childAuditEvent.addEventData(new AuditEventData("certStatus", certStatusText)); } if (LOG.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); sb.append("certHashAlgo: ").append(certID.getHashAlgOID().getId()).append(", "); String hexCertHash = null; if (certHash != null) { hexCertHash = Hex.toHexString(certHash).toUpperCase(); } sb.append("issuerKeyHash: ").append(Hex.toHexString(certID.getIssuerKeyHash()).toUpperCase()) .append(", "); sb.append("issuerNameHash: ").append(Hex.toHexString(certID.getIssuerNameHash()).toUpperCase()) .append(", "); sb.append("serialNumber: ").append(certID.getSerialNumber()).append(", "); sb.append("certStatus: ").append(certStatusText).append(", "); sb.append("thisUpdate: ").append(thisUpdate).append(", "); sb.append("nextUpdate: ").append(nextUpdate).append(", "); sb.append("certHash: ").append(hexCertHash); LOG.debug(sb.toString()); } basicOcspBuilder.addResponse(certID, bcCertStatus, thisUpdate, nextUpdate, CollectionUtil.isEmpty(extensions) ? null : new Extensions(extensions.toArray(new Extension[0]))); cacheThisUpdate = Math.max(cacheThisUpdate, thisUpdate.getTime()); if (nextUpdate != null) { cacheNextUpdate = Math.min(cacheNextUpdate, nextUpdate.getTime()); } } if (includeExtendedRevokeExtension) { responseExtensions.add(new Extension(ObjectIdentifiers.id_pkix_ocsp_extendedRevoke, true, DERNull.INSTANCE.getEncoded())); } if (CollectionUtil.isNotEmpty(responseExtensions)) { basicOcspBuilder .setResponseExtensions(new Extensions(responseExtensions.toArray(new Extension[0]))); } ConcurrentContentSigner concurrentSigner = null; if (responderOption.getMode() != OCSPMode.RFC2560) { extensionType = ObjectIdentifiers.id_pkix_ocsp_prefSigAlgs; criticalExtensionOIDs.remove(extensionType); Extension ext = request.getExtension(extensionType); if (ext != null) { ASN1Sequence preferredSigAlgs = ASN1Sequence.getInstance(ext.getParsedValue()); concurrentSigner = signer.getSignerForPreferredSigAlgs(preferredSigAlgs); } } if (CollectionUtil.isNotEmpty(criticalExtensionOIDs)) { return createUnsuccessfullOCSPResp(OcspResponseStatus.malformedRequest); } if (concurrentSigner == null) { concurrentSigner = signer.getFirstSigner(); } ContentSigner singleSigner; try { singleSigner = concurrentSigner.borrowContentSigner(); } catch (NoIdleSignerException e) { return createUnsuccessfullOCSPResp(OcspResponseStatus.tryLater); } X509CertificateHolder[] certsInResp; EmbedCertsMode certsMode = responseOption.getEmbedCertsMode(); if (certsMode == null || certsMode == EmbedCertsMode.SIGNER) { certsInResp = new X509CertificateHolder[] { signer.getBcCertificate() }; } else if (certsMode == EmbedCertsMode.SIGNER_AND_CA) { certsInResp = signer.getBcCertificateChain(); } else { // NONE certsInResp = null; } BasicOCSPResp basicOcspResp; try { basicOcspResp = basicOcspBuilder.build(singleSigner, certsInResp, new Date()); } catch (OCSPException e) { final String message = "answer() basicOcspBuilder.build"; if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage()); } LOG.debug(message, e); if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.ERROR, AuditStatus.FAILED, "BasicOCSPRespBuilder.build() with OCSPException"); } return createUnsuccessfullOCSPResp(OcspResponseStatus.internalError); } finally { concurrentSigner.returnContentSigner(singleSigner); } OCSPRespBuilder ocspRespBuilder = new OCSPRespBuilder(); try { OCSPResp ocspResp = ocspRespBuilder.build(OcspResponseStatus.successfull.getStatus(), basicOcspResp); if (couldCacheInfo) { ResponseCacheInfo cacheInfo = new ResponseCacheInfo(cacheThisUpdate); if (cacheNextUpdate != Long.MAX_VALUE) { cacheInfo.setNextUpdate(cacheNextUpdate); } return new OcspRespWithCacheInfo(ocspResp, cacheInfo); } else { return new OcspRespWithCacheInfo(ocspResp, null); } } catch (OCSPException e) { final String message = "answer() ocspRespBuilder.build"; if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), e.getClass().getName(), e.getMessage()); } LOG.debug(message, e); if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.ERROR, AuditStatus.FAILED, "OCSPRespBuilder.build() with OCSPException"); } return createUnsuccessfullOCSPResp(OcspResponseStatus.internalError); } } catch (Throwable t) { final String message = "Throwable"; if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), t.getClass().getName(), t.getMessage()); } LOG.debug(message, t); if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.ERROR, AuditStatus.FAILED, "internal error"); } return createUnsuccessfullOCSPResp(OcspResponseStatus.internalError); } }