Example usage for org.bouncycastle.asn1.cmp ErrorMsgContent getPKIStatusInfo

List of usage examples for org.bouncycastle.asn1.cmp ErrorMsgContent getPKIStatusInfo

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cmp ErrorMsgContent getPKIStatusInfo.

Prototype

public PKIStatusInfo getPKIStatusInfo() 

Source Link

Usage

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

License:Open Source License

@Test
public void test07EERevReqWithUnknownCA()
        throws NoSuchAlgorithmException, EjbcaException, IOException, Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    Collection<Certificate> certs = this.certificateStoreSession
            .findCertificatesBySubjectAndIssuer(USER_DN.toString(), issuerDN);
    log.debug("Found " + certs.size() + " certificates for userDN \"" + USER_DN + "\"");
    Certificate cert = null, tmp = null;
    Iterator<Certificate> itr = certs.iterator();
    while (itr.hasNext()) {
        tmp = itr.next();//from  www.ja v a2s  .co m
        if (!this.certificateStoreSession.isRevoked(issuerDN, CertTools.getSerialNumber(tmp))) {
            cert = tmp;
            break;
        }
    }
    final String userName = "cmprevuser1";
    if (cert == null) {
        createUser(userName, "CN=" + userName + ",C=SE", "foo123", true, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
        cert = this.signSession.createCertificate(ADMIN, "cmprevuser1", "foo123",
                new PublicKeyWrapper(admkeys.getPublic()));
    }
    try {
        assertNotNull("No certificate to revoke.", cert);

        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genRevReq("CN=cmprevuser1,C=SE", USER_DN, CertTools.getSerialNumber(cert), cert,
                this.nonce, this.transid, false, pAlg, null);
        assertNotNull("Generating CrmfRequest failed.", msg);

        String adminName = "cmpTestAdmin";
        KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
        AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE",
                this.caid, SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        Certificate admCert = getCertFromCredentials(adminToken);
        CMPCertificate[] extraCert = getCMPCert(admCert);
        msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull(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, "CN=cmprevuser1,C=SE", USER_DN, this.cacert,
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revStatus = checkRevokeStatus(issuerDN, CertTools.getSerialNumber(cert));
        assertEquals("Revocation request succeeded", RevokedCertInfo.NOT_REVOKED, revStatus);
        ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        try {
            PKIMessage respObject = PKIMessage.getInstance(asn1InputStream.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 = "CA with DN 'C=SE,CN=cmprevuser1' is unknown";
            assertEquals(expectedErrMsg, errMsg);
            removeAuthenticationToken(adminToken, admCert, adminName);
        } finally {
            asn1InputStream.close();
        }
    } finally {
        this.endEntityManagementSession.deleteUser(ADMIN, userName);
    }
}

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

License:Open Source License

@Test
public void test10HMACCrmfReqWrongAuthenticationModule() throws Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_DN_PART_PWD);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "UID");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

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

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

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);/*from ww w .j  a v  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, USER_DN, 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);

        final PKIBody body = respObject.getBody();
        assertEquals(23, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        final String expectedErrMsg = "The authentication module 'DnPartPwd' cannot be used in RA mode";
        assertEquals(expectedErrMsg, errMsg);
    } finally {
        inputStream.close();
    }
}

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

License:Open Source License

@Test
public void test11EECrmfCheckAdminAuthorization()
        throws NoSuchAlgorithmException, EjbcaException, IOException, Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

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

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null,
            null, null, null, pAlg, null);
    assertNotNull("Generating CrmfRequest failed.", msg);

    String adminName = "cmpTestUnauthorizedAdmin";
    createUser(adminName, "CN=" + adminName + ",C=SE", "foo123", true, this.caid,
            SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    KeyPair admkeys = KeyTools.genKeys("512", "RSA");
    Certificate admCert = this.signSession.createCertificate(ADMIN, adminName, "foo123",
            new PublicKeyWrapper(admkeys.getPublic()));
    CMPCertificate[] extraCert = getCMPCert(admCert);
    msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(msg);//  w w  w.ja  v a2 s .co m

    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, USER_DN, 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();
        assertEquals("'CN=cmpTestUnauthorizedAdmin,C=SE' is not an authorized administrator.", errMsg);
    } finally {
        inputStream.close();
    }

}

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

License:Open Source License

@Test
public void test12EECrmfNotCheckAdmin()
        throws NoSuchAlgorithmException, EjbcaException, IOException, Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.cmpConfiguration.setOmitVerificationsInECC(ALIAS, true);
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

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

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null,
            null, null, null, pAlg, new DEROctetString(this.nonce));
    assertNotNull("Generating CrmfRequest failed.", msg);

    String adminName = "cmpTestAdmin";
    KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
    AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE",
            this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    Certificate admCert = getCertFromCredentials(adminToken);
    CMPCertificate[] extraCert = getCMPCert(admCert);
    msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(msg);// w w  w.  jav  a2 s . c  o  m

    //********************************************
    final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
            "BC");
    sig.initVerify(admCert.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, USER_DN, 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 = "Omitting some verifications can only be accepted in RA mode and when the CMP request has already been authenticated, for example, through the use of NestedMessageContent";
        assertEquals(expectedErrmsg, errMsg);
    } finally {
        inputStream.close();
    }
    removeAuthenticationToken(adminToken, admCert, adminName);

}

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   ww w. ja va  2  s  .com
        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:/* w w  w . j  av a  2s. 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

/**
 * Test the error message returned when CMP request missing a PBE protection in RA mode (operationmode=ra) and HMAC authentication is configured. 
 * //from w w  w. ja  v a  2s.  c om
 * @throws Exception on some errors
 */
