Example usage for org.bouncycastle.asn1.x500 X500Name toString

List of usage examples for org.bouncycastle.asn1.x500 X500Name toString

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x500 X500Name toString.

Prototype

public String toString() 

Source Link

Usage

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

License:Open Source License

@Test
public void test13CrmfReqClientModeHMAC() throws Exception {
    String clientPassword = "foo123client";

    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_HMAC);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, clientPassword);
    this.cmpConfiguration.setRAMode(ALIAS, false);
    this.cmpConfiguration.setAllowRAVerifyPOPO(ALIAS, true);
    this.cmpConfiguration.setResponseProtection(ALIAS, "signature");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    String clientUsername = "clientTestUser";
    final X500Name clientDN = new X500Name("CN=" + clientUsername + ",C=SE");
    createUser(clientUsername, clientDN.toString(), clientPassword, true, this.caid,
            SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);

    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

    PKIMessage msg = genCertReq(issuerDN, clientDN, keys, this.cacert, this.nonce, this.transid, true, null,
            null, null, null, null, null);
    assertNotNull("Generating CrmfRequest failed.", msg);
    CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
    X500Name reqissuer = ir.toCertReqMsgArray()[0].getCertReq().getCertTemplate().getIssuer();
    assertNotNull("reqissuer is null", reqissuer);

    PKIMessage req = protectPKIMessage(msg, false, clientPassword, "mykeyid", 567);
    assertNotNull("Protecting PKIMessage with HMACPbe failed.", req);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);/*  w w w  .j av a  2  s  .  c o  m*/
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
    checkCmpResponseGeneral(resp, issuerDN, clientDN, this.cacert, req.getHeader().getSenderNonce().getOctets(),
            req.getHeader().getTransactionID().getOctets(), true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    ir = (CertReqMessages) req.getBody().getContent();
    Certificate cert1 = checkCmpCertRepMessage(clientDN, this.cacert, resp,
            ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
    assertNotNull("Crmf request did not return a certificate", cert1);

    // 
    // Try a request with no issuerDN in the certTemplate
    createUser(clientUsername, clientDN.toString(), clientPassword, true, this.caid,
            SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    try {
        PKIMessage msgNoIssuer = genCertReq(null, clientDN, keys, this.cacert, this.nonce, this.transid, true,
                null, null, null, null, null, null);
        assertNotNull("Generating CrmfRequest with no issuer failed.", msgNoIssuer);
        PKIMessage reqNoIssuer = protectPKIMessage(msgNoIssuer, false, clientPassword, "mykeyid", 567);
        assertNotNull("Protecting PKIMessage with HMACPbe failed.", req);
        ByteArrayOutputStream bao2 = new ByteArrayOutputStream();
        DEROutputStream out2 = new DEROutputStream(bao2);
        out2.writeObject(reqNoIssuer);
        byte[] ba2 = bao2.toByteArray();
        // Send request and receive response
        byte[] respNoIssuer = sendCmpHttp(ba2, 200, ALIAS);
        checkCmpResponseGeneral(respNoIssuer, issuerDN, clientDN, this.cacert,
                reqNoIssuer.getHeader().getSenderNonce().getOctets(),
                reqNoIssuer.getHeader().getTransactionID().getOctets(), true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        ir = (CertReqMessages) reqNoIssuer.getBody().getContent();
        Certificate cert2 = checkCmpCertRepMessage(clientDN, this.cacert, respNoIssuer,
                ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
        assertNotNull("Crmf request did not return a certificate", cert2);

        // Send a confirm message to the CA
        String hash = CertTools.getFingerprintAsString(cert2);
        int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        PKIMessage confirm = genCertConfirm(USER_DN, this.cacert, this.nonce, this.transid, hash, reqId);
        PKIMessage protectedConfirm = protectPKIMessage(confirm, false, clientPassword, null, 567);
        assertNotNull(protectedConfirm);
        ByteArrayOutputStream bao3 = new ByteArrayOutputStream();
        DEROutputStream out3 = new DEROutputStream(bao3);
        out3.writeObject(protectedConfirm);
        byte[] ba3 = bao3.toByteArray();
        // Send request and receive response
        byte[] resp3 = sendCmpHttp(ba3, 200, ALIAS);
        checkCmpResponseGeneral(resp3, issuerDN, USER_DN, this.cacert, this.nonce, this.transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpPKIConfirmMessage(USER_DN, this.cacert, resp3);
    } finally {
        this.endEntityManagementSession.deleteUser(ADMIN, clientUsername);
    }
}

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

License:Open Source License

@Test
public void test14HMACModuleInClientMode()
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException,
        IOException, InvalidAlgorithmParameterException, AuthorizationDeniedException,
        UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, EjbcaException, java.lang.Exception {

    this.cmpConfiguration.setRAMode(ALIAS, false);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    final String clientUsername = "clientTestUser";
    final X500Name clientDN = new X500Name("CN=" + clientUsername + ",C=SE");
    final String clientPassword = "foo123client";

    createUser(clientUsername, clientDN.toString(), clientPassword, true, this.caid,
            SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    try {//from ww w  .  ja  va 2s .com
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

        PKIMessage msg = genCertReq(issuerDN, clientDN, keys, this.cacert, this.nonce, this.transid, false,
                null, null, null, null, null, null);
        assertNotNull("Generating CrmfRequest failed.", msg);
        PKIMessage req = protectPKIMessage(msg, false, clientPassword, "mykeyid", 567);
        assertNotNull("Protecting PKIMessage failed", req);

        HMACAuthenticationModule hmac = new HMACAuthenticationModule(ADMIN, "-", ALIAS, this.cmpConfiguration,
                this.caSession.getCAInfo(ADMIN, this.caid), this.eeAccessSession);
        hmac.verifyOrExtract(req, null);
        assertNotNull("HMAC returned null password.", hmac.getAuthenticationString());
        assertEquals("HMAC returned the wrong password", clientPassword, hmac.getAuthenticationString());

        // Test the same but without issuerDN in the request
        msg = genCertReq(null, clientDN, keys, this.cacert, this.nonce, this.transid, false, null, null, null,
                null, null, null);
        assertNotNull("Generating CrmfRequest failed.", msg);
        req = protectPKIMessage(msg, false, clientPassword, "mykeyid", 567);
        assertNotNull("Protecting PKIMessage failed", req);
        hmac.verifyOrExtract(req, null);
        assertNotNull("HMAC returned null password.", hmac.getAuthenticationString());
        assertEquals("HMAC returned the wrong password", clientPassword, hmac.getAuthenticationString());
    } finally {
        this.endEntityManagementSession.deleteUser(ADMIN, clientUsername);
    }
}

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

License:Open Source License

@Test
public void test15CrmfReqClientModeRegToken() throws Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "-");
    this.cmpConfiguration.setRAMode(ALIAS, false);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    final String clientUsername = "clientTestUser";
    final X500Name clientDN = new X500Name("CN=" + clientUsername + ",C=SE");
    final String clientPassword = "foo123client";
    try {/*from   w w w  .j a v  a  2s  .c  o m*/
        this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, clientUsername, ReasonFlags.unused);
    } catch (Exception e) {// do nothing
    }
    createUser(clientUsername, clientDN.toString(), "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE,
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    try {
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

        PKIMessage msg = genCertReq(issuerDN, clientDN, keys, this.cacert, this.nonce, this.transid, false,
                null, null, null, null, null, null);
        assertNotNull("Generating CrmfRequest failed.", msg);
        PKIMessage req = protectPKIMessage(msg, false, clientPassword, "mykeyid", 567);
        assertNotNull("Protecting PKIMessage with HMACPbe failed.", req);

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, clientDN, this.cacert,
                req.getHeader().getSenderNonce().getOctets(), req.getHeader().getTransactionID().getOctets(),
                true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        Certificate cert1 = checkCmpCertRepMessage(clientDN, this.cacert, resp,
                ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
        assertNotNull("Crmf request did not return a certificate", cert1);
    } finally {
        this.endEntityManagementSession.deleteUser(ADMIN, clientUsername);
    }
}

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

License:Open Source License

@Test
public void test16CrmfReqClientModeMultipleModules() throws Exception {
    String authmodules = CmpConfiguration.AUTHMODULE_HMAC + ";" + CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD;

    this.cmpConfiguration.setAuthenticationModule(ALIAS, authmodules);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "foo123hmac;-");
    this.cmpConfiguration.setRAMode(ALIAS, false);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    final String clientUsername = "clientTestUser";
    final X500Name clientDN = new X500Name("CN=" + clientUsername + ",C=SE");

    createUser(clientUsername, clientDN.toString(), "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE,
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    try {//  w  ww.  ja  v a2  s  .  c  o m
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

        PKIMessage msg = genCertReq(issuerDN, clientDN, keys, this.cacert, this.nonce, this.transid, false,
                null, null, null, null, null, null);
        assertNotNull("Generating CrmfRequest failed.", msg);

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(msg);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, clientDN, this.cacert,
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
        Certificate cert1 = checkCmpCertRepMessage(clientDN, this.cacert, resp,
                ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
        assertNotNull("Crmf request did not return a certificate", cert1);

        VerifyPKIMessage verifier = new VerifyPKIMessage(this.caSession.getCAInfo(ADMIN, this.caid), ALIAS,
                ADMIN, this.caSession, this.eeAccessSession, this.certificateStoreSession,
                this.authorizationSession, this.endEntityProfileSession, null, this.endEntityManagementSession,
                this.cmpConfiguration);

        ICMPAuthenticationModule authmodule = verifier.getUsedAuthenticationModule(msg, null, false);
        assertEquals(CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD, authmodule.getName());
    } finally {
        this.endEntityManagementSession.deleteUser(ADMIN, clientUsername);
    }
}

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

License:Open Source License

@Test
public void test17HMACCrmfReqClientModeHMACInvalidPassword() throws Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_HMAC);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "foo123client");
    this.cmpConfiguration.setRAMode(ALIAS, false);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    final String clientUsername = "clientTestUser";
    final X500Name clientDN = new X500Name("CN=" + clientUsername + ",C=SE");
    String clientPassword = "foo123client";
    try {/*from w w w .  j a  v  a  2  s.  c  o m*/
        this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, clientUsername, ReasonFlags.unused);
    } catch (Exception e) {//do nothing
    }
    createUser(clientUsername, clientDN.toString(), "foo123ee", true, this.caid,
            SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    try {
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

        PKIMessage msg = genCertReq(issuerDN, clientDN, keys, this.cacert, this.nonce, this.transid, false,
                null, null, null, null, null, null);
        assertNotNull("Generating CrmfRequest failed.", msg);
        PKIMessage req = protectPKIMessage(msg, false, clientPassword, "mykeyid", 567);
        assertNotNull("Protecting PKIMessage with HMACPbe failed.", req);

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, clientDN, this.cacert,
                req.getHeader().getSenderNonce().getOctets(), req.getHeader().getTransactionID().getOctets(),
                false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());

        ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        try {
            PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
            assertNotNull(respObject);

            PKIBody body = respObject.getBody();
            assertEquals(23, body.getType());
            ErrorMsgContent err = (ErrorMsgContent) body.getContent();
            String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
            String expectedErrMsg = "Authentication failed for message. clientTestUser.";
            assertEquals(expectedErrMsg, errMsg);
        } finally {
            inputStream.close();
        }
    } finally {
        this.endEntityManagementSession.deleteUser(ADMIN, clientUsername);
    }
}

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

License:Open Source License

/** Test CMP initial request against EJBCA CMP in client mode (operationmode=normal) using End Entity certificate signature authentication, 
 * i.e. the request is signed by a certificate of the same end entity making the request, and this signature is used for authenticating the end entity.
 * Test://from  www.j a  v a2  s.c o  m
 * - Request signed by a fake certificate, i.e. one that is not in the database (FAIL)
 * - Request signed by a certificate that beloongs to another user (FAIL)
 * - Request signed by a proper certificate but where user status is not NEW (FAIL)
 * - Request signed by a proper, but revoked certificate (FAIL)
 * - A working request signed by a proper, unrevoked certificate and user status is NEW (SUCCESS)
 * 
 * @throws Exception on some errors
 */
@Test
public void test18CrmfReqClientModeEESignature() throws Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "-");
    this.cmpConfiguration.setRAMode(ALIAS, false);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    final X500Name testUserDN = new X500Name("CN=cmptestuser16,C=SE");
    final String testUsername = "cmptestuser16";
    final String otherUserDN = "CN=cmptestotheruser16,C=SE";
    final String otherUsername = "cmptestotheruser16";
    String fingerprint = null;
    String fingerprint2 = null;
    String fingerprint3 = null;
    try {
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        KeyPair fakeKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        createUser(testUsername, testUserDN.toString(), "foo123", true, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        // A real certificate that can be used to sign the message
        Certificate cert = this.signSession.createCertificate(ADMIN, testUsername, "foo123",
                new PublicKeyWrapper(keys.getPublic()));
        fingerprint = CertTools.getFingerprintAsString(cert);
        // A fake certificate that should not be valid
        Certificate fakeCert = CertTools.genSelfCert(testUserDN.toString(), 30, null, fakeKeys.getPrivate(),
                fakeKeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false);

        // Step 1 sign with fake certificate, should not be valid as end entity authentication
        {
            AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
            PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid,
                    false, null, null, null, null, pAlg, null);
            assertNotNull("Generating CrmfRequest failed.", msg);
            CMPCertificate[] extraCert = getCMPCert(fakeCert);
            msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, fakeKeys.getPrivate(),
                    pAlg.getAlgorithm().getId(), "BC");
            assertNotNull(msg);
            //******************************************''''''
            final Signature sig = Signature
                    .getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC");
            sig.initVerify(fakeCert.getPublicKey());
            sig.update(CmpMessageHelper.getProtectedBytes(msg));
            boolean verified = sig.verify(msg.getProtection().getBytes());
            assertTrue("Signing the message failed.", verified);
            //***************************************************

            final ByteArrayOutputStream bao = new ByteArrayOutputStream();
            final DEROutputStream out = new DEROutputStream(bao);
            out.writeObject(msg);
            final byte[] ba = bao.toByteArray();
            // Send request and receive response
            final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
            // This should have failed
            checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert,
                    msg.getHeader().getSenderNonce().getOctets(),
                    msg.getHeader().getTransactionID().getOctets(), false, null,
                    PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
            ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
            PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
            try {
                assertNotNull(respObject);
                PKIBody body = respObject.getBody();
                assertEquals(23, body.getType());
                ErrorMsgContent err = (ErrorMsgContent) body.getContent();
                String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
                String expectedErrMsg = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database.";
                assertEquals(expectedErrMsg, errMsg);
            } finally {
                inputStream.close();
            }
        }
        // Step 2, sign the request with a certificate that does not belong to the user
        {
            KeyPair otherKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
            createUser(otherUsername, otherUserDN, "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE,
                    CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
            // A real certificate that can be used to sign the message
            Certificate othercert = this.signSession.createCertificate(ADMIN, otherUsername, "foo123",
                    new PublicKeyWrapper(otherKeys.getPublic()));
            fingerprint2 = CertTools.getFingerprintAsString(cert);
            AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
            PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid,
                    false, null, null, null, null, pAlg, null);
            assertNotNull("Generating CrmfRequest failed.", msg);
            CMPCertificate[] extraCert = getCMPCert(othercert);
            msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, otherKeys.getPrivate(),
                    pAlg.getAlgorithm().getId(), "BC");
            assertNotNull(msg);
            //******************************************''''''
            final Signature sig = Signature
                    .getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC");
            sig.initVerify(othercert.getPublicKey());
            sig.update(CmpMessageHelper.getProtectedBytes(msg));
            boolean verified = sig.verify(msg.getProtection().getBytes());
            assertTrue("Signing the message failed.", verified);
            //***************************************************

            final ByteArrayOutputStream bao = new ByteArrayOutputStream();
            final DEROutputStream out = new DEROutputStream(bao);
            out.writeObject(msg);
            final byte[] ba = bao.toByteArray();
            // Send request and receive response
            final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
            // This should have failed
            checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert,
                    msg.getHeader().getSenderNonce().getOctets(),
                    msg.getHeader().getTransactionID().getOctets(), false, null,
                    PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
            ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
            try {
                PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
                assertNotNull(respObject);
                PKIBody body = respObject.getBody();
                assertEquals(23, body.getType());
                ErrorMsgContent err = (ErrorMsgContent) body.getContent();
                String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
                String expectedErrMsg = "The End Entity certificate attached to the PKIMessage in the extraCert field does not belong to user '"
                        + testUsername + "'";
                assertEquals(expectedErrMsg, errMsg);
            } finally {
                inputStream.close();
            }
        }

        // Step 3 sign with the real certificate, but user status is not NEW
        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false,
                null, null, null, null, pAlg, null);
        assertNotNull("Generating CrmfRequest failed.", msg);
        CMPCertificate[] extraCert = getCMPCert(cert);
        msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, keys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull(msg);
        //******************************************''''''
        final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
                "BC");
        sig.initVerify(cert.getPublicKey());
        sig.update(CmpMessageHelper.getProtectedBytes(msg));
        boolean verified = sig.verify(msg.getProtection().getBytes());
        assertTrue("Signing the message failed.", verified);
        //***************************************************

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(msg);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert,
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        // This should have failed
        ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        try {
            PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
            assertNotNull(respObject);
            PKIBody body = respObject.getBody();
            assertEquals(23, body.getType());
            ErrorMsgContent err = (ErrorMsgContent) body.getContent();
            String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
            String expectedErrMsg = "Got request with status GENERATED (40), NEW, FAILED or INPROCESS required: cmptestuser16.";
            assertEquals(expectedErrMsg, errMsg);

            // Step 4 now set status to NEW, and a clear text password, then it should finally work
            createUser(testUsername, testUserDN.toString(), "randompasswordhere", true, this.caid,
                    SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
            // Send request and receive response
            final byte[] resp2 = sendCmpHttp(ba, 200, ALIAS);
            CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
            Certificate cert2 = checkCmpCertRepMessage(testUserDN, this.cacert, resp2,
                    ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
            assertNotNull("CrmfRequest did not return a certificate", cert2);
            fingerprint3 = CertTools.getFingerprintAsString(cert2);

            // Step 5, revoke the certificate and try again
            {
                this.certificateStoreSession.setRevokeStatus(ADMIN, cert,
                        RevokedCertInfo.REVOCATION_REASON_CESSATIONOFOPERATION, null);
                final byte[] resp3 = sendCmpHttp(ba, 200, ALIAS);
                // This should have failed
                checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert,
                        msg.getHeader().getSenderNonce().getOctets(),
                        msg.getHeader().getTransactionID().getOctets(), false, null,
                        PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
                ASN1InputStream inputStream3 = new ASN1InputStream(new ByteArrayInputStream(resp3));
                try {
                    PKIMessage respObject3 = PKIMessage.getInstance(inputStream3.readObject());
                    assertNotNull(respObject);
                    PKIBody body3 = respObject3.getBody();
                    assertEquals(23, body3.getType());
                    err = (ErrorMsgContent) body3.getContent();
                    String errMsg3 = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
                    String expectedErrMsg3 = "The certificate attached to the PKIMessage in the extraCert field is not active.";
                    assertEquals(expectedErrMsg3, errMsg3);
                } finally {
                    inputStream3.close();
                }
            }
        } finally {
            inputStream.close();
        }

    } finally {
        try {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused);
        } catch (Exception e) {// do nothing
        }

        try {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, otherUsername, ReasonFlags.unused);
        } catch (Exception e) {// do nothing
        }

        this.internalCertStoreSession.removeCertificate(fingerprint);
        this.internalCertStoreSession.removeCertificate(fingerprint2);
        this.internalCertStoreSession.removeCertificate(fingerprint3);
    }
}

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

