Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

List of usage examples for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream.

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java

License:Open Source License

private static CMPCertificate[] getCMPCert(Certificate cert) throws CertificateEncodingException, IOException {
    ASN1InputStream ins = new ASN1InputStream(cert.getEncoded());
    try {/*w  w  w.  j av a2  s.  c o m*/
        ASN1Primitive pcert = ins.readObject();
        org.bouncycastle.asn1.x509.Certificate c = org.bouncycastle.asn1.x509.Certificate
                .getInstance(pcert.toASN1Primitive());
        CMPCertificate[] res = { new CMPCertificate(c) };
        return res;
    } finally {
        ins.close();
    }
}

From source file:org.ejbca.core.protocol.cmp.RevocationMessageHandler.java

License:Open Source License

public ResponseMessage handleMessage(final BaseCmpMessage msg, boolean authenticated) {
    if (LOG.isTraceEnabled()) {
        LOG.trace(">handleMessage");
    }//from  w  w w.jav  a  2 s  .c  o m

    CA ca = null;
    try {
        final String caDN = msg.getHeader().getRecipient().getName().toString();
        final int caId = CertTools.stringToBCDNString(caDN).hashCode();
        if (LOG.isDebugEnabled()) {
            LOG.debug("CA DN is '" + caDN + "' and resulting caId is " + caId
                    + ", after CertTools.stringToBCDNString conversion.");
        }
        ca = caSession.getCA(admin, caId);
    } catch (CADoesntExistsException e) {
        final String errMsg = "CA with DN '" + msg.getHeader().getRecipient().getName().toString()
                + "' is unknown";
        LOG.info(errMsg);
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                errMsg);
    } catch (AuthorizationDeniedException e) {
        LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()), e);
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                FailInfo.INCORRECT_DATA, e.getMessage());
    }

    ResponseMessage resp = null;
    // if version == 1 it is cmp1999 and we should not return a message back
    // Try to find a HMAC/SHA1 protection key
    final String keyId = CmpMessageHelper.getStringFromOctets(msg.getHeader().getSenderKID());
    ResponseStatus status = ResponseStatus.FAILURE;
    FailInfo failInfo = FailInfo.BAD_MESSAGE_CHECK;
    String failText = null;

    //Verify the authenticity of the message
    final VerifyPKIMessage messageVerifyer = new VerifyPKIMessage(ca.getCAInfo(), this.confAlias, admin,
            caSession, endEntityAccessSession, certificateStoreSession, authorizationSession,
            endEntityProfileSession, authenticationProviderSession, endEntityManagementSession,
            this.cmpConfiguration);
    ICMPAuthenticationModule authenticationModule = messageVerifyer
            .getUsedAuthenticationModule(msg.getMessage(), null, authenticated);
    if (authenticationModule == null) {
        LOG.info(messageVerifyer.getErrorMessage());
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                FailInfo.BAD_MESSAGE_CHECK, messageVerifyer.getErrorMessage());
    }

    // If authentication was correct, we will now try to find the certificate to revoke
    final PKIMessage pkimsg = msg.getMessage();
    final PKIBody body = pkimsg.getBody();
    final RevReqContent rr = (RevReqContent) body.getContent();
    RevDetails rd;
    try {
        rd = rr.toRevDetailsArray()[0];
    } catch (Exception e) {
        LOG.debug("Could not parse the revocation request. Trying to parse it as novosec generated message.");
        rd = CmpMessageHelper.getNovosecRevDetails(rr);
        LOG.debug("Succeeded in parsing the novosec generated request.");
    }
    final CertTemplate ct = rd.getCertDetails();
    final ASN1Integer serno = ct.getSerialNumber();
    final X500Name issuer = ct.getIssuer();
    // Get the revocation reason. 
    // For CMPv1 this can be a simple DERBitString or it can be a requested CRL Entry Extension
    // If there exists CRL Entry Extensions we will use that, because it's the only thing allowed in CMPv2
    int reason = RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED;
    final ASN1OctetString reasonoctets = rd.getCrlEntryDetails().getExtension(Extension.reasonCode)
            .getExtnValue();
    DERBitString reasonbits;
    try {
        reasonbits = new DERBitString(reasonoctets.getEncoded());
    } catch (IOException e1) {
        LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e1.getMessage()), e1);
        return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                FailInfo.INCORRECT_DATA, e1.getMessage());
    }
    if (reasonbits != null) {
        reason = CertTools.bitStringToRevokedCertInfo(reasonbits);
        if (LOG.isDebugEnabled()) {
            LOG.debug("CMPv1 revocation reason: " + reason);
        }
    }
    final Extensions crlExt = rd.getCrlEntryDetails();
    if (crlExt != null) {
        final Extension ext = crlExt.getExtension(Extension.reasonCode);
        if (ext != null) {
            try {
                final ASN1InputStream ai = new ASN1InputStream(ext.getExtnValue().getOctets());
                final ASN1Primitive obj = ai.readObject();
                final ASN1Enumerated crlreason = ASN1Enumerated.getInstance(obj);
                // RevokedCertInfo.REVOCATION_REASON_AACOMPROMISE are the same integer values as the CRL reason extension code
                reason = crlreason.getValue().intValue();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("CRLReason extension: " + reason);
                }
                ai.close();
            } catch (IOException e) {
                LOG.info("Exception parsin CRL reason extension: ", e);
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No CRL reason code extension present.");
            }
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No CRL entry extensions present");
        }
    }

    if ((serno != null) && (issuer != null)) {
        final String iMsg = INTRES.getLocalizedMessage("cmp.receivedrevreq", issuer.toString(),
                serno.getValue().toString(16));
        LOG.info(iMsg);
        try {
            endEntityManagementSession.revokeCert(admin, serno.getValue(), issuer.toString(), reason);
            status = ResponseStatus.SUCCESS;
        } catch (AuthorizationDeniedException e) {
            failInfo = FailInfo.NOT_AUTHORIZED;
            final String errMsg = INTRES.getLocalizedMessage("cmp.errornotauthrevoke", issuer.toString(),
                    serno.getValue().toString(16));
            failText = errMsg;
            LOG.info(failText);
        } catch (FinderException e) {
            failInfo = FailInfo.BAD_CERTIFICATE_ID;
            final String errMsg = INTRES.getLocalizedMessage("cmp.errorcertnofound", issuer.toString(),
                    serno.getValue().toString(16));
            failText = errMsg;
            // This is already info logged in endEntityManagementSession.revokeCert
            // LOG.info(failText);
        } catch (WaitingForApprovalException e) {
            status = ResponseStatus.GRANTED_WITH_MODS;
        } catch (ApprovalException e) {
            failInfo = FailInfo.BAD_REQUEST;
            final String errMsg = INTRES.getLocalizedMessage("cmp.erroralreadyrequested");
            failText = errMsg;
            LOG.info(failText);
        } catch (AlreadyRevokedException e) {
            failInfo = FailInfo.BAD_REQUEST;
            final String errMsg = INTRES.getLocalizedMessage("cmp.erroralreadyrevoked");
            failText = errMsg;
            // This is already info logged in endEntityManagementSession.revokeCert
            // LOG.info(failText);
        }
    } else {
        failInfo = FailInfo.BAD_CERTIFICATE_ID;
        final String errMsg = INTRES.getLocalizedMessage("cmp.errormissingissuerrevoke", issuer.toString(),
                serno.getValue().toString(16));
        failText = errMsg;
        LOG.info(failText);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating a PKI revocation message response");
    }
    final CmpRevokeResponseMessage rresp = new CmpRevokeResponseMessage();
    rresp.setRecipientNonce(msg.getSenderNonce());
    rresp.setSenderNonce(new String(Base64.encode(CmpMessageHelper.createSenderNonce())));
    rresp.setSender(msg.getRecipient());
    rresp.setRecipient(msg.getSender());
    rresp.setTransactionId(msg.getTransactionId());
    rresp.setFailInfo(failInfo);
    rresp.setFailText(failText);
    rresp.setStatus(status);

    if (StringUtils.equals(responseProtection, "pbe")) {
        final HMACAuthenticationModule hmacmodule = (HMACAuthenticationModule) authenticationModule;
        final String owfAlg = hmacmodule.getCmpPbeVerifyer().getOwfOid();
        final String macAlg = hmacmodule.getCmpPbeVerifyer().getMacOid();
        final int iterationCount = 1024;
        final String cmpRaAuthSecret = hmacmodule.getAuthenticationString();

        if ((owfAlg != null) && (macAlg != null) && (keyId != null) && (cmpRaAuthSecret != null)) {
            // Set all protection parameters
            if (LOG.isDebugEnabled()) {
                LOG.debug(responseProtection + ", " + owfAlg + ", " + macAlg + ", " + keyId + ", "
                        + cmpRaAuthSecret);
            }
            rresp.setPbeParameters(keyId, cmpRaAuthSecret, owfAlg, macAlg, iterationCount);
        }
    } else if (StringUtils.equals(responseProtection, "signature")) {
        try {
            final CryptoToken cryptoToken = cryptoTokenSession
                    .getCryptoToken(ca.getCAToken().getCryptoTokenId());
            final String aliasCertSign = ca.getCAToken()
                    .getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
            rresp.setSignKeyInfo(ca.getCertificateChain(), cryptoToken.getPrivateKey(aliasCertSign),
                    cryptoToken.getSignProviderName());
            if (msg.getHeader().getProtectionAlg() != null) {
                rresp.setPreferredDigestAlg(AlgorithmTools
                        .getDigestFromSigAlg(msg.getHeader().getProtectionAlg().getAlgorithm().getId()));
            }
        } catch (CryptoTokenOfflineException e) {
            LOG.error(e.getLocalizedMessage(), e);
        }
    }
    resp = rresp;
    try {
        resp.create();
    } catch (InvalidKeyException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (NoSuchAlgorithmException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (NoSuchProviderException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (CertificateEncodingException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    } catch (CRLException e) {
        String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
        LOG.error(errMsg, e);
    }

    return resp;
}

From source file:org.ejbca.core.protocol.MSPKCS10RequestMessage.java

License:Open Source License

/**
 * Returns the name of the Certificate Template or null if not available or not known.
 *//*from  w ww .  ja va  2s .  c  om*/
public String getMSRequestInfoTemplateName() {
    if (pkcs10 == null) {
        log.error("PKCS10 not inited!");
        return null;
    }
    // Get attributes
    Attribute[] attributes = pkcs10.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    if (attributes.length == 0) {
        log.error("Cannot find request extension.");
        return null;
    }
    ASN1Set set = attributes[0].getAttrValues();
    DERSequence seq = (DERSequence) DERSequence.getInstance(set.getObjectAt(0));
    Enumeration<?> enumeration = seq.getObjects();
    while (enumeration.hasMoreElements()) {
        DERSequence seq2 = (DERSequence) DERSequence.getInstance(enumeration.nextElement());
        ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) seq2.getObjectAt(0);
        if (szOID_ENROLL_CERTTYPE_EXTENSION.equals(oid.getId())) {
            try {
                DEROctetString dos = (DEROctetString) seq2.getObjectAt(1);
                ASN1InputStream dosAsn1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(dos.getOctets()));
                try {
                    ASN1String derobj = (ASN1String) dosAsn1InputStream.readObject();
                    return derobj.getString();
                } finally {
                    dosAsn1InputStream.close();
                }
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
    return null;
}

From source file:org.ejbca.core.protocol.MSPKCS10RequestMessage.java

License:Open Source License

/**
 * Returns a String vector with known subject altnames:
 *   [0] Requested GUID/*from   w w w.ja  va2  s .  c o m*/
 *   [1] Requested DNS
 */
public String[] getMSRequestInfoSubjectAltnames() {
    String[] ret = new String[2]; // GUID, DNS so far..
    if (pkcs10 == null) {
        log.error("PKCS10 not inited!");
        return ret;
    }
    // Get attributes
    Attribute[] attributes = pkcs10.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    if (attributes.length != 0) {
        ASN1Set set = attributes[0].getAttrValues();
        DERSequence seq = (DERSequence) DERSequence.getInstance(set.getObjectAt(0));
        Enumeration<?> enumeration = seq.getObjects();
        while (enumeration.hasMoreElements()) {
            DERSequence seq2 = (DERSequence) DERSequence.getInstance(enumeration.nextElement());
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) seq2.getObjectAt(0);
            if ("2.5.29.17".equals(oid.getId())) { //SubjectAN
                try {
                    DEROctetString dos = (DEROctetString) seq2.getObjectAt(2);
                    ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(dos.getOctets()));
                    while (ais.available() > 0) {
                        DERSequence seq3 = (DERSequence) ais.readObject();
                        Enumeration<?> enum1 = seq3.getObjects();
                        while (enum1.hasMoreElements()) {
                            DERTaggedObject dto = (DERTaggedObject) enum1.nextElement();
                            if (dto.getTagNo() == 0) {
                                // Sequence of OIDs and tagged objects
                                DERSequence ds = (DERSequence) dto.getObject();
                                ASN1ObjectIdentifier doid = (ASN1ObjectIdentifier) ds.getObjectAt(0);
                                if (OID_GUID.equals((doid).getId())) {
                                    DEROctetString dos3 = (DEROctetString) ((DERTaggedObject) ds.getObjectAt(1))
                                            .getObject();
                                    ret[0] = dos3.toString().substring(1); // Removes the initial #-sign
                                }
                            } else if (dto.getTagNo() == 2) {
                                // DNS
                                DEROctetString dos3 = (DEROctetString) dto.getObject();
                                ret[1] = new String(dos3.getOctets());
                            }
                        }
                    }
                    ais.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }
    }
    return ret;
}

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

License:Open Source License

/**
 *
 * @param ocspPackage//from   w  w  w.j  a  v a  2s  .  co  m
 * @param nonce
 * @param respCode expected response code, OK = 0, if not 0, response checking will not continue after response code is checked.
 * @param httpCode, normally 200 for OK or OCSP error. Can be 400 is more than 1 million bytes is sent for example
 * @return a SingleResp or null if respCode != 0
 * @throws IOException
 * @throws OCSPException
 * @throws NoSuchProviderException
 * @throws CertificateException on parsing errors.
 * @throws OperatorCreationException 
 */
protected SingleResp[] sendOCSPPost(byte[] ocspPackage, String nonce, int respCode, int httpCode)
        throws IOException, OCSPException, NoSuchProviderException, OperatorCreationException,
        CertificateException {
    // POST the OCSP request
    URL url = new URL(this.sBaseURL + this.urlEnding);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    // we are going to do a POST
    con.setDoOutput(true);
    con.setRequestMethod("POST");

    // POST it
    con.setRequestProperty("Content-Type", "application/ocsp-request");
    OutputStream os = con.getOutputStream();
    os.write(ocspPackage);
    os.close();
    assertEquals("Response code", httpCode, con.getResponseCode());
    if (con.getResponseCode() != 200) {
        return null; // if it is an http error code we don't need to test any more
    }
    // Some appserver (Weblogic) responds with "application/ocsp-response; charset=UTF-8"
    assertNotNull("No Content-Type in reply.", con.getContentType());
    assertTrue(con.getContentType().startsWith("application/ocsp-response"));
    OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream()));
    assertEquals("Response status not the expected.", respCode, response.getStatus());
    if (respCode != 0) {
        assertNull("According to RFC 2560, responseBytes are not set on error.", response.getResponseObject());
        return null; // it messes up testing of invalid signatures... but is needed for the unsuccessful responses
    }
    BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    X509CertificateHolder[] chain = brep.getCerts();
    assertNotNull(
            "No certificate chain returned in response (chain == null), is ocsp.includesignercert=false in ocsp.properties?. It should be set to default value for test to run.",
            chain);
    boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(chain[0]));
    assertTrue("Response failed to verify.", verify);
    // Check nonce (if we sent one)
    if (nonce != null) {
        byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue()
                .getEncoded();
        assertNotNull(noncerep);
        ASN1InputStream ain = new ASN1InputStream(noncerep);
        ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject());
        ain.close();
        assertEquals(nonce, new String(oct.getOctets()));
    }
    SingleResp[] singleResps = brep.getResponses();
    return singleResps;
}

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