@Test
public void test19NoHMACAuthentication() throws Exception {

    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_HMAC);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "foo123");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

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

    PKIMessage msg = genCertReq(issuerDN, USER_DN, 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, USER_DN, 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);

        final PKIBody body = respObject.getBody();
        assertEquals(23, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        final String expectedErrMsg = "PKI Message is not athenticated properly. No HMAC protection was found.";
        assertEquals(expectedErrMsg, errMsg);
    } finally {
        inputStream.close();
    }
}

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

License:Open Source License

/**
 * Test the error message returned when CMP request missing a signature in RA mode (operationmode=ra) and EndEntityCertificate authentication is configured. 
 * //w  w w  .j  ava  2  s  .  c  o  m
 * @throws Exception on some errors
 */
@Test
public void test20NoEECAuthentication() throws Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.cmpConfiguration.setRAMode(ALIAS, false);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

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

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null,
            null, null, null, pAlg, new DEROctetString(this.nonce));
    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, USER_DN, 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 = "PKI Message is not athenticated properly. No PKI protection is found.";
        assertEquals(expectedErrMsg, errMsg);
    } finally {
        inputStream.close();
    }
}

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

License:Open Source License

/**
 * Sending a Crmf Request in RA mode. The request is authenticated using HMAC and is expected to contain the EndEntityProfile 'EMPTY' in the KeyId field.
 * The request should fail because specifying 'EMPTY' or 'ENDUSER' as the KeyId is not allowed in combination with RA mode and HMAC authentication module 
 * /*from  w w w  .  j  a v a 2  s  .c  o  m*/
 * The test is only done for HMAC and not EndEntityCertificate because in the later, the use of profiles can be restricted through Administrator privileges.
 * Other authentication modules are not used in RA mode
 * 
 * @throws Exception
 */
@Test
public void test24HMACUnacceptedKeyId() throws Exception {

    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_HMAC);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "foo123hmac");
    this.cmpConfiguration.setRAEEProfile(ALIAS, "KeyId");
    this.cmpConfiguration.setRACertProfile(ALIAS, "ProfileDefault");
    this.cmpConfiguration.setRACAName(ALIAS, "TestCA");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

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

    PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null,
            null, null, null, null, null);
    assertNotNull("Generating CrmfRequest failed.", msg);
    PKIMessage req = protectPKIMessage(msg, false, "foo123hmac", "EMPTY", 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, USER_DN, 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);

        final PKIBody body = respObject.getBody();
        assertEquals(23, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        final String expectedErrMsg = "Unaccepted KeyId 'EMPTY' in CMP request";
        assertEquals(expectedErrMsg, errMsg);
    } finally {
        inputStream.close();
    }
}

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

License:Open Source License

/**
 * Sends a CMP request with the alias requestAlias in the URL and expects a CMP error message 
 * that extractedAlias does not  exist./*from  w ww.j  a  v a  2 s. c o  m*/
 * 
 * @param requestAlias the alias that is  specified in the URL
 * @param extractedAlias the alias that EJBCA will use to handle the CMP request
 * @throws Exception
 */
private void sendCmpRequest(CmpConfiguration cmpconfig, String requestAlias, String extractedAlias)
        throws Exception {

    if (cmpconfig.aliasExists(extractedAlias)) {
        cmpconfig.renameAlias(extractedAlias, "backUpAlias" + extractedAlias + "ForAliasTesting001122334455");
        this.globalConfigurationSession.saveConfiguration(ADMIN, cmpconfig);
    }

    try {
        String urlString = this.httpReqPath + '/' + this.baseResource;
        if (requestAlias != null) {
            urlString += "/" + requestAlias;
        }
        log.info("http URL: " + urlString);
        URL url = new URL(urlString);
        final HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "application/pkixcmp");
        con.connect();
        assertEquals("Unexpected HTTP response code.", 200, con.getResponseCode()); // OK response (will use alias "alias123")

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // This works for small requests, and CMP requests are small enough
        InputStream in = con.getInputStream();
        int b = in.read();
        while (b != -1) {
            baos.write(b);
            b = in.read();
        }
        baos.flush();
        in.close();
        byte[] respBytes = baos.toByteArray();
        assertNotNull(respBytes);
        assertTrue(respBytes.length > 0);

        ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(respBytes));
        PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
        assertNotNull(respObject);

        final PKIBody body = respObject.getBody();
        assertEquals(23, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        final String expectedErrMsg = "Wrong URL. CMP alias '" + extractedAlias + "' does not exist";
        assertEquals(expectedErrMsg, errMsg);
        inputStream.close();
    } finally {
        if (cmpconfig.aliasExists("backUpAlias" + extractedAlias + "ForAliasTesting001122334455")) {
            cmpconfig.renameAlias("backUpAlias" + extractedAlias + "ForAliasTesting001122334455",
                    extractedAlias);
            this.globalConfigurationSession.saveConfiguration(ADMIN, cmpconfig);
        }
    }
}