License:Open Source License

/**
 * Tests that EndEntityAuthentication module can be successfully used in client mode when the end entity's password is not stored in clear text.
 * /*  w  w  w.  j  av a2  s . com*/
 * @throws Exception
 */
@Test
public void test21CrmfRequestClientModeEECNotClearPassword() throws Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "-");
    this.cmpConfiguration.setRAMode(ALIAS, false);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    final X500Name testUserDN = new X500Name("CN=cmptestuser21,C=SE");
    final String testUsername = "cmptestuser21";
    String fingerprint = null;
    String fingerprint2 = null;
    try {
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);

        createUser(testUsername, testUserDN.toString(), "foo123", false, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        Certificate cert = this.signSession.createCertificate(ADMIN, testUsername, "foo123",
                new PublicKeyWrapper(keys.getPublic()));
        fingerprint = CertTools.getFingerprintAsString(cert);

        //Edit the status of the user to NEW
        createUser(testUsername, testUserDN.toString(), "foo123", false, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false,
                null, null, null, null, pAlg, null);
        assertNotNull("Generating CrmfRequest failed.", msg);
        CMPCertificate[] extraCert = getCMPCert(cert);
        msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, keys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull(msg);
        //******************************************''''''
        final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
                "BC");
        sig.initVerify(cert.getPublicKey());
        sig.update(CmpMessageHelper.getProtectedBytes(msg));
        boolean verified = sig.verify(msg.getProtection().getBytes());
        assertTrue("Signing the message failed.", verified);
        //***************************************************

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(msg);
        final byte[] ba = bao.toByteArray();

        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
        Certificate cert2 = checkCmpCertRepMessage(testUserDN, this.cacert, resp,
                ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
        assertNotNull("CrmfRequest did not return a certificate", cert2);
        fingerprint2 = CertTools.getFingerprintAsString(cert2);
    } finally {
        try {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused);
        } catch (Exception e) {// do nothing
        }

        this.internalCertStoreSession.removeCertificate(fingerprint);
        this.internalCertStoreSession.removeCertificate(fingerprint2);
    }
}

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