License:Open Source License

/**
 *
 * @param ocspPackage//  w  w  w. j a v  a2s  .c  o m
 * @param nonce
 * @param respCode expected response code, OK = 0, if not 0, response checking will not continue after response code is checked.
 * @param httpCode, normally 200 for OK or OCSP error. Can be 400 is more than 1 million bytes is sent for example
 * @return a BasicOCSPResp or null if not found
 * @throws IOException
 * @throws OCSPException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException on parsing errors.
 * @throws OperatorCreationException 
 */
protected BasicOCSPResp sendOCSPGet(byte[] ocspPackage, String nonce, int respCode, int httpCode,
        boolean shouldIncludeSignCert, X509Certificate signCert) throws IOException, OCSPException,
        NoSuchProviderException, NoSuchAlgorithmException, OperatorCreationException, CertificateException {
    // GET the OCSP request
    String b64 = new String(Base64.encode(ocspPackage, false));
    //String urls = URLEncoder.encode(b64, "UTF-8");   // JBoss/Tomcat will not accept escaped '/'-characters by default
    URL url = new URL(this.sBaseURL + '/' + b64 + this.urlEnding);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    if (con.getResponseCode() != httpCode) {
        log.info("URL when request gave unexpected result: " + url.toString() + " Message was: "
                + con.getResponseMessage());
    }
    assertEquals("Response code did not match. ", httpCode, con.getResponseCode());
    if (con.getResponseCode() != 200) {
        return null; // if it is an http error code we don't need to test any more
    }
    // Some appserver (Weblogic) responds with "application/ocsp-response; charset=UTF-8"
    assertNotNull(con.getContentType());
    assertTrue(con.getContentType().startsWith("application/ocsp-response"));
    OCSPResp response = new OCSPResp(IOUtils.toByteArray(con.getInputStream()));
    assertNotNull("Response should not be null.", response);
    assertEquals("Response status not the expected.", respCode, response.getStatus());
    if (respCode != 0) {
        assertNull("According to RFC 2560, responseBytes are not set on error.", response.getResponseObject());
        return null; // it messes up testing of invalid signatures... but is needed for the unsuccessful responses
    }
    BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();

    final X509CertificateHolder signCertHolder;
    if (!shouldIncludeSignCert) {
        assertEquals("The signing certificate should not be included in the OCSP response ", 0,
                brep.getCerts().length);
        signCertHolder = new JcaX509CertificateHolder(signCert);
    } else {
        X509CertificateHolder[] chain = brep.getCerts();
        signCertHolder = chain[0];
    }
    boolean verify = brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(signCertHolder));

    assertTrue("Response failed to verify.", verify);
    // Check nonce (if we sent one)
    if (nonce != null) {
        byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue()
                .getEncoded();
        assertNotNull(noncerep);
        ASN1InputStream ain = new ASN1InputStream(noncerep);
        ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject());
        ain.close();
        assertEquals(nonce, new String(oct.getOctets()));
    }
    return brep;
}

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

