Example usage for org.bouncycastle.asn1.cmp PKIMessage getHeader

List of usage examples for org.bouncycastle.asn1.cmp PKIMessage getHeader

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cmp PKIMessage getHeader.

Prototype

public PKIHeader getHeader() 

Source Link

Usage

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

/**
 * Test the basic certification request message
 *
 * @throws OperatorCreationException//w w  w  .j a  v a2  s.  c om
 * @throws CertificateEncodingException
 * @throws IOException
 * @throws CRMFException
 * @throws CMPException
 * @throws CMSException
 */
@Test
public void testCertification() throws OperatorCreationException, CertificateEncodingException, IOException,
        CRMFException, CMPException, CMSException, ParseException, PKICMPMessageException,
        NoSuchProviderException, NoSuchAlgorithmException, NoSuchFieldException, IllegalAccessException {
    String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName();

    KeyPair keyPair = new KeyPair(pki.getTestUser1Cert().getPublicKey(), pki.getTestUser1CertPrivateKey());

    PKICMPMessages pkiMessages = new PKICMPMessages();
    pkiMessages.setPkiKeyStore(pkiKeyStoreRA);
    byte[] result = pkiMessages.createCertificateMessageWithLocalKey(distinguishedName, keyPair);

    ASN1InputStream asn1InputStream = new ASN1InputStream(result);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive);

    // Header verification
    Assert.assertEquals(pkiMessage.getHeader().getPvno().getValue(), BigInteger.valueOf(2));
    Assert.assertEquals(pkiKeyStoreRA.getRecipientCertificate().getSubjectDN().getName(),
            pkiMessage.getHeader().getRecipient().getName().toString());
    Assert.assertEquals(pkiKeyStoreRA.getSenderCertificate().getSubjectDN().getName(),
            pkiMessage.getHeader().getSender().getName().toString());
    Assert.assertNotNull(pkiMessage.getHeader().getSenderNonce());
    Assert.assertNotNull(pkiMessage.getHeader().getTransactionID());
    Assert.assertNotNull(pkiMessage.getHeader().getMessageTime().getDate());
    // check the body
    // Check the tests in Bouncycastle for decoding cert request
    Assert.assertEquals(PKIBody.TYPE_CERT_REQ, pkiMessage.getBody().getType());
    CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent())
            .toCertReqMsgArray();
    Assert.assertEquals(BigInteger.ZERO.toString(), certReqMsgs[0].getCertReq().getCertReqId().toString());
    Assert.assertEquals(distinguishedName,
            certReqMsgs[0].getCertReq().getCertTemplate().getSubject().toString());
    Assert.assertArrayEquals(keyPair.getPublic().getEncoded(),
            certReqMsgs[0].getCertReq().getCertTemplate().getPublicKey().getEncoded());
    AttributeTypeAndValue[] attributeTypeAndValue = certReqMsgs[0].getCertReq().getControls()
            .toAttributeTypeAndValueArray();
    Assert.assertEquals(CRMFObjectIdentifiers.id_regCtrl_pkiArchiveOptions, attributeTypeAndValue[0].getType());
    // Check the signature
    GeneralPKIMessage generalPKIMessage = new GeneralPKIMessage(result);
    Assert.assertTrue(generalPKIMessage.hasProtection());
    ProtectedPKIMessage pkiMsg = new ProtectedPKIMessage(generalPKIMessage);
    ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder()
            .setProvider(pkiKeyStoreRA.getProvider())
            .build(pkiKeyStoreRA.getSenderCertificate().getPublicKey());

    Assert.assertTrue(pkiMsg.verify(verifierProvider));
}

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

/**
 * Test certification message with a predefined transactionId
 * @throws OperatorCreationException/*from w  w w . ja va  2s  . c o m*/
 * @throws PKICMPMessageException
 * @throws CertificateEncodingException
 * @throws IOException
 * @throws CRMFException
 * @throws CMPException
 * @throws CMSException
 */