License:Open Source License

protected static void checkCmpPKIErrorMessage(byte[] retMsg, String sender, X500Name recipient, int errorCode,
        String errorMsg) throws IOException {
    ////w w  w  . j  a v  a 2s . c om
    // Parse response message
    //
    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);
    PKIHeader header = respObject.getHeader();
    assertEquals(header.getSender().getTagNo(), 4);
    {
        final X500Name name = X500Name.getInstance(header.getSender().getName());
        assertEquals(name.toString(), sender);
    }
    {
        final X500Name name = X500Name.getInstance(header.getRecipient().getName());
        assertArrayEquals(name.getEncoded(), recipient.getEncoded());
    }

    PKIBody body = respObject.getBody();
    int tag = body.getType();
    assertEquals(tag, 23);
    ErrorMsgContent n = (ErrorMsgContent) body.getContent();
    assertNotNull(n);
    PKIStatusInfo info = n.getPKIStatusInfo();
    assertNotNull(info);
    BigInteger i = info.getStatus();
    assertEquals(i.intValue(), 2);
    DERBitString b = info.getFailInfo();
    assertEquals("Return wrong error code.", errorCode, b.intValue());
    if (errorMsg != null) {
        PKIFreeText freeText = info.getStatusString();
        DERUTF8String utf = freeText.getStringAt(0);
        assertEquals(errorMsg, utf.getString());
    }
}

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