License:Open Source License

private OCSPUnidResponse sendOCSPRequest(byte[] ocspPackage, X509Certificate knownTrustAnchor, boolean useGet)
        throws IOException, OCSPException, OperatorCreationException, CertificateException,
        UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    final HttpURLConnection con;
    if (useGet) {
        String b64 = new String(Base64.encode(ocspPackage, false));
        URL url = new URL(httpReqPath + '/' + b64);
        con = (HttpURLConnection) url.openConnection();
    } else {//  ww  w  . j  a va 2  s .  c  o  m
        // POST the OCSP request
        URL url = new URL(httpReqPath);
        con = (HttpURLConnection) getUrlConnection(url);
        // we are going to do a POST
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        // POST it
        con.setRequestProperty("Content-Type", "application/ocsp-request");
        OutputStream os = null;
        try {
            os = con.getOutputStream();
            os.write(ocspPackage);
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }
    final OCSPUnidResponse ret = new OCSPUnidResponse();
    ret.setHttpReturnCode(con.getResponseCode());
    if (ret.getHttpReturnCode() != 200) {
        if (ret.getHttpReturnCode() == 401) {
            ret.setErrorCode(OCSPUnidResponse.ERROR_UNAUTHORIZED);
        } else {
            ret.setErrorCode(OCSPUnidResponse.ERROR_UNKNOWN);
        }
        return ret;
    }
    final OCSPResp response;
    {
        final InputStream in = con.getInputStream();
        if (in != null) {
            try {
                response = new OCSPResp(IOUtils.toByteArray(in));
            } finally {
                in.close();
            }
        } else {
            response = null;
        }
    }
    if (response == null) {
        ret.setErrorCode(OCSPUnidResponse.ERROR_NO_RESPONSE);
        return ret;
    }
    ret.setResp(response);
    final BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    if (brep == null) {
        ret.setErrorCode(OCSPUnidResponse.ERROR_NO_RESPONSE);
        return ret;
    }
    // Compare nonces to see if the server sent the same nonce as we sent
    final byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue()
            .getEncoded();
    if (noncerep != null) {
        ASN1InputStream ain = new ASN1InputStream(noncerep);
        ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject());
        ain.close();
        boolean eq = ArrayUtils.isEquals(this.nonce, oct.getOctets());
        if (!eq) {
            ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_NONCE);
            return ret;
        }
    }

    final RespID id = brep.getResponderId();
    final DERTaggedObject to = (DERTaggedObject) id.toASN1Object().toASN1Primitive();
    final RespID respId;
    final X509CertificateHolder[] chain = brep.getCerts();
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    X509Certificate signerCertificate = converter.getCertificate(chain[0]);
    final PublicKey signerPub = signerCertificate.getPublicKey();
    if (to.getTagNo() == 1) {
        // This is Name
        respId = new JcaRespID(signerCertificate.getSubjectX500Principal());
    } else {
        // This is KeyHash
        respId = new JcaRespID(signerPub, SHA1DigestCalculator.buildSha1Instance());
    }
    if (!id.equals(respId)) {
        // Response responderId does not match signer certificate responderId!
        ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERID);
    }
    if (!brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(signerPub))) {
        ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNATURE);
        return ret;
    }

    /* 
     * Okay, at this point we have three different variables and six different possible valid use cases. These
     * variables are:
     *          1. If the OCSP reply is from a CA (integrated) or an OCSP responder (standalone) 
     *          2. If it was from a CA, then if that CA is self signed or a subCA
     *          3. If the server (in the integrated case) or keybinding (standalone case) was set to include the certificate chain
     */

    //If we have a chain, verify it
    if (chain.length > 1) {
        // end at one shortof chain.length, because the root certificate is (usually) not included in the OCSP response
        // TODO: improve this when we can pass in the root cert from parameter to properly validate the whole chain
        for (int i = 0; i + 1 < chain.length; i++) {
            final X509Certificate cert1 = converter.getCertificate(chain[i]);
            final X509Certificate cert2 = converter.getCertificate(chain[Math.min(i + 1, chain.length - 1)]);
            try {
                cert1.verify(cert2.getPublicKey());
            } catch (GeneralSecurityException e) {
                m_log.info("Verifying problem with", e);
                m_log.info("Certificate to be verified: " + cert1);
                m_log.info("Verifying certificate: " + cert2);
                ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
                return ret;
            }
        }
    }

    if (CertTools.isCA(signerCertificate)) {
        //Verify that the signer certificate was the same as the trust anchor
        if (!signerCertificate.getSerialNumber().equals(knownTrustAnchor.getSerialNumber())) {
            m_log.info("Signing certificate for integrated OCSP was not the provided trust anchor.");
            ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
            return ret;
        }
    } else if (CertTools.isOCSPCert(signerCertificate)) {
        //If an OCSP certificate was used to sign
        try {
            signerCertificate.verify(knownTrustAnchor.getPublicKey());
        } catch (GeneralSecurityException e) {
            m_log.info("Signing certificate was not signed by known trust anchor.");
            ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
            return ret;
        }
    } else {
        m_log.info("Signing certificate was not an OCSP certificate.");
        ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
        return ret;
    }

    String fnr = getFnr(brep);
    if (fnr != null) {
        ret.setFnr(fnr);
    }
    return ret;
}

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