@Test
public void testCertificationWithTransactionId()
        throws OperatorCreationException, PKICMPMessageException, CertificateEncodingException, IOException,
        CRMFException, CMPException, CMSException, NoSuchFieldException, IllegalAccessException {
    String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName();
    byte[] transactionId = { 0x01, 0x02, 0x03, 0x04 };

    PKICMPMessages pkiMessages = new PKICMPMessages();
    pkiMessages.setPkiKeyStore(pkiKeyStoreRA);
    pkiMessages.setTransactionId(transactionId);
    byte[] result = pkiMessages.createCertificateMessageWithRemoteKey(distinguishedName);

    ASN1InputStream asn1InputStream = new ASN1InputStream(result);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive);

    Assert.assertArrayEquals(transactionId, pkiMessage.getHeader().getTransactionID().getOctets());
}

From source file:org.ejbca.core.protocol.cmp.authentication.EndEntityCertificateAuthenticationModule.java

License:Open Source License

@Override
/*/*from  www . j  a v a 2  s.  c o  m*/
 * Verifies the signature of 'msg'. msg should be signed and the signer's certificate should be  
 * attached in msg in the extraCert field.  
 * 
 * When successful, the authentication string is set.
 */
public boolean verifyOrExtract(final PKIMessage msg, final String username) {

    //Check that msg is signed
    if (msg.getProtection() == null) {
        this.errorMessage = "PKI Message is not athenticated properly. No PKI protection is found.";
        return false;
    }

    // Read the extraCert and store it in a local variable
    extraCert = getExtraCert(msg);
    if (extraCert == null) {
        this.errorMessage = "Error while reading the certificate in the extraCert field";
        return false;
    }

    boolean vendormode = impl.isVendorCertificateMode(msg.getBody().getType(), this.confAlias);
    boolean omitVerifications = cmpConfiguration.getOmitVerificationsInEEC(confAlias);
    boolean ramode = cmpConfiguration.getRAMode(confAlias);
    if (log.isDebugEnabled()) {
        log.debug("CMP is operating in RA mode: " + this.cmpConfiguration.getRAMode(this.confAlias));
        log.debug("CMP is operating in Vendor mode: " + vendormode);
        log.debug("CMP message already been authenticated: " + authenticated);
        log.debug("Omitting som verifications: " + omitVerifications);
    }

    //----------------------------------------------------------------------------------------
    // Perform the different checks depending on the configuration and previous authentication
    //----------------------------------------------------------------------------------------

    // Not allowed combinations.
    if (ramode && vendormode) {
        this.errorMessage = "Vendor mode and RA mode cannot be combined";
        return false;
    }
    if (omitVerifications && (!ramode || !authenticated)) {
        this.errorMessage = "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";
        return false;
    }

    // Accepted combinations
    if (omitVerifications && ramode && authenticated) {
        // Do nothing here
        if (log.isDebugEnabled()) {
            log.debug(
                    "Skipping some verification of the extraCert certificate in RA mode and an already authenticated CMP message, tex. through NestedMessageContent");
        }
    } else if (ramode) {

        // Get the CA to use for the authentication
        CAInfo cainfo = getCAInfoByName(authenticationparameter);
        if (cainfo == null)
            return false;

        // Check that extraCert is in the Database
        CertificateInfo certinfo = certSession.getCertificateInfo(CertTools.getFingerprintAsString(extraCert));
        if (certinfo == null) {
            this.errorMessage = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database.";
            return false;
        }

        // More extraCert verifications
        if (!isExtraCertIssuedByCA(cainfo) || !isExtraCertValid() || !isExtraCertActive(certinfo)) {
            return false;
        }

        // Check that extraCert belong to an admin with sufficient access rights
        if (!isAuthorizedAdmin(certinfo, msg, cainfo.getCAId())) {
            this.errorMessage = "'" + CertTools.getSubjectDN(extraCert)
                    + "' is not an authorized administrator.";
            return false;
        }

    } else if (!ramode) { // client mode

        String extraCertUsername = null;
        if (vendormode) {

            // Check that extraCert is issued  by a configured VendorCA
            if (!impl.isExtraCertIssuedByVendorCA(admin, this.confAlias, extraCert)) {
                this.errorMessage = "The certificate in extraCert field is not issued by any of the configured Vendor CAs: "
                        + cmpConfiguration.getVendorCA(confAlias);
                return false;
            }

            // Extract the username from extraCert to use for  further authentication
            String subjectDN = CertTools.getSubjectDN(extraCert);
            extraCertUsername = CertTools.getPartFromDN(subjectDN,
                    this.cmpConfiguration.getExtractUsernameComponent(this.confAlias));
            if (log.isDebugEnabled()) {
                log.debug("Username (" + extraCertUsername + ") was extracted from the '"
                        + this.cmpConfiguration.getExtractUsernameComponent(this.confAlias)
                        + "' part of the subjectDN of the certificate in the 'extraCerts' field.");
            }

        } else {

            // Get the CA to use for the authentication
            CAInfo cainfo = getCAInfoByIssuer(CertTools.getIssuerDN(extraCert));

            // Check that extraCert is in the Database
            CertificateInfo certinfo = certSession
                    .getCertificateInfo(CertTools.getFingerprintAsString(extraCert));
            if (certinfo == null) {
                this.errorMessage = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database.";
                return false;
            }

            // More extraCert verifications
            if (!isExtraCertIssuedByCA(cainfo) || !isExtraCertValid() || !isExtraCertActive(certinfo)) {
                return false;
            }

            // Extract the username from extraCert to use for  further authentication
            extraCertUsername = certinfo.getUsername();
        }

        // Check if this certificate belongs to the user
        if ((username != null) && (extraCertUsername != null)) {
            if (!StringUtils.equals(username, extraCertUsername)) {
                this.errorMessage = "The End Entity certificate attached to the PKIMessage in the extraCert field does not belong to user '"
                        + username + "'";
                if (log.isDebugEnabled()) {
                    // Use a different debug message, as not to reveal too much information
                    log.debug(this.errorMessage + ", but to user '" + extraCertUsername + "'");
                }
                return false;
            }

            //set the password of the request to this user's password so it can later be used when issuing the certificate
            if (log.isDebugEnabled()) {
                log.debug(
                        "The End Entity certificate attached to the PKIMessage in the extraCert field belongs to user '"
                                + username + "'.");
                log.debug("Extracting and setting password for user '" + username + "'.");
            }
            try {
                EndEntityInformation user = eeAccessSession.findUser(admin, username);
                password = user.getPassword();
                if (password == null) {
                    password = genRandomPwd();
                    user.setPassword(password);
                    eeManagementSession.changeUser(admin, user, false);
                }
            } catch (AuthorizationDeniedException e) {
                if (log.isDebugEnabled()) {
                    log.debug(e.getLocalizedMessage());
                }
                this.errorMessage = e.getLocalizedMessage();
                return false;
            } catch (CADoesntExistsException e) {
                if (log.isDebugEnabled()) {
                    log.debug(e.getLocalizedMessage());
                }
                this.errorMessage = e.getLocalizedMessage();
                return false;
            } catch (UserDoesntFullfillEndEntityProfile e) {
                if (log.isDebugEnabled()) {
                    log.debug(e.getLocalizedMessage());
                }
                this.errorMessage = e.getLocalizedMessage();
                return false;
            } catch (WaitingForApprovalException e) {
                if (log.isDebugEnabled()) {
                    log.debug(e.getLocalizedMessage());
                }
                this.errorMessage = e.getLocalizedMessage();
                return false;
            } catch (EjbcaException e) {
                if (log.isDebugEnabled()) {
                    log.debug(e.getLocalizedMessage());
                }
                this.errorMessage = e.getLocalizedMessage();
                return false;
            }
        }
    }

    //-------------------------------------------------------------
    //Begin the signature verification process.
    //Verify the signature of msg using the public key of extraCert
    //-------------------------------------------------------------
    try {
        final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
                "BC");
        sig.initVerify(extraCert.getPublicKey());
        sig.update(CmpMessageHelper.getProtectedBytes(msg));
        if (sig.verify(msg.getProtection().getBytes())) {
            if (password == null) {
                // If not set earlier
                password = genRandomPwd();
            }
        } else {
            this.errorMessage = "Failed to verify the signature in the PKIMessage";
            return false;
        }
    } catch (InvalidKeyException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getLocalizedMessage());
        }
        this.errorMessage = e.getLocalizedMessage();
        return false;
    } catch (NoSuchAlgorithmException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getLocalizedMessage());
        }
        this.errorMessage = e.getLocalizedMessage();
        return false;
    } catch (NoSuchProviderException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getLocalizedMessage());
        }
        this.errorMessage = e.getLocalizedMessage();
        return false;
    } catch (SignatureException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getLocalizedMessage());
        }
        this.errorMessage = e.getLocalizedMessage();
        return false;
    }

    return this.password != null;
}

From source file:org.ejbca.core.protocol.cmp.authentication.EndEntityCertificateAuthenticationModule.java

License:Open Source License

/**
 * Checks if cert belongs to an administrator who is authorized to process the request.
 * //w  ww .j a  v  a2  s . c  om
 * @param certInfo
 * @param msg
 * @param caid
 * @return true if the administrator is authorized to process the request and false otherwise.
 */
private boolean isAuthorizedAdmin(final CertificateInfo certInfo, final PKIMessage msg, final int caid) {
    final String username = certInfo.getUsername();

    X509Certificate x509cert = (X509Certificate) extraCert;
    Set<X509Certificate> credentials = new HashSet<X509Certificate>();
    credentials.add(x509cert);

    AuthenticationSubject subject = new AuthenticationSubject(null, credentials);
    AuthenticationToken reqAuthToken = authenticationProviderSession.authenticate(subject);

    if (!authSession.isAuthorizedNoLogging(admin, StandardRules.CAACCESS.resource() + caid)) {
        if (log.isDebugEnabled()) {
            log.debug("Admin " + admin.toString() + " not authorized to resource "
                    + StandardRules.CAACCESS.resource() + caid);
        }
        return false;
    }

    final int eeprofid;
    try {
        eeprofid = getUsedEndEntityProfileId((DEROctetString) msg.getHeader().getSenderKID());
    } catch (EndEntityProfileNotFoundException e) {
        log.error(e.getLocalizedMessage(), e);
        return false;
    }

    final int tagnr = msg.getBody().getType();
    if ((tagnr == CmpPKIBodyConstants.CERTIFICATAIONREQUEST)
            || (tagnr == CmpPKIBodyConstants.INITIALIZATIONREQUEST)
            || (tagnr == CmpPKIBodyConstants.KEYUPDATEREQUEST)) {

        if (!authorizedToEndEntityProfile(reqAuthToken, eeprofid, AccessRulesConstants.CREATE_END_ENTITY)) {
            if (log.isDebugEnabled()) {
                log.debug("Admin " + admin.toString() + " was not authorized to resource "
                        + StandardRules.ROLE_ROOT);
            }
            return false;
        }

        if (!authorizedToEndEntityProfile(reqAuthToken, eeprofid, AccessRulesConstants.EDIT_END_ENTITY)) {
            if (log.isDebugEnabled()) {
                log.debug("Admin " + admin.toString() + " was not authorized to resource "
                        + StandardRules.ROLE_ROOT);
            }
            return false;
        }

        if (!authSession.isAuthorizedNoLogging(reqAuthToken, AccessRulesConstants.REGULAR_CREATECERTIFICATE)) {
            if (log.isDebugEnabled()) {
                log.debug("Administrator " + username + " is not authorized to create certificates.");
            }
            return false;
        }
    } else if (tagnr == CmpPKIBodyConstants.REVOCATIONREQUEST) {

        if (!authorizedToEndEntityProfile(reqAuthToken, eeprofid, AccessRulesConstants.REVOKE_END_ENTITY)) {
            if (log.isDebugEnabled()) {
                log.debug("Administrator " + username + " is not authorized to revoke.");
            }
            return false;
        }

        if (!authSession.isAuthorizedNoLogging(reqAuthToken, AccessRulesConstants.REGULAR_REVOKEENDENTITY)) {
            if (log.isDebugEnabled()) {
                log.debug("Administrator " + username + " is not authorized to revoke End Entities");
            }
            return false;
        }

    }
    return true;
}

From source file:org.ejbca.core.protocol.cmp.authentication.HMACAuthenticationModule.java

License:Open Source License

@Override
/*/*from w w w  .j  a v  a2  s  .com*/
 * Verifies that 'msg' is sent by a trusted source. 
 * 
 * In RA mode:
 *      - A globally configured shared secret for all CAs will be used to authenticate the message.
 *      - If the globally shared secret fails, the password set in the CA will be used to authenticate the message.
 *  In client mode, the clear-text password set in the pre-registered end entity in the database will be used to 
 *  authenticate the message. 
 * 
 * When successful, the authentication string will be set to the password that was successfully used in authenticating the message.
 */
public boolean verifyOrExtract(final PKIMessage msg, final String username) {

    if (msg == null) {
        this.errorMessage = "No PKIMessage was found";
        return false;
    }

    if ((msg.getProtection() == null) || (msg.getHeader().getProtectionAlg() == null)) {
        this.errorMessage = "PKI Message is not athenticated properly. No HMAC protection was found.";
        return false;
    }

    try {
        verifyer = new CmpPbeVerifyer(msg);
    } catch (Exception e) {
        this.errorMessage = "Could not create CmpPbeVerifyer. " + e.getMessage();
        return false;
    }

    if (verifyer == null) {
        this.errorMessage = "Could not create CmpPbeVerifyer Object";
        return false;
    }

    if (this.cmpConfiguration.getRAMode(this.confAlias)) { //RA mode
        if (LOG.isDebugEnabled()) {
            LOG.debug("Verifying HMAC in RA mode");
        }

        // Check that the value of KeyId from the request is allowed 
        // Note that this restriction only applies to 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
        if (StringUtils.equals(cmpConfiguration.getRAEEProfile(confAlias), "KeyId")
                || StringUtils.equals(cmpConfiguration.getRACertProfile(confAlias), "KeyId")) {
            final String keyId = CmpMessageHelper.getStringFromOctets(msg.getHeader().getSenderKID());
            if (StringUtils.equals(keyId, "EMPTY") || StringUtils.equals(keyId, "ENDUSER")) {
                errorMessage = "Unaccepted KeyId '" + keyId + "' in CMP request";
                LOG.info(errorMessage);
                return false;
            }
        }

        // If we use a globally configured shared secret for all CAs we check it right away
        String authSecret = globalSharedSecret;

        if (globalSharedSecret != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Verifying message using Global Shared secret");
            }
            try {
                if (verifyer.verify(authSecret)) {
                    this.password = authSecret;
                } else {
                    String errmsg = INTRES.getLocalizedMessage("cmp.errorauthmessage", "Global auth secret");
                    LOG.info(errmsg); // info because this is something we should expect and we handle it
                    if (verifyer.getErrMsg() != null) {
                        errmsg = verifyer.getErrMsg();
                        LOG.info(errmsg);
                    }
                }
            } catch (InvalidKeyException e) {
                this.errorMessage = e.getLocalizedMessage();
                if (LOG.isDebugEnabled()) {
                    LOG.debug(this.errorMessage, e);
                }
                return false;
            } catch (NoSuchAlgorithmException e) {
                this.errorMessage = e.getLocalizedMessage();
                if (LOG.isDebugEnabled()) {
                    LOG.debug(this.errorMessage, e);
                }
                return false;
            } catch (NoSuchProviderException e) {
                this.errorMessage = e.getLocalizedMessage();
                if (LOG.isDebugEnabled()) {
                    LOG.debug(this.errorMessage, e);
                }
                return false;
            }
        }

        // If password is null, then we failed verification using global shared secret
        if (this.password == null) {

            if (cainfo instanceof X509CAInfo) {
                authSecret = ((X509CAInfo) cainfo).getCmpRaAuthSecret();

                if (StringUtils.isNotEmpty(authSecret)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Verify message using 'CMP RA Authentication Secret' from CA '"
                                + cainfo.getName() + "'.");
                    }
                    try {
                        if (verifyer.verify(authSecret)) {
                            this.password = authSecret;
                        } else {
                            // info because this is something we should expect and we handle it
                            LOG.info(INTRES.getLocalizedMessage("cmp.errorauthmessage",
                                    "Auth secret for CA=" + cainfo.getName()));
                            if (verifyer.getErrMsg() != null) {
                                LOG.info(verifyer.getErrMsg());
                            }
                        }
                    } catch (InvalidKeyException e) {
                        this.errorMessage = INTRES.getLocalizedMessage("cmp.errorgeneral");
                        LOG.error(this.errorMessage, e);
                        return false;
                    } catch (NoSuchAlgorithmException e) {
                        this.errorMessage = INTRES.getLocalizedMessage("cmp.errorgeneral");
                        LOG.error(this.errorMessage, e);
                        return false;
                    } catch (NoSuchProviderException e) {
                        this.errorMessage = INTRES.getLocalizedMessage("cmp.errorgeneral");
                        LOG.error(this.errorMessage, e);
                        return false;
                    }
                } else {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("CMP password is null from CA '" + cainfo.getName() + "'.");
                    }
                }
            }
        }

        // If password is still null, then we have failed verification with CA authentication secret too.
        if (password == null) {
            this.errorMessage = "Failed to verify message using both Global Shared Secret and CMP RA Authentication Secret";
            return false;
        }

    } else { //client mode
        if (LOG.isDebugEnabled()) {
            LOG.debug("Verifying HMAC in Client mode");
        }
        //If client mode, we try to get the pre-registered endentity from the DB, and if there is a 
        //clear text password we check HMAC using this password.
        EndEntityInformation userdata = null;
        String subjectDN = null;

        try {
            if (username != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Searching for an end entity with username='" + username + "'.");
                }
                userdata = this.eeAccessSession.findUser(admin, username);
            } else {
                // No username given, so we try to find from subject/issuerDN from the certificate request
                final CertTemplate certTemp = getCertTemplate(msg);
                subjectDN = certTemp.getSubject().toString();

                String issuerDN = null;
                final X500Name issuer = certTemp.getIssuer();
                if ((issuer != null) && (subjectDN != null)) {
                    issuerDN = issuer.toString();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Searching for an end entity with SubjectDN='" + subjectDN + "' and isserDN='"
                                + issuerDN + "'");
                    }

                    List<EndEntityInformation> userdataList = eeAccessSession
                            .findUserBySubjectAndIssuerDN(this.admin, subjectDN, issuerDN);
                    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.");
                    }
                } else if (subjectDN != null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Searching for an end entity with SubjectDN='" + subjectDN + "'.");
                    }
                    List<EndEntityInformation> userdataList = this.eeAccessSession.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.");
                    }
                }
            }
        } catch (AuthorizationDeniedException e) {
            LOG.info("No EndEntity with subjectDN '" + subjectDN + "' could be found. "
                    + e.getLocalizedMessage());
        }

        if (userdata != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Comparing HMAC password authentication for user '" + userdata.getUsername() + "'.");
            }

            final String eepassword = userdata.getPassword();
            if (StringUtils.isNotEmpty(eepassword)) {
                try {
                    if (verifyer.verify(eepassword)) {
                        this.password = eepassword;
                    } else {
                        String errmsg = INTRES.getLocalizedMessage("cmp.errorauthmessage",
                                userdata.getUsername());
                        LOG.info(errmsg); // info because this is something we should expect and we handle it
                        if (verifyer.getErrMsg() != null) {
                            errmsg = verifyer.getErrMsg();
                            LOG.info(errmsg);
                        }
                        this.errorMessage = errmsg;
                        return false;
                    }
                } catch (InvalidKeyException e) {
                    this.errorMessage = INTRES.getLocalizedMessage("cmp.errorgeneral");
                    LOG.error(this.errorMessage, e);
                    return false;
                } catch (NoSuchAlgorithmException e) {
                    this.errorMessage = INTRES.getLocalizedMessage("cmp.errorgeneral");
                    LOG.error(this.errorMessage, e);
                    return false;
                } catch (NoSuchProviderException e) {
                    this.errorMessage = INTRES.getLocalizedMessage("cmp.errorgeneral");
                    LOG.error(this.errorMessage, e);
                    return false;
                }
            } else {
                this.errorMessage = "No clear text password for user '" + userdata.getUsername()
                        + "', not possible to check authentication.";
                return false;
            }
        } else {
            LOG.info(INTRES.getLocalizedMessage("ra.errorentitynotexist",
                    StringUtils.isNotEmpty(username) ? username : subjectDN));
            this.errorMessage = INTRES.getLocalizedMessage("ra.wrongusernameorpassword");
            return false;
        }
    }

    return this.password != null;
}

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

License:Open Source License

@Test
public void test03HMACCrmfReq() throws Exception {

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

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

    final 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 PKIMessage req = protectPKIMessage(msg, false, "foo123", "mykeyid", 567);
    assertNotNull("Protecting PKIMessage with HMACPbe failed.", req);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);/*from   w w  w. j  a  va  2s.c  om*/
    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(), true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    final CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    final Certificate cert1 = checkCmpCertRepMessage(USER_DN, this.cacert, resp,
            ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
    assertNotNull("Crmf request did not return a certificate", cert1);
}

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

License:Open Source License

@Test
public void test04HMACRevReq() 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);

    final X500Name revUserDN = new X500Name("CN=cmprevuser1,C=SE");
    final String revUsername = "cmprevuser1";
    String fingerprint = null;// ww  w. j ava  2  s  .c o m
    try {

        Collection<Certificate> certs = this.certificateStoreSession
                .findCertificatesBySubjectAndIssuer(revUserDN.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();
            if (!this.certificateStoreSession.isRevoked(issuerDN, CertTools.getSerialNumber(tmp))) {
                cert = tmp;
                break;
            }
        }
        if (cert == null) {
            createUser(revUsername, revUserDN.toString(), "foo123", true, this.caid,
                    SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
            KeyPair admkeys = KeyTools.genKeys("1024", "RSA");
            cert = this.signSession.createCertificate(ADMIN, revUsername, "foo123",
                    new PublicKeyWrapper(admkeys.getPublic()));
        }
        assertNotNull("No certificate to revoke.", cert);

        fingerprint = CertTools.getFingerprintAsString(cert); // to be able to remove

        PKIMessage msg = genRevReq(issuerDN, revUserDN, CertTools.getSerialNumber(cert), this.cacert,
                this.nonce, this.transid, false, null, null);
        assertNotNull("Generating RevocationRequest failed.", msg);
        PKIMessage req = protectPKIMessage(msg, false, "foo123", "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, revUserDN, this.cacert,
                req.getHeader().getSenderNonce().getOctets(), req.getHeader().getTransactionID().getOctets(),
                true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revStatus = checkRevokeStatus(issuerDN, CertTools.getSerialNumber(cert));
        Assert.assertNotEquals("Revocation request failed to revoke the certificate",
                RevokedCertInfo.NOT_REVOKED, revStatus);
    } finally {
        if (this.eeAccessSession.findUser(ADMIN, revUsername) != null) {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, revUsername, ReasonFlags.unused);
        }
        this.internalCertStoreSession.removeCertificate(fingerprint);
    }

}

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

License:Open Source License

@Test
public void test05EECrmfReq() 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);

    final X500Name testUserDN = new X500Name("CN=cmptestuser5,C=SE");
    final String testUsername = "cmptestuser5";
    String fingerprint = null;/*from  www .  j a v a 2  s . c  o m*/
    String fingerprint2 = null;
    AuthenticationToken admToken = null;
    Certificate admCert = null;
    try {
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

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

        KeyPair admkeys = KeyTools.genKeys("512", "RSA");
        admToken = createAdminToken(admkeys, testUsername, testUserDN.toString(), this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        admCert = getCertFromCredentials(admToken);
        fingerprint = CertTools.getFingerprintAsString(admCert);

        CMPCertificate[] extraCert = getCMPCert(admCert);
        msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull(msg);
        //******************************************''''''
        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, testUserDN, this.cacert,
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        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 {
        removeAuthenticationToken(admToken, admCert, testUsername); // also removes testUsername
        this.internalCertStoreSession.removeCertificate(fingerprint);
        this.internalCertStoreSession.removeCertificate(fingerprint2);
    }
}

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

License:Open Source License

@Test
public void test06EERevReq() 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();/*w w w.  ja v  a  2s .co  m*/
        if (!this.certificateStoreSession.isRevoked(issuerDN, CertTools.getSerialNumber(tmp))) {
            cert = tmp;
            break;
        }
    }
    if (cert == null) {
        createUser("cmprevuser1", "CN=cmprevuser1,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()));
    }
    assertNotNull("No certificate to revoke.", cert);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage msg = genRevReq(issuerDN, USER_DN, CertTools.getSerialNumber(cert), this.cacert, 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, issuerDN, USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(),
            msg.getHeader().getTransactionID().getOctets(), true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    int revStatus = checkRevokeStatus(issuerDN, CertTools.getSerialNumber(cert));
    assertNotEquals("Revocation request failed to revoke the certificate", RevokedCertInfo.NOT_REVOKED,
            revStatus);

    removeAuthenticationToken(adminToken, admCert, adminName);
}

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();/* w ww .jav a  2  s  .com*/
        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);
    }
}