License:Open Source License

@Override
/*//www . j av  a 2s .c o  m
 * Handles the CMP message
 * 
 * Expects the CMP message to be a CrmfRequestMessage. The message is authenticated using 
 * EndEntityCertificateAuthenticationModule in client mode. It used the attached certificate 
 * to find then End Entity which this certificate belongs to and requesting for a new certificate 
 * to be generated. 
 * 
 * If automatic update of the key (same as certificate renewal), the end entity's status is set to 
 * 'NEW' before processing the request. If using the same old keys in the new certificate is not allowed, 
 * a check is made to insure the the key specified in the request is not the same as the key of the attached 
 * certificate.
 * 
 * The KeyUpdateRequet is processed only in client mode.
 */
public ResponseMessage handleMessage(final BaseCmpMessage msg, boolean authenticated) {
    if (LOG.isTraceEnabled()) {
        LOG.trace(">handleMessage");
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("CMP running on RA mode: " + this.cmpConfiguration.getRAMode(this.confAlias));
    }

    ResponseMessage resp = null;
    try {

        CrmfRequestMessage crmfreq = null;
        if (msg instanceof CrmfRequestMessage) {
            crmfreq = (CrmfRequestMessage) msg;
            crmfreq.getMessage();

            EndEntityCertificateAuthenticationModule eecmodule = null;
            X509Certificate oldCert = null;

            // Find the subjectDN to look for
            String subjectDN = null;
            String issuerDN = null;
            if (this.cmpConfiguration.getRAMode(this.confAlias)) {

                // Check that EndEntityCertificate authentication module is set
                if (!cmpConfiguration.isInAuthModule(confAlias,
                        CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE)) {
                    String errmsg = "EndEnityCertificate authentication module is not configured. For a KeyUpdate request to be authentication in RA mode, EndEntityCertificate "
                            + "authentication module has to be set and configured";
                    LOG.info(errmsg);
                    return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                            FailInfo.BAD_REQUEST, errmsg);
                }

                // Check PKIMessage authentication
                String authparameter = cmpConfiguration.getAuthenticationParameter(
                        CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE, confAlias);
                eecmodule = new EndEntityCertificateAuthenticationModule(admin, authparameter, confAlias,
                        cmpConfiguration, authenticated, caSession, certStoreSession, authorizationSession,
                        endEntityProfileSession, endEntityAccessSession, authenticationProviderSession,
                        endEntityManagementSession);
                if (!eecmodule.verifyOrExtract(crmfreq.getPKIMessage(), null)) {
                    LOG.info(eecmodule.getErrorMessage());
                    return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                            FailInfo.BAD_REQUEST, eecmodule.getErrorMessage());
                } else {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("The CMP KeyUpdate request for SubjectDN '" + crmfreq.getSubjectDN()
                                + "' was verified successfully");
                    }
                }
                oldCert = (X509Certificate) eecmodule.getExtraCert();

                CertReqMessages kur = (CertReqMessages) crmfreq.getPKIMessage().getBody().getContent();
                CertReqMsg certmsg;
                try {
                    certmsg = kur.toCertReqMsgArray()[0];
                } catch (Exception e) {
                    LOG.debug(
                            "Could not parse the revocation request. Trying to parse it as novosec generated message.");
                    certmsg = CmpMessageHelper.getNovosecCertReqMsg(kur);
                    LOG.debug("Succeeded in parsing the novosec generated request.");
                }
                X500Name dn = certmsg.getCertReq().getCertTemplate().getSubject();
                if (dn != null) {
                    subjectDN = dn.toString();
                }
                dn = certmsg.getCertReq().getCertTemplate().getIssuer();
                if (dn != null) {
                    issuerDN = dn.toString();
                }
            } else { // client mode

                eecmodule = new EndEntityCertificateAuthenticationModule(admin, null, confAlias,
                        cmpConfiguration, authenticated, caSession, certStoreSession, authorizationSession,
                        endEntityProfileSession, endEntityAccessSession, authenticationProviderSession,
                        endEntityManagementSession);
                if (!eecmodule.verifyOrExtract(crmfreq.getPKIMessage(), null)) {
                    LOG.info(eecmodule.getErrorMessage());
                    return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                            FailInfo.BAD_REQUEST, eecmodule.getErrorMessage());
                }
                oldCert = (X509Certificate) eecmodule.getExtraCert();

                subjectDN = oldCert.getSubjectDN().toString();
                issuerDN = oldCert.getIssuerDN().toString();
            }

            if (subjectDN == null) {
                final String errMsg = "Cannot find a SubjectDN in the request";
                LOG.info(errMsg);
                return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                        FailInfo.BAD_REQUEST, errMsg);
            }

            // Find the end entity that the certificate belongs to                
            if (LOG.isDebugEnabled()) {
                LOG.debug("Looking for an end entity with subjectDN: " + subjectDN);
            }
            EndEntityInformation userdata = null;
            if (issuerDN == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("The CMP KeyUpdateRequest did not specify an issuer");
                }
                List<EndEntityInformation> userdataList = endEntityAccessSession.findUserBySubjectDN(admin,
                        subjectDN);
                if (userdataList.size() > 0) {
                    userdata = userdataList.get(0);
                }
                if (userdataList.size() > 1) {
                    LOG.warn("Multiple end entities with subject DN " + subjectDN
                            + " were found. This may lead to unexpected behavior.");
                }
            } else {
                List<EndEntityInformation> userdataList = endEntityAccessSession
                        .findUserBySubjectAndIssuerDN(admin, subjectDN, issuerDN);
                if (userdataList.size() > 0) {
                    userdata = userdataList.get(0);
                }
                if (userdataList.size() > 1) {
                    LOG.warn("Multiple end entities with subject DN " + subjectDN + " and issuer DN" + issuerDN
                            + " were found. This may lead to unexpected behavior.");
                }
            }

            if (userdata == null) {
                final String errMsg = INTRES.getLocalizedMessage("cmp.infonouserfordn", subjectDN);
                LOG.info(errMsg);
                return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                        FailInfo.BAD_MESSAGE_CHECK, errMsg);
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("Found user '" + userdata.getUsername() + "'");
            }

            // The password that should be used to obtain the new certificate
            String password = StringUtils.isNotEmpty(userdata.getPassword()) ? userdata.getPassword()
                    : eecmodule.getAuthenticationString();

            // Set the appropriate parameters in the end entity
            userdata.setPassword(password);
            endEntityManagementSession.changeUser(admin, userdata, true);
            if (this.cmpConfiguration.getKurAllowAutomaticUpdate(this.confAlias)) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Setting the end entity status to 'NEW'. Username: " + userdata.getUsername());
                }

                endEntityManagementSession.setUserStatus(admin, userdata.getUsername(),
                        EndEntityConstants.STATUS_NEW);
            }

            // Set the appropriate parameters in the request
            crmfreq.setUsername(userdata.getUsername());
            crmfreq.setPassword(password);
            if (crmfreq.getHeader().getProtectionAlg() != null) {
                crmfreq.setPreferredDigestAlg(AlgorithmTools
                        .getDigestFromSigAlg(crmfreq.getHeader().getProtectionAlg().getAlgorithm().getId()));
            }

            // Check the public key, whether it is allowed to use the old keys or not.
            if (!this.cmpConfiguration.getKurAllowSameKey(this.confAlias)) {
                PublicKey certPublicKey = oldCert.getPublicKey();
                PublicKey requestPublicKey = crmfreq.getRequestPublicKey();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Not allowing update with same key, comparing keys.");
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("OldKey: " + certPublicKey.toString());
                        LOG.trace("NewKey: " + requestPublicKey.toString());
                    }
                }
                if (certPublicKey.equals(requestPublicKey)) {
                    final String errMsg = "Invalid key. The public key in the KeyUpdateRequest is the same as the public key in the existing end entity certificate";
                    LOG.info(errMsg);
                    return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                            FailInfo.BAD_MESSAGE_CHECK, errMsg);
                }
            }

            // Process the request
            resp = signSession.createCertificate(admin, crmfreq,
                    org.ejbca.core.protocol.cmp.CmpResponseMessage.class, userdata);

            if (resp == null) {
                final String errMsg = INTRES.getLocalizedMessage("cmp.errornullresp");
                LOG.info(errMsg);
                resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                        FailInfo.BAD_MESSAGE_CHECK, errMsg);
            }
        } else {
            final String errMsg = INTRES.getLocalizedMessage("cmp.errornocmrfreq");
            LOG.info(errMsg);
            resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE,
                    FailInfo.BAD_MESSAGE_CHECK, errMsg);
        }

    } catch (AuthorizationDeniedException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (CADoesntExistsException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (UserDoesntFullfillEndEntityProfile e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (WaitingForApprovalException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (EjbcaException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (FinderException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (CesecoreException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (InvalidKeyException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info("Error while reading the public key of the extraCert attached to the CMP request");
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info("Error while reading the public key of the extraCert attached to the CMP request");
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (NoSuchProviderException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info("Error while reading the public key of the extraCert attached to the CMP request");
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    } catch (CertificateExtensionException e) {
        final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage());
        LOG.info(errMsg, e);
        resp = CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST,
                e.getMessage());
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("<handleMessage");
    }
    return resp;
}

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

License:Open Source License

/**
 * Sends a KeyUpdateRequest concerning a certificate that does not exist in the database. A CMP error message is expected and no certificate renewal.
 * /*from w  w w .  j ava2s . co  m*/
 * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal)
 * - Pre-configuration: Sets cmp.allowautomaticrenewal to 'true' and tests that the resetting of configuration has worked.
 * - Pre-configuration: Sets cmp.allowupdatewithsamekey to 'true'
 * - Generates a self-signed certificate, fakecert
 * - Generates a CMP KeyUpdate Request and tests that such request has been created.
 * - Signs the CMP request using fakecert and attaches fakecert to the CMP request. Tests that the CMP request is still not null
 * - Sends the request using HTTP and receives an response.
 * - Examines the response:
 *       - Checks that the response is not empty or null
 *       - Checks that the protection algorithm is sha1WithRSAEncryption
 *       - Checks that the signer is the expected CA
 *       - Verifies the response signature
 *       - Checks that the response's senderNonce is 16 bytes long
 *       - Checks that the request's senderNonce is the same as the response's recipientNonce
 *       - Checks that the request and the response has the same transactionID
 *       - Parses the response and checks that the parsing did not result in a 'null'
 *       - Checks that the CMP response message tag number is '23', indicating a CMP error message
 *       - Checks that the CMP response message contain the expected error details text
 * 
 * @throws Exception
 */
@Test
public void test04UpdateKeyWithFakeCert() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">test04UpdateKeyWithFakeCert");
    }

    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //--------------- create the user and issue his first certificate -----------------
    final String fakeUsername = "fakeuser";
    final X500Name fakeUserDN = new X500Name("CN=" + fakeUsername + ",C=SE");
    createUser(fakeUsername, fakeUserDN.toString(), "foo123");

    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    Certificate fakeCert = CertTools.genSelfCert(fakeUserDN.toString(), 30, null, keys.getPrivate(),
            keys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false);
    assertNotNull("Failed to create a test certificate", fakeCert);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);

    // Sending a request with a certificate that neither it nor the issuer CA is in the database
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, null, null,
            pAlg, new DEROctetString(this.nonce));
    assertNotNull("Failed to generate a CMP renewal request", req);

    CMPCertificate[] extraCert = getCMPCert(fakeCert);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    PKIBody body = respObject.getBody();
    assertEquals(23, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    String expectedErrMsg = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database.";
    assertEquals(expectedErrMsg, errMsg);

    // sending another renewal request with a certificate issued by an existing CA but the certificate itself is not in the database        
    // A certificate, not in the database, issued by TestCA
    byte[] fakecertBytes = Base64.decode(("MIIB6TCCAVKgAwIBAgIIIKF3bEBbbyQwDQYJKoZIhvcNAQELBQAwETEPMA0GA1UE"
            + "AwwGVGVzdENBMB4XDTEzMDMxMjExMTcyMVoXDTEzMDMyMjExMjcyMFowIDERMA8G"
            + "A1UEAwwIZmFrZXVzZXIxCzAJBgNVBAYTAlNFMFwwDQYJKoZIhvcNAQEBBQADSwAw"
            + "SAJBAKZlXrI3TwziiDK9/E1V4n6PCXhpRERSLWPEpRvRPWfpvazpq7R2UZZRq5i2"
            + "hrqKDbfLdAouh2J7AIlUZG3cdJECAwEAAaN/MH0wHQYDVR0OBBYEFCb2tsZTXOh7"
            + "FjjVXpSxkJ79P3tJMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAURmtK3gFt81Bp"
            + "3z+YZuzBm65Ja6IwDgYDVR0PAQH/BAQDAgXgMB0GA1UdJQQWMBQGCCsGAQUFBwMC"
            + "BggrBgEFBQcDBDANBgkqhkiG9w0BAQsFAAOBgQAmclw6cwuQkiPSN4bHOP5S7bdU"
            + "+UKXLIkk1L84q0WQfblNzYkcDXMsxwJ1dv2Yd/dxIjtVjrhVIUrRMA70jtWs31CH"
            + "t9ofdgncIdtzZo49mLRQDwhTCApoLf0BCNb2rWpzCPWQTa97y0u5T65m7DAkBTV/" + "JAkFQIZCLSAci++qPA==")
                    .getBytes());
    fakeCert = CertTools.getCertfromByteArray(fakecertBytes);

    req = genRenewalReq(fakeUserDN, this.cacert, this.nonce, this.transid, keys, false, null, null, pAlg,
            new DEROctetString(this.nonce));
    assertNotNull("Failed to generate a CMP renewal request", req);

    extraCert = getCMPCert(fakeCert);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());

    respObject = null;
    asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    body = respObject.getBody();
    assertEquals(23, body.getType());
    err = (ErrorMsgContent) body.getContent();
    errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    expectedErrMsg = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database.";
    assertEquals(expectedErrMsg, errMsg);

    if (log.isTraceEnabled()) {
        log.trace("<test04UpdateKeyWithFakeCert");
    }

}