Example usage for org.bouncycastle.cert.ocsp OCSPReq getRequestorName

List of usage examples for org.bouncycastle.cert.ocsp OCSPReq getRequestorName

Introduction

In this page you can find the example usage for org.bouncycastle.cert.ocsp OCSPReq getRequestorName.

Prototype

public GeneralName getRequestorName() 

Source Link

Usage

From source file:Controllers.OCSPController.java

License:Apache License

/**
 * Method to do OCSP response to client.
 *
 * @param requestBytes/*  ww w  .  j av  a 2 s  . c  o  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.
 * /*  w  w w.  j  a v  a2  s  .  co 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.jruby.ext.openssl.OCSPRequest.java

License:Common Public License

@JRubyMethod(name = "verify", rest = true)
public IRubyObject verify(IRubyObject[] args) {
    Ruby runtime = getRuntime();/* w  w  w . j a v a  2 s . c  o  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);
}