List of usage examples for org.bouncycastle.cert.ocsp OCSPReq isSigned
public boolean isSigned()
From source file:Controllers.OCSPController.java
License:Apache License
/** * Method to do OCSP response to client. * * @param requestBytes/*from w ww . j av a 2 s. co m*/ * @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:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java
License:Open Source License
/** * This method takes byte array and translates it onto a OCSPReq class. * //from w w w . j a va2 s . c o m * @param request the byte array in question. * @param remoteAddress The remote address of the HttpRequest associated with this array. * @param transactionLogger A transaction logger. * @return * @throws MalformedRequestException * @throws SignRequestException thrown if an unsigned request was processed when system configuration requires that all requests be signed. * @throws CertificateException * @throws NoSuchAlgorithmException * @throws SignRequestSignatureException */ private OCSPReq translateRequestFromByteArray(byte[] request, String remoteAddress, TransactionLogger transactionLogger) throws MalformedRequestException, SignRequestException, SignRequestSignatureException, CertificateException, NoSuchAlgorithmException { final OCSPReq ocspRequest; try { ocspRequest = new OCSPReq(request); } catch (IOException e) { throw new MalformedRequestException("Could not form OCSP request", e); } if (ocspRequest.getRequestorName() == null) { if (log.isDebugEnabled()) { log.debug("Requestor name is null"); } } else { if (log.isDebugEnabled()) { log.debug("Requestor name is: " + ocspRequest.getRequestorName().toString()); } if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.REQ_NAME, ocspRequest.getRequestorName().toString()); } } /** * 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 (log.isDebugEnabled()) { log.debug("Incoming OCSP request is signed : " + ocspRequest.isSigned()); } if (ocspRequest.isSigned()) { final X509Certificate signercert = checkRequestSignature(remoteAddress, ocspRequest); final String signercertIssuerName = CertTools.getIssuerDN(signercert); final BigInteger signercertSerNo = CertTools.getSerialNumber(signercert); final String signercertSubjectName = CertTools.getSubjectDN(signercert); if (transactionLogger.isEnabled()) { transactionLogger.paramPut(TransactionLogger.SIGN_ISSUER_NAME_DN, signercertIssuerName); transactionLogger.paramPut(TransactionLogger.SIGN_SERIAL_NO, signercert.getSerialNumber().toByteArray()); transactionLogger.paramPut(TransactionLogger.SIGN_SUBJECT_NAME, signercertSubjectName); transactionLogger.paramPut(PatternLogger.REPLY_TIME, TransactionLogger.REPLY_TIME); } // Check if we have configured request verification using the old property file way.. boolean enforceRequestSigning = OcspConfiguration.getEnforceRequestSigning(); // Next, check if there is an OcspKeyBinding where signing is required and configured for this request // In the case where multiple requests are bundled together they all must be trusting the signer for (final Req req : ocspRequest.getRequestList()) { OcspSigningCacheEntry ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getEntry(req.getCertID()); if (ocspSigningCacheEntry == null) { if (log.isTraceEnabled()) { log.trace("Using default responder to check signature."); } ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getDefaultEntry(); } if (ocspSigningCacheEntry != null && ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) { if (log.isTraceEnabled()) { log.trace("ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate: " + ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()); } final OcspKeyBinding ocspKeyBinding = ocspSigningCacheEntry.getOcspKeyBinding(); if (log.isTraceEnabled()) { log.trace("OcspKeyBinding " + ocspKeyBinding.getId() + ", RequireTrustedSignature: " + ocspKeyBinding.getRequireTrustedSignature()); } if (ocspKeyBinding.getRequireTrustedSignature()) { enforceRequestSigning = true; boolean isTrusted = false; final List<InternalKeyBindingTrustEntry> trustedCertificateReferences = ocspKeyBinding .getTrustedCertificateReferences(); if (trustedCertificateReferences.isEmpty()) { // We trust ANY cert from a known CA isTrusted = true; } else { for (final InternalKeyBindingTrustEntry trustEntry : trustedCertificateReferences) { final int trustedCaId = trustEntry.getCaId(); final BigInteger trustedSerialNumber = trustEntry.fetchCertificateSerialNumber(); if (log.isTraceEnabled()) { log.trace("Processing trustedCaId=" + trustedCaId + " trustedSerialNumber=" + trustedSerialNumber + " signercertIssuerName.hashCode()=" + signercertIssuerName.hashCode() + " signercertSerNo=" + signercertSerNo); } if (trustedCaId == signercertIssuerName.hashCode()) { if (trustedSerialNumber == null) { // We trust any certificate from this CA isTrusted = true; if (log.isTraceEnabled()) { log.trace( "Trusting request signature since ANY certificate from issuer " + trustedCaId + " is trusted."); } break; } else if (signercertSerNo.equals(trustedSerialNumber)) { // We trust this particular certificate from this CA isTrusted = true; if (log.isTraceEnabled()) { log.trace( "Trusting request signature since certificate with serialnumber " + trustedSerialNumber + " from issuer " + trustedCaId + " is trusted."); } break; } } } } if (!isTrusted) { final String infoMsg = intres.getLocalizedMessage("ocsp.infosigner.notallowed", signercertSubjectName, signercertIssuerName, signercertSerNo.toString(16)); log.info(infoMsg); throw new SignRequestSignatureException(infoMsg); } } } } if (enforceRequestSigning) { // If it verifies OK, check if it is revoked final CertificateStatus status = certificateStoreSession.getStatus(signercertIssuerName, signercertSerNo); /* * 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); log.info(infoMsg); throw new SignRequestSignatureException(infoMsg); } } } else { if (OcspConfiguration.getEnforceRequestSigning()) { // Signature required throw new SignRequestException("Signature required"); } // Next, check if there is an OcspKeyBinding where signing is required and configured for this request // In the case where multiple requests are bundled together they all must be trusting the signer for (final Req req : ocspRequest.getRequestList()) { OcspSigningCacheEntry ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getEntry(req.getCertID()); if (ocspSigningCacheEntry == null) { ocspSigningCacheEntry = OcspSigningCache.INSTANCE.getDefaultEntry(); } if (ocspSigningCacheEntry != null && ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) { final OcspKeyBinding ocspKeyBinding = ocspSigningCacheEntry.getOcspKeyBinding(); if (ocspKeyBinding.getRequireTrustedSignature()) { throw new SignRequestException("Signature required"); } } } } return ocspRequest; }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
License:Open Source License
/** Checks the signature on an OCSP request and checks that it is signed by an allowed CA. * Does not check for revocation of the signer certificate * /*from www . ja v a 2 s. c om*/ * @param clientRemoteAddr The ip address or hostname of the remote client that sent the request, can be null. * @param req The signed OCSPReq * @param cacerts a CertificateCache of Certificates, the authorized CA-certificates. The signer certificate must be issued by one of these. * @return X509Certificate which is the certificate that signed the OCSP request * @throws SignRequestSignatureException if signature verification fail, or if the signing certificate is not authorized * @throws SignRequestException if there is no signature on the OCSPReq * @throws OCSPException if the request can not be parsed to retrieve certificates * @throws NoSuchProviderException if the BC provider is not installed * @throws CertificateException if the certificate can not be parsed * @throws NoSuchAlgorithmException if the certificate contains an unsupported algorithm * @throws InvalidKeyException if the certificate, or CA key is invalid * @throws OperatorCreationException */ public static X509Certificate checkRequestSignature(String clientRemoteAddr, OCSPReq req, CaCertificateCache cacerts) throws SignRequestException, OCSPException, NoSuchProviderException, CertificateException, NoSuchAlgorithmException, InvalidKeyException, SignRequestSignatureException, OperatorCreationException { X509Certificate signercert = null; if (!req.isSigned()) { String infoMsg = intres.getLocalizedMessage("ocsp.errorunsignedreq", clientRemoteAddr); log.info(infoMsg); throw new SignRequestException(infoMsg); } // Get all certificates embedded in the request (probably a certificate chain) X509CertificateHolder[] certs = req.getCerts(); // Set, as a try, the signer to be the first certificate, so we have a name to log... String signer = null; JcaX509CertificateConverter converter = new JcaX509CertificateConverter(); if (certs.length > 0) { signer = CertTools.getSubjectDN(converter.getCertificate(certs[0])); } // We must find a cert to verify the signature with... boolean verifyOK = false; for (int i = 0; i < certs.length; i++) { if (req.isSignatureValid(new JcaContentVerifierProviderBuilder().build(certs[i])) == true) { signercert = converter.getCertificate(certs[i]); signer = CertTools.getSubjectDN(signercert); Date now = new Date(); String signerissuer = CertTools.getIssuerDN(signercert); String infoMsg = intres.getLocalizedMessage("ocsp.infosigner", signer); log.info(infoMsg); verifyOK = true; // Also check that the signer certificate can be verified by one of the CA-certificates // that we answer for X509Certificate signerca = cacerts.findLatestBySubjectDN(HashID.getFromIssuerDN(certs[i])); String subject = signer; String issuer = signerissuer; if (signerca != null) { try { signercert.verify(signerca.getPublicKey()); if (log.isDebugEnabled()) { log.debug("Checking validity. Now: " + now + ", signerNotAfter: " + signercert.getNotAfter()); } CertTools.checkValidity(signercert, now); // Move the error message string to the CA cert subject = CertTools.getSubjectDN(signerca); issuer = CertTools.getIssuerDN(signerca); CertTools.checkValidity(signerca, now); } catch (SignatureException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } catch (InvalidKeyException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } catch (CertificateNotYetValidException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certnotyetvalid", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } catch (CertificateExpiredException e) { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.certexpired", subject, issuer, e.getMessage()); log.info(infoMsg); verifyOK = false; } } else { infoMsg = intres.getLocalizedMessage("ocsp.infosigner.nocacert", signer, signerissuer); log.info(infoMsg); verifyOK = false; } break; } } if (!verifyOK) { String errMsg = intres.getLocalizedMessage("ocsp.errorinvalidsignature", signer); log.info(errMsg); throw new SignRequestSignatureException(errMsg); } return signercert; }
From source file:org.jruby.ext.openssl.OCSPRequest.java
License:Common Public License
@JRubyMethod(name = "verify", rest = true) public IRubyObject verify(IRubyObject[] args) { Ruby runtime = getRuntime();/*from w w w .j ava2 s . co m*/ ThreadContext context = runtime.getCurrentContext(); int flags = 0; boolean ret = false; if (Arity.checkArgumentCount(runtime, args, 2, 3) == 3) { flags = RubyFixnum.fix2int((RubyFixnum) args[2]); } IRubyObject certificates = args[0]; IRubyObject store = args[1]; OCSPReq bcOCSPReq = getBCOCSPReq(); if (bcOCSPReq == null) { throw newOCSPError(runtime, new NullPointerException("Missing BC asn1bcReq. Missing certIDs or signature?")); } if (!bcOCSPReq.isSigned()) { return RubyBoolean.newBoolean(runtime, ret); } GeneralName genName = bcOCSPReq.getRequestorName(); if (genName.getTagNo() != 4) { return RubyBoolean.newBoolean(runtime, ret); } X500Name genX500Name = X500Name.getInstance(genName.getName()); X509StoreContext storeContext = null; JcaContentVerifierProviderBuilder jcacvpb = new JcaContentVerifierProviderBuilder(); jcacvpb.setProvider("BC"); try { java.security.cert.Certificate signer = findCertByName(genX500Name, certificates, flags); if (signer == null) return RubyBoolean.newBoolean(runtime, ret); if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOINTERN))) > 0 && ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_TRUSTOTHER))) > 0)) flags |= RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOVERIFY)); if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOSIGS))) == 0) { PublicKey signerPubKey = signer.getPublicKey(); ContentVerifierProvider cvp = jcacvpb.build(signerPubKey); ret = bcOCSPReq.isSignatureValid(cvp); if (!ret) { return RubyBoolean.newBoolean(runtime, ret); } } if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOVERIFY))) == 0) { if ((flags & RubyFixnum.fix2int(_OCSP(runtime).getConstant(OCSP_NOCHAIN))) > 0) { storeContext = X509StoreContext.newStoreContext(context, (X509Store) store, X509Cert.wrap(runtime, signer), context.nil); } else { RubyArray certs = RubyArray.newEmptyArray(runtime); ASN1Sequence bcCerts = asn1bcReq.getOptionalSignature().getCerts(); if (bcCerts != null) { Iterator<ASN1Encodable> it = bcCerts.iterator(); while (it.hasNext()) { Certificate cert = Certificate.getInstance(it.next()); certs.add(X509Cert.wrap(runtime, new X509AuxCertificate(cert))); } } storeContext = X509StoreContext.newStoreContext(context, (X509Store) store, X509Cert.wrap(runtime, signer), certs); } storeContext.set_purpose(context, _X509(runtime).getConstant("PURPOSE_OCSP_HELPER")); storeContext.set_trust(context, _X509(runtime).getConstant("TRUST_OCSP_REQUEST")); ret = storeContext.verify(context).isTrue(); if (!ret) return RubyBoolean.newBoolean(runtime, false); } } catch (Exception e) { debugStackTrace(e); throw newOCSPError(runtime, e); } return RubyBoolean.newBoolean(getRuntime(), ret); }
From source file:org.xipki.ocsp.server.impl.OcspServer.java
License:Open Source License
private OcspRespWithCacheInfo checkSignature(final OCSPReq request, final RequestOption requestOption, final AuditEvent auditEvent) throws OCSPException, CertificateParsingException, InvalidAlgorithmParameterException, OcspResponderException { if (request.isSigned() == false) { if (requestOption.isSignatureRequired() == false) { return null; }//from w w w .j a v a 2 s . com String message = "signature in request required"; LOG.warn(message); if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.INFO, AuditStatus.FAILED, message); } return createUnsuccessfullOCSPResp(OcspResponseStatus.sigRequired); } if (requestOption.isValidateSignature() == false) { return null; } X509CertificateHolder[] certs = request.getCerts(); if (certs == null || certs.length < 1) { String message = "no certificate found in request to verify the signature"; LOG.warn(message); if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.INFO, AuditStatus.FAILED, message); } return createUnsuccessfullOCSPResp(OcspResponseStatus.unauthorized); } ContentVerifierProvider cvp; try { cvp = securityFactory.getContentVerifierProvider(certs[0]); } catch (InvalidKeyException e) { LOG.warn("securityFactory.getContentVerifierProvider, InvalidKeyException: {}", e.getMessage()); if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.ERROR, AuditStatus.FAILED, e.getMessage()); } return createUnsuccessfullOCSPResp(OcspResponseStatus.unauthorized); } boolean sigValid = request.isSignatureValid(cvp); if (sigValid == false) { String message = "request signature is invalid"; LOG.warn(message); if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.INFO, AuditStatus.FAILED, message); } return createUnsuccessfullOCSPResp(OcspResponseStatus.unauthorized); } // validate the certPath Date referenceTime = new Date(); if (canBuildCertpath(certs, requestOption, referenceTime)) { return null; } String message = "could not build certpath for the request's signer certifcate"; LOG.warn(message); if (auditEvent != null) { fillAuditEvent(auditEvent, AuditLevel.INFO, AuditStatus.FAILED, message); } return createUnsuccessfullOCSPResp(OcspResponseStatus.unauthorized); }
From source file:org.xipki.pki.ocsp.server.impl.OcspServer.java
License:Open Source License
private OcspRespWithCacheInfo checkSignature(final OCSPReq request, final RequestOption requestOption, final AuditEvent event) throws OCSPException, CertificateParsingException, InvalidAlgorithmParameterException, OcspResponderException { if (!request.isSigned()) { if (!requestOption.isSignatureRequired()) { return null; }/*w w w .java2s .c om*/ String message = "signature in request required"; LOG.warn(message); fillAuditEvent(event, AuditLevel.INFO, AuditStatus.FAILED, message); return createUnsuccessfulOcspResp(OcspResponseStatus.sigRequired); } if (!requestOption.isValidateSignature()) { return null; } X509CertificateHolder[] certs = request.getCerts(); if (certs == null || certs.length < 1) { String message = "no certificate found in request to verify the signature"; LOG.warn(message); fillAuditEvent(event, AuditLevel.INFO, AuditStatus.FAILED, message); return createUnsuccessfulOcspResp(OcspResponseStatus.unauthorized); } ContentVerifierProvider cvp; try { cvp = securityFactory.getContentVerifierProvider(certs[0]); } catch (InvalidKeyException ex) { LOG.warn("securityFactory.getContentVerifierProvider, InvalidKeyException: {}", ex.getMessage()); fillAuditEvent(event, AuditLevel.ERROR, AuditStatus.FAILED, ex.getMessage()); return createUnsuccessfulOcspResp(OcspResponseStatus.unauthorized); } boolean sigValid = request.isSignatureValid(cvp); if (!sigValid) { String message = "request signature is invalid"; LOG.warn(message); fillAuditEvent(event, AuditLevel.INFO, AuditStatus.FAILED, message); return createUnsuccessfulOcspResp(OcspResponseStatus.unauthorized); } // validate the certPath Date referenceTime = new Date(); if (canBuildCertpath(certs, requestOption, referenceTime)) { return null; } String message = "could not build certpath for the request's signer certificate"; LOG.warn(message); fillAuditEvent(event, AuditLevel.INFO, AuditStatus.FAILED, message); return createUnsuccessfulOcspResp(OcspResponseStatus.unauthorized); }