Package org.ejbca.core.protocol

Examples of org.ejbca.core.protocol.IResponseMessage


        byte[] result = null
        Certificate cert=null;
    PKCS10RequestMessage req = RequestMessageUtils.genPKCS10RequestMessage(b64Encoded);
    req.setUsername(username);
        req.setPassword(password);
        IResponseMessage resp = signsession.createCertificate(administrator, req, X509ResponseMessage.class, null);
        cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
        if(resulttype == ENCODED_CERTIFICATE) {
          result = cert.getEncoded();
        } else
          result = signsession.createPKCS7(administrator, cert, true);
        }
View Full Code Here


    public byte[] cvcCertRequest(SignSessionLocal signsession, byte[] b64Encoded, String username, String password) throws Exception {           
      CVCRequestMessage req = RequestMessageUtils.genCVCRequestMessage(b64Encoded);
        req.setUsername(username);
            req.setPassword(password);
            // Yes it says X509ResponseMessage, but for CVC it means it just contains the binary certificate blob
            IResponseMessage resp = signsession.createCertificate(administrator, req, X509ResponseMessage.class, null);
            Certificate cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
            byte[] result = cert.getEncoded();
            log.debug("Created CV certificate for " + username);
            if (debug != null) {
                debug.print("<h4>Generated certificate:</h4>");
                debug.printInsertLineBreaks(cert.toString().getBytes());             
View Full Code Here


  private byte[] getCertResponseFromPublicKey(final Admin admin, final IRequestMessage msg,
      final String hardTokenSN, final String responseType) throws EjbcaException, CertificateEncodingException, CertificateException, IOException {
    byte[] retval = null;
    final IResponseMessage resp = signSession.createCertificate(admin, msg, org.ejbca.core.protocol.X509ResponseMessage.class, null);
    final java.security.cert.Certificate cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
    if (responseType.equalsIgnoreCase(CertificateHelper.RESPONSETYPE_CERTIFICATE)) {
      retval = cert.getEncoded();
    } else if(responseType.equalsIgnoreCase(CertificateHelper.RESPONSETYPE_PKCS7)) {
      retval = signSession.createPKCS7(admin, cert, false);
    } else if(responseType.equalsIgnoreCase(CertificateHelper.RESPONSETYPE_PKCS7WITHCHAIN)) {
View Full Code Here

    }
    return ret;
  }

  public static IResponseMessage createResponseMessage(Class responseClass, IRequestMessage req, Certificate cert, PrivateKey signPriv, String provider){
    IResponseMessage ret = null;
    // Create the response message and set all required fields
    try {
      ret = (IResponseMessage) responseClass.newInstance();
    } catch (InstantiationException e) {
      //TODO : do something with these exceptions
      log.error("Error creating response message", e);
      return null;
    } catch (IllegalAccessException e) {
      log.error("Error creating response message", e);
      return null;
    }
    if (ret.requireSignKeyInfo()) {
      ret.setSignKeyInfo(cert, signPriv, provider);
    }
    if (req.getSenderNonce() != null) {
      ret.setRecipientNonce(req.getSenderNonce());
    }
    if (req.getTransactionId() != null) {
      ret.setTransactionId(req.getTransactionId());
    }
    // Sender nonce is a random number
    byte[] senderNonce = new byte[16];
    Random randomSource = new Random();
    randomSource.nextBytes(senderNonce);
    ret.setSenderNonce(new String(Base64.encode(senderNonce)));
    // If we have a specified request key info, use it in the reply
    if (req.getRequestKeyInfo() != null) {
      ret.setRecipientKeyInfo(req.getRequestKeyInfo());
    }
    // Which digest algorithm to use to create the response, if applicable
    ret.setPreferredDigestAlg(req.getPreferredDigestAlg());
    // Include the CA cert or not in the response, if applicable for the response type
    ret.setIncludeCACert(req.includeCACert());
    // Hint to the response which request type it is in response to
    ret.setRequestType(req.getRequestType());
    ret.setRequestId(req.getRequestId());
    // If there is some protection parameters we need to lift over from the request message, the request and response knows about it
    ret.setProtectionParamsFromRequest(req);
    return ret;
  }
View Full Code Here

                      log.debug("Request is processed with status: "+msg.getStatus());
                      SubMessages submessagesresp = msg.getSubMessages(null,null,null);
                      Iterator<ISubMessage> iter =  submessagesresp.getSubMessages().iterator();
                      PKCS10Response resp = (PKCS10Response)iter.next();
                      // create proper ScepResponseMessage
                      IResponseMessage ret = reqmsg.createResponseMessage(org.ejbca.core.protocol.scep.ScepResponseMessage.class, reqmsg, racert, rapriv, cryptProvider);
                      ret.setCACert(cacert);
                    X509Certificate respCert = resp.getCertificate();
                      if ( resp.isSuccessful() && (respCert != null) ) {
                        ret.setCertificate(respCert);                         
                      } else {
                        ret.setStatus(ResponseStatus.FAILURE);
                        ret.setFailInfo(FailInfo.BAD_REQUEST);
                        String failText = resp.getFailInfo();
                        ret.setFailText(failText);
                      }
                      ret.create();
                      reply = ret.getResponseMessage();                       
                    } else {
                      log.debug("Request is not yet processed, status: "+msg.getStatus());
                        reply = createPendingResponseMessage(reqmsg, racert, rapriv, cryptProvider).getResponseMessage();
                        log.debug("Responding with pending response, still pending.");                    
                    }                   
View Full Code Here

    if(userdata.getTokenType() != SecConst.TOKEN_SOFT_BROWSERGEN){
      throw new WrongTokenTypeException ("Error: Wrong Token Type of user, must be 'USERGENERATED' for PKCS10/SPKAC/CRMF/CVC requests");
    }
    // This is the secret sauce, do the end entity handling automagically here before we get the cert
    addOrEditUser(admin, userdata, false, true);
    IResponseMessage retval = null;
    try {
      retval = signSession.createCertificate(admin, req, responseClass, userdata);
    } catch (NotFoundException e) {
      sessionContext.setRollbackOnly()// This is an application exception so it wont trigger a roll-back automatically
      throw e;
View Full Code Here

   */
  private byte[] getCertResponseFromPublicKey(Admin admin, IRequestMessage msg, String hardTokenSN, int responseType, UserDataVO userData)
  throws EjbcaException, CertificateEncodingException, CertificateException, IOException {
    byte[] retval = null;
    Class respClass = org.ejbca.core.protocol.X509ResponseMessage.class;
    IResponseMessage resp =  signSession.createCertificate(admin, msg, respClass, userData);
    java.security.cert.Certificate cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
    if(responseType == SecConst.CERT_RES_TYPE_CERTIFICATE){
      retval = cert.getEncoded();
    }
    if(responseType == SecConst.CERT_RES_TYPE_PKCS7){
      retval = signSession.createPKCS7(admin, cert, false);
View Full Code Here

    this.certificateStoreSession = certificateStoreSession;

  }
  public IResponseMessage handleMessage(BaseCmpMessage msg) {
    LOG.trace(">handleMessage");
    IResponseMessage resp = null;
    // if version == 1 it is cmp1999 and we should not return a message back
    // Try to find a HMAC/SHA1 protection key
    String owfAlg = null;
    String macAlg = null;
    int iterationCount = 1024;
    String cmpRaAuthSecret = null;
    String keyId = getSenderKeyId(msg.getHeader());
    if (keyId != null) {
      try {
        ResponseStatus status = ResponseStatus.FAILURE;
        FailInfo failInfo = FailInfo.BAD_MESSAGE_CHECK;
        String failText = null;
        CmpPbeVerifyer verifyer = new CmpPbeVerifyer(msg.getMessage());       
        owfAlg = verifyer.getOwfOid();
        macAlg = verifyer.getMacOid();
        iterationCount = verifyer.getIterationCount();
        boolean ret = true;
        if (raAuthenticationSecret != null) {
          if (!verifyer.verify(raAuthenticationSecret)) {
            ret = false;
          }
          cmpRaAuthSecret = raAuthenticationSecret;
        } else {
          // Get the correct profiles' and CA ids based on current configuration.
          CAInfo caInfo;
          try {
            int eeProfileId = getUsedEndEntityProfileId(keyId);
            int caId = getUsedCaId(keyId, eeProfileId);
            caInfo = caAdminSession.getCAInfo(admin, caId);
          } catch (NotFoundException e) {
            LOG.info(INTRES.getLocalizedMessage(CMP_ERRORGENERAL, e.getMessage()), e);
            return CmpMessageHelper.createUnprotectedErrorMessage(msg, ResponseStatus.FAILURE, FailInfo.INCORRECT_DATA, e.getMessage());
          } catch (EJBException e) {
            final String errMsg = INTRES.getLocalizedMessage(CMP_ERRORADDUSER);
            LOG.error(errMsg, e);                  
            return null;    // Fatal error
          }
          if (caInfo instanceof X509CAInfo) {
            cmpRaAuthSecret = ((X509CAInfo) caInfo).getCmpRaAuthSecret();
          }
          // Now we know which CA the request is for, if we didn't use a global shared secret we can check it now!
          if (cmpRaAuthSecret == null || !verifyer.verify(cmpRaAuthSecret)) {
            ret = false;
          }
        }
        if (ret) {
          // If authentication was correct, we will now try to find the certificate to revoke
          PKIMessage pkimsg = msg.getMessage();
          PKIBody body = pkimsg.getBody();
          RevReqContent rr = body.getRr();
          RevDetails rd = rr.getRevDetails(0);
          CertTemplate ct = rd.getCertDetails();
          DERInteger serno = ct.getSerialNumber();
          X509Name issuer = ct.getIssuer();
          // Get the revocation reason.
          // For CMPv1 this can be a simple DERBitString or it can be a requested CRL Entry Extension
          // If there exists CRL Entry Extensions we will use that, because it's the only thing allowed in CMPv2
          int reason = RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED;
          DERBitString reasonbits = rd.getRevocationReason();
          if (reasonbits != null) {
            reason = CertTools.bitStringToRevokedCertInfo(reasonbits);           
            LOG.debug("CMPv1 revocation reason: "+reason);
          } else {
            LOG.debug("CMPv1 revocation reason is null");
          }
          X509Extensions crlExt = rd.getCrlEntryDetails();
          if (crlExt != null) {
            X509Extension ext = crlExt.getExtension(X509Extensions.ReasonCode);
            if (ext != null) {
              try {
                ASN1InputStream ai = new ASN1InputStream(ext.getValue().getOctets());
                DERObject obj = ai.readObject();
                DEREnumerated crlreason = DEREnumerated.getInstance(obj);
                // RevokedCertInfo.REVOCATION_REASON_AACOMPROMISE are the same integer values as the CRL reason extension code
                reason = crlreason.getValue().intValue();
                LOG.debug("CRLReason extension: "+reason);
              } catch (IOException e) {
                LOG.info("Exception parsin CRL reason extension: ", e);
              }
            } else {
              LOG.debug("No CRL reason code extension present.");
            }
          } else {
            LOG.debug("No CRL entry extensions present");
          }
         
          if ( (serno != null) && (issuer != null) ) {
            String iMsg = INTRES.getLocalizedMessage("cmp.receivedrevreq", issuer.toString(), serno.getValue().toString(16));
            LOG.info(iMsg);
            try {
              userAdminSession.revokeCert(admin, serno.getValue(), issuer.toString(), reason);
              status = ResponseStatus.SUCCESS;
            } catch (AuthorizationDeniedException e) {
              failInfo = FailInfo.NOT_AUTHORIZED;
              String errMsg = INTRES.getLocalizedMessage("cmp.errornotauthrevoke", issuer.toString(), serno.getValue().toString(16));
              failText = errMsg;
              LOG.error(failText);
            } catch (FinderException e) {
              failInfo = FailInfo.BAD_CERTIFICATE_ID;
              String errMsg = INTRES.getLocalizedMessage("cmp.errorcertnofound", issuer.toString(), serno.getValue().toString(16));
              failText = errMsg;
              LOG.error(failText);
            } catch (WaitingForApprovalException e) {
              status = ResponseStatus.GRANTED_WITH_MODS;
            } catch (ApprovalException e) {
              failInfo = FailInfo.BAD_REQUEST;
              String errMsg = INTRES.getLocalizedMessage("cmp.erroralreadyrequested");
              failText = errMsg;
              LOG.error(failText);
            } catch (AlreadyRevokedException e) {
              failInfo = FailInfo.BAD_REQUEST;
              String errMsg = INTRES.getLocalizedMessage("cmp.erroralreadyrevoked");
              failText = errMsg;
              LOG.error(failText);
            }
          } else {
            failInfo = FailInfo.BAD_CERTIFICATE_ID;
            String errMsg = INTRES.getLocalizedMessage("cmp.errormissingissuerrevoke", issuer.toString(), serno.getValue().toString(16));
            failText = errMsg;
            LOG.error(failText);
          }
        } else {
          String errMsg = INTRES.getLocalizedMessage("cmp.errorauthmessage");
          LOG.error(errMsg);
          failText = errMsg;
          if (verifyer.getErrMsg() != null) {
            failText = verifyer.getErrMsg();
          }
        }
        LOG.debug("Creating a PKI revocation message response");
        CmpRevokeResponseMessage rresp = new CmpRevokeResponseMessage();
        rresp.setRecipientNonce(msg.getSenderNonce());
        rresp.setSenderNonce(new String(Base64.encode(CmpMessageHelper.createSenderNonce())));
        rresp.setSender(msg.getRecipient());
        rresp.setRecipient(msg.getSender());
        rresp.setTransactionId(msg.getTransactionId());
        rresp.setFailInfo(failInfo);
        rresp.setFailText(failText);
        rresp.setStatus(status);
          // Set all protection parameters
        LOG.debug(responseProtection+", "+owfAlg+", "+macAlg+", "+keyId+", "+cmpRaAuthSecret);
          if (StringUtils.equals(responseProtection, "pbe") && (owfAlg != null) && (macAlg != null) && (keyId != null) && (cmpRaAuthSecret != null) ) {
            rresp.setPbeParameters(keyId, cmpRaAuthSecret, owfAlg, macAlg, iterationCount);
          }
          resp = rresp;
        try {
          resp.create();
        } catch (InvalidKeyException e) {
          String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
          LOG.error(errMsg, e);     
        } catch (NoSuchAlgorithmException e) {
          String errMsg = INTRES.getLocalizedMessage("cmp.errorgeneral");
View Full Code Here

          log.error(eMsg);
          return CmpMessageHelper.createUnprotectedErrorMessage(null, ResponseStatus.FAILURE, FailInfo.BAD_REQUEST, eMsg);
        }
        throw new Exception("Something is null! Handler="+handler+", cmpMessage="+cmpMessage);
      }
      final IResponseMessage ret  = handler.handleMessage(cmpMessage);
      if (ret != null) {
        log.debug("Received a response message from CmpMessageHandler.");
      } else {
        log.error( intres.getLocalizedMessage("cmp.errorresponsenull") );
      }
View Full Code Here

    @Override
    public IResponseMessage processRequest(Admin admin, CAInfo cainfo, IRequestMessage requestmessage) throws CAExistsException, CADoesntExistsException,
            AuthorizationDeniedException, CATokenOfflineException {
        final CA ca;
        Collection<Certificate> certchain = null;
        IResponseMessage returnval = null;
        // check authorization
        if(!authorizationSession.isAuthorizedNoLog(admin, "/super_administrator")) {
            String msg = intres.getLocalizedMessage("caadmin.notauthorizedtocertresp", cainfo.getName());
            logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_NOTAUTHORIZEDTORESOURCE,
                    msg);
            throw new AuthorizationDeniedException(msg);
        }

        // Check that CA doesn't already exists
        CAData oldcadata = null;
        int caid = cainfo.getCAId();
        if (caid >= 0 && caid <= CAInfo.SPECIALCAIDBORDER) {
          String msg = intres.getLocalizedMessage("caadmin.errorcaexists", cainfo.getName());
          logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg);
          throw new CAExistsException(msg);
        }
        oldcadata = CAData.findById(entityManager, Integer.valueOf(caid));
        // If it did not exist with a certain DN (caid) perhaps a CA with the
        // same CA name exists?
        if (oldcadata == null) {
          oldcadata = CAData.findByName(entityManager, cainfo.getName());
        }
        boolean processinternalca = false;
        if (oldcadata != null) {
            // If we find an already existing CA, there is a good chance that we
            // should throw an exception
            // Saying that the CA already exists.
            // However, if we have the same DN, and give the same name, we
            // simply assume that the admin actually wants
            // to treat an internal CA as an external CA, perhaps there is
            // different HSMs connected for root CA and sub CA?
            if (log.isDebugEnabled()) {
                log.debug("Old castatus=" + oldcadata.getStatus() + ", oldcaid=" + oldcadata.getCaId().intValue() + ", caid=" + cainfo.getCAId()
                        + ", oldcaname=" + oldcadata.getName() + ", name=" + cainfo.getName());
            }
            if (((oldcadata.getStatus() == SecConst.CA_WAITING_CERTIFICATE_RESPONSE) || (oldcadata.getStatus() == SecConst.CA_ACTIVE) || (oldcadata.getStatus() == SecConst.CA_EXTERNAL))
                    && (oldcadata.getCaId().intValue() == cainfo.getCAId()) && (oldcadata.getName().equals(cainfo.getName()))) {
                // Yes, we have all the same DN, CAName and the old CA is either
                // waiting for a certificate response or is active
                // (new CA or active CA that we want to renew)
                // or it is an external CA that we want to issue a new
                // certificate to
                processinternalca = true;
                if (oldcadata.getStatus() == SecConst.CA_EXTERNAL) {
                    log.debug("Renewing an external CA.");
                } else {
                    log.debug("Processing an internal CA, as an external.");
                }
            } else {
                String msg = intres.getLocalizedMessage("caadmin.errorcaexists", cainfo.getName());
                log.info(msg);
                throw new CAExistsException(msg);
            }
        }

        // get signing CA
        if (cainfo.getSignedBy() > CAInfo.SPECIALCAIDBORDER || cainfo.getSignedBy() < 0) {
            try {
              CAData signcadata = CAData.findByIdOrThrow(entityManager, Integer.valueOf(cainfo.getSignedBy()));
                CA signca = signcadata.getCA();
                try {
                    // Check that the signer is valid
                    checkSignerValidity(admin, signcadata);

                    // Get public key from request
                    PublicKey publickey = requestmessage.getRequestPublicKey();

                    // Create cacertificate
                    Certificate cacertificate = null;
                    String subjectAltName = null;
                    if (cainfo instanceof X509CAInfo) {
                        subjectAltName = ((X509CAInfo) cainfo).getSubjectAltName();
                    }
                    UserDataVO cadata = new UserDataVO("nobody", cainfo.getSubjectDN(), cainfo.getSubjectDN().hashCode(), subjectAltName, null, 0, 0, 0, cainfo
                            .getCertificateProfileId(), null, null, 0, 0, null);
                    // We can pass the PKCS10 request message as extra
                    // parameters
                    if (requestmessage instanceof PKCS10RequestMessage) {
                        ExtendedInformation extInfo = new ExtendedInformation();
                        PKCS10CertificationRequest pkcs10 = ((PKCS10RequestMessage) requestmessage).getCertificationRequest();
                        extInfo.setCustomData(ExtendedInformation.CUSTOM_PKCS10, new String(Base64.encode(pkcs10.getEncoded())));
                        cadata.setExtendedinformation(extInfo);
                    }
                    CertificateProfile certprofile = certificateProfileSession.getCertificateProfile(admin, cainfo.getCertificateProfileId());
                    String sequence = null;
                    byte[] ki = requestmessage.getRequestKeyInfo();
                    if ((ki != null) && (ki.length > 0)) {
                        sequence = new String(ki);
                    }
                    cacertificate = signca.generateCertificate(cadata, publickey, -1, cainfo.getValidity(), certprofile, sequence);
                    // X509ResponseMessage works for both X509 CAs and CVC CAs
                    // here...pure luck? I don't think so!
                    returnval = new X509ResponseMessage();
                    returnval.setCertificate(cacertificate);

                    // Build Certificate Chain
                    Collection<Certificate> rootcachain = signca.getCertificateChain();
                    certchain = new ArrayList<Certificate>();
                    certchain.add(cacertificate);
View Full Code Here

TOP

Related Classes of org.ejbca.core.protocol.IResponseMessage

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.