License:Open Source License

private String getFnr(BasicOCSPResp brep) throws IOException {
    Extension fnrrep = brep.getExtension(FnrFromUnidExtension.FnrFromUnidOid);
    if (fnrrep == null) {
        return null;
    }//  w  ww . ja  v  a2  s  . c  o m
    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(fnrrep.getExtnValue().getEncoded()));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    FnrFromUnidExtension fnrobj = FnrFromUnidExtension.getInstance(aIn.readObject());
    return fnrobj.getFnr();
}

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

License:Open Source License

public static BasicOCSPRespGenerator createOCSPResponse(OCSPReq req, X509Certificate respondercert,
        int respIdType) throws OCSPException, NotSupportedException {
    if (null == req) {
        throw new IllegalArgumentException();
    }//from   w  w  w  .  ja  v a2s  .  c o m
    BasicOCSPRespGenerator res = null;
    if (respIdType == OcspConfiguration.RESPONDERIDTYPE_NAME) {
        res = new BasicOCSPRespGenerator(new RespID(respondercert.getSubjectX500Principal()));
    } else {
        res = new BasicOCSPRespGenerator(respondercert.getPublicKey());
    }
    X509Extensions reqexts = req.getRequestExtensions();
    if (reqexts != null) {
        X509Extension ext = reqexts.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_response);
        if (null != ext) {
            //m_log.debug("Found extension AcceptableResponses");
            ASN1OctetString oct = ext.getValue();
            try {
                ASN1Sequence seq = ASN1Sequence.getInstance(
                        new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject());
                Enumeration en = seq.getObjects();
                boolean supportsResponseType = false;
                while (en.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement();
                    //m_log.debug("Found oid: "+oid.getId());
                    if (oid.equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic)) {
                        // This is the response type we support, so we are happy! Break the loop.
                        supportsResponseType = true;
                        m_log.debug("Response type supported: " + oid.getId());
                        continue;
                    }
                }
                if (!supportsResponseType) {
                    throw new NotSupportedException(
                            "Required response type not supported, this responder only supports id-pkix-ocsp-basic.");
                }
            } catch (IOException e) {
            }
        }
    }
    return res;
}

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

License:Open Source License

private String getFnr(BasicOCSPResp brep) throws IOException {
    byte[] fnrrep = brep.getExtension(FnrFromUnidExtension.FnrFromUnidOid).getExtnValue().getEncoded();
    if (fnrrep == null) {
        return null;
    }//from   w  w  w.  j  a v a  2  s.co m
    assertNotNull(fnrrep);
    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(fnrrep));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    FnrFromUnidExtension fnrobj = FnrFromUnidExtension.getInstance(aIn.readObject());
    return fnrobj.getFnr();
}