Example usage for org.bouncycastle.asn1.ocsp OCSPResponseStatus SIG_REQUIRED

List of usage examples for org.bouncycastle.asn1.ocsp OCSPResponseStatus SIG_REQUIRED

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.ocsp OCSPResponseStatus SIG_REQUIRED.

Prototype

int SIG_REQUIRED

To view the source code for org.bouncycastle.asn1.ocsp OCSPResponseStatus SIG_REQUIRED.

Click Source Link

Usage

From source file:ee.ria.xroad.signer.certmanager.OcspClient.java

License:Open Source License

private static void verifyResponse(OCSPResp response) throws Exception {
    int responseStatus = response.getStatus();

    if (responseStatus == OCSPResponseStatus.SUCCESSFUL) {
        return;/*  www . ja  v  a  2 s  .  c o m*/
    }

    if (responseStatus == OCSPResponseStatus.SIG_REQUIRED) {
        throw new OCSPException("OCSP responder requires request to be signed");
    }

    throw new OCSPException("Invalid OCSP response status: " + responseStatus);
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspSignedHttpTest.java

License:Open Source License

/** Tests ocsp message
 * @throws Exception error//from w  w  w  .  j a v  a2  s  .  co  m
 */
@Test
public void test01OcspGood() throws Exception {
    log.trace(">test01OcspGood()");

    // find a CA (TestCA?) create a user and generate his cert
    // send OCSP req to server and get good response
    // change status of cert to bad status
    // send OCSP req and get bad status
    // (send crap message and get good error)

    // Make user that we know...
    boolean userExists = endEntityManagementSession.existsUser(END_ENTITY_NAME);
    if (!userExists) {
        endEntityManagementSession.addUser(admin, END_ENTITY_NAME, "foo123", "C=SE,O=AnaTom,CN=OCSPTest", null,
                "ocsptest@anatom.se", false, SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityTypes.ENDUSER.toEndEntityType(),
                SecConst.TOKEN_SOFT_PEM, 0, caid);
        log.debug("created user: ocsptest, foo123, C=SE, O=AnaTom, CN=OCSPTest");
    } else {
        log.debug("User ocsptest already exists.");
        EndEntityInformation userData = new EndEntityInformation(END_ENTITY_NAME, "C=SE,O=AnaTom,CN=OCSPTest",
                caid, null, "ocsptest@anatom.se", EndEntityConstants.STATUS_NEW,
                EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, null, SecConst.TOKEN_SOFT_PEM, 0,
                null);
        userData.setPassword("foo123");
        endEntityManagementSession.changeUser(admin, userData, false);
        log.debug("Reset status to NEW");
    }
    try {
        // Generate certificate for the new user
        KeyPair keys = KeyTools.genKeys("512", "RSA");

        // user that we know exists...
        ocspTestCert = (X509Certificate) signSession.createCertificate(admin, "ocsptest", "foo123",
                new PublicKeyWrapper(keys.getPublic()));
        assertNotNull("Failed to create a certificate", ocspTestCert);

        // And an OCSP request
        OCSPReqBuilder gen = new OCSPReqBuilder();
        gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
                ocspTestCert.getSerialNumber()));
        Extension[] extensions = new Extension[1];
        extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
                new DEROctetString("123456789".getBytes()));
        gen.setRequestExtensions(new Extensions(extensions));
        X509CertificateHolder chain[] = new JcaX509CertificateHolder[2];
        chain[0] = new JcaX509CertificateHolder(ocspTestCert);
        chain[1] = new JcaX509CertificateHolder(cacert);
        gen.setRequestorName(chain[0].getSubject());
        OCSPReq req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA")
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), 20480), chain);
        // Send the request and receive a singleResponse
        SingleResp[] singleResps = helper.sendOCSPPost(req.getEncoded(), "123456789",
                OCSPResponseStatus.SUCCESSFUL, 200);
        assertEquals("Number of of SingResps should be 1.", 1, singleResps.length);
        SingleResp singleResp = singleResps[0];

        CertificateID certId = singleResp.getCertID();
        assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(),
                ocspTestCert.getSerialNumber());
        Object status = singleResp.getCertStatus();
        assertEquals("Status is not null (good)", null, status);

        // Try with an unsigned request, we should get a status code 5 back from the server (signature required)
        req = gen.build();
        // Send the request and receive a singleResponse, this response should have error code SIGNATURE_REQUIRED
        singleResps = helper.sendOCSPPost(req.getEncoded(), "123456789", OCSPResponseStatus.SIG_REQUIRED, 200);
        assertNull(singleResps);

        // sign with a keystore where the CA-certificate is not known
        KeyStore store = KeyStore.getInstance("PKCS12", "BC");
        ByteArrayInputStream fis = new ByteArrayInputStream(ks3);
        store.load(fis, "foo123".toCharArray());
        Certificate[] certs = KeyTools.getCertChain(store, "privateKey");
        chain[0] = new JcaX509CertificateHolder((X509Certificate) certs[0]);
        chain[1] = new JcaX509CertificateHolder((X509Certificate) certs[1]);
        PrivateKey pk = (PrivateKey) store.getKey("privateKey", "foo123".toCharArray());
        req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA").build(pk), 20480),
                chain);
        // Send the request and receive a singleResponse, this response should have error code UNAUTHORIZED (6)
        singleResps = helper.sendOCSPPost(req.getEncoded(), "123456789", OCSPResponseStatus.UNAUTHORIZED, 200);
        assertNull(singleResps);
    } finally {
        endEntityManagementSession.deleteUser(roleMgmgToken, END_ENTITY_NAME);
    }
    log.trace("<test01OcspGood()");
}

From source file:org.viafirma.nucleo.validacion.OcspValidatorHandler.java

License:Apache License

/**
 * Valida mediante ocsp RFC 2560, el certificado indicado.
 * /*from w  ww.  j  a v  a  2  s  .  co  m*/
 * @param certificadoX509
 *            Certificado que deseamos validar.
 * @param certificadoX509Emisor
 *            Certificado emisor del certificado a validar.
 * @return
 * @throws CertPathValidatorException
 */
private CodigoError validarOCSP(X509Certificate certificadoX509, X509Certificate certificadoX509Emisor)
        throws CertPathValidatorException {
    // Si la validacin esta desactivada consideramos el certificado
    // validado.
    if (validacionOnline) {
        try {
            // Generamos la peticin OCSP para el certificado.
            OCSPReq request = generateRequest(certificadoX509, certificadoX509Emisor);

            // Recuperamos la url desde la que realizar la validacin OCSP
            String url = getUrlOCSP(certificadoX509);

            // Bytes del request
            byte[] byteRequest = request.getEncoded();

            // Enviamos la peticin y recuperamos la respuesta
            InputStream inResponse = sendRequest(url, byteRequest);
            OCSPResp ocspResponse = new OCSPResp(inResponse);

            // but why Response Status is 6(No Valid)..?
            if (OCSPResponseStatus.SUCCESSFUL == ocspResponse.getStatus()) {
                log.info("Obtenida respuesta correcta OCSP.  Estado:" + ocspResponse.getStatus());
                CertificateID certID = new CertificateID(CertificateID.HASH_SHA1, certificadoX509Emisor,
                        certificadoX509.getSerialNumber());
                BasicOCSPResp brep = (BasicOCSPResp) ocspResponse.getResponseObject();

                // Comprobamos que la respuesta OCSP no ha sido manipulada y
                // ha sido firmada por un certificado de confianza.
                // Recupero el certificado con el que debe haber sido
                // firmado el ocsp
                checkOCSP(brep);
                SingleResp[] singleResp = brep.getResponses();

                for (SingleResp resp : singleResp) {
                    CertificateID respCertID = resp.getCertID();
                    if (respCertID.equals(certID)) {
                        Object status = resp.getCertStatus();
                        if (status == CertificateStatus.GOOD) {
                            log.debug("OCSPChecker: Status of certificate is: good");
                            break;
                        } else if (status instanceof org.bouncycastle.ocsp.RevokedStatus) {
                            log.debug("OCSPChecker: Status of certificate is: revoked");
                            throw new CertPathValidatorException("Certificate has been revoked");
                        } else if (status instanceof org.bouncycastle.ocsp.UnknownStatus) {
                            log.debug("OCSPChecker: Status of certificate is: unknown");
                            throw new CertPathValidatorException("Certificate's revocation status is unknown");
                        } else {
                            log.debug("Status of certificate is: not recognized");
                            throw new CertPathValidatorException("Unknown OCSP response for certificate");
                        }
                    }

                }

                return CodigoError.OK_CERTIFICADO_VALIDADO;
            } else {
                /**
                 * successful (0), --Response has valid confirmations
                 * malformedRequest (1), --Illegal confirmation request
                 * internalError (2), --Internal error in issuer tryLater
                 * (3), --Try again later --(4) is not used sigRequired (5),
                 * --Must sign the request unauthorized (6) --Request
                 * unauthorized
                 */
                if (OCSPResponseStatus.MALFORMED_REQUEST == ocspResponse.getStatus()) {
                    log.warn(
                            "Obtenida respuesta Incorrecta OCSP: malformedRequest (1), --Illegal confirmation request. estatus: "
                                    + ocspResponse.getStatus());
                    return CodigoError.ERROR_OCSP_URL;
                } else if (OCSPResponseStatus.INTERNAL_ERROR == ocspResponse.getStatus()) {
                    log.warn(
                            "Obtenida respuesta Incorrecta OCSP: internalError (2),--Internal error in issuer. estatus: "
                                    + ocspResponse.getStatus());
                    return CodigoError.ERROR_OCSP_INTERNAL_ERROR;
                } else if (OCSPResponseStatus.TRY_LATER == ocspResponse.getStatus()) {
                    log.warn("Obtenida respuesta Incorrecta OCSP: tryLater (3), --Try again later. estatus: "
                            + ocspResponse.getStatus());
                    return CodigoError.ERROR_OCSP_TRY_LATER;
                } else if (OCSPResponseStatus.SIG_REQUIRED == ocspResponse.getStatus()) {
                    log.warn(
                            "Obtenida respuesta Incorrecta OCSP: sigRequired(5),--Must sign the request. estatus: "
                                    + ocspResponse.getStatus());
                    return CodigoError.ERROR_OCSP_INTERNAL_ERROR;
                } else if (OCSPResponseStatus.SIG_REQUIRED == ocspResponse.getStatus()) {
                    log.warn(
                            "Obtenida respuesta Incorrecta OCSP: unauthorized (6)--Request unauthorized. estatus: "
                                    + ocspResponse.getStatus());
                    return CodigoError.ERROR_OCSP_INTERNAL_ERROR;
                } else {
                    log.warn(
                            "Obtenida una respuesta incorrecta OCSP, probablemente el certificado este caducado.");
                    return CodigoError.ERROR_VALIDACION_CERTIFICADO_CADUCADO;
                }

            }

        } catch (OCSPException e) {
            log.fatal(CodigoError.ERROR_OCSP_INTERNAL_ERROR, e);
            return CodigoError.ERROR_OCSP_INTERNAL_ERROR;
        } catch (ExcepcionErrorInterno e) {
            log.error("No se puede validar el certificado. ", e);
            return e.getCodError();
        } catch (IOException e) {
            log.fatal(CodigoError.ERROR_INTERNO, e);
            return CodigoError.ERROR_INTERNO;
        }
    } else {
        log.info("La validacin online OCSP esta desactivada. Consideramos el certificado Vlido.");
        return CodigoError.OK_CERTIFICADO_VALIDADO;
    }
}