Package org.ejbca.core.model.ca.caadmin

Examples of org.ejbca.core.model.ca.caadmin.CA


        }
        crlCreateSession.run(administrator, ca);
    }

    public void createDeltaCRL(String issuerdn) throws CATokenOfflineException {     
        CA ca;
        try {
            ca = caSession.getCA(administrator, issuerdn.hashCode());
        } catch (CADoesntExistsException e) {
            throw new RuntimeException(e);
        }
View Full Code Here


            logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CACREATED, msg, ctoe);
            throw ctoe;
        }

        // Create CA
        CA ca = null;
        // The certificate profile used for the CAs certificate
        CertificateProfile certprofile = certificateProfileSession.getCertificateProfile(admin, cainfo.getCertificateProfileId());
        // AltName is not implemented for all CA types
        String caAltName = null;
        // X509 CA is the normal type of CA
        if (cainfo instanceof X509CAInfo) {
            log.info("Creating an X509 CA");
            X509CAInfo x509cainfo = (X509CAInfo) cainfo;
            // Create X509CA
            ca = new X509CA(x509cainfo);
            X509CA x509ca = (X509CA) ca;
            ca.setCAToken(catoken);

            // getCertificateProfile
            if ((x509cainfo.getPolicies() != null) && (x509cainfo.getPolicies().size() > 0)) {
                certprofile.setUseCertificatePolicies(true);
                certprofile.setCertificatePolicies(x509cainfo.getPolicies());
            } else if (certprofile.getUseCertificatePolicies()) {
                x509ca.setPolicies(certprofile.getCertificatePolicies());
            }
            caAltName = x509cainfo.getSubjectAltName();
        } else {
            // CVC CA is a special type of CA for EAC electronic passports
            log.info("Creating a CVC CA");
            CVCCAInfo cvccainfo = (CVCCAInfo) cainfo;
            // Create CVCCA
            ca = new CVCCA(cvccainfo);
            ca.setCAToken(catoken);
        }

        // Certificate chain
        Collection<Certificate> certificatechain = null;
        String sequence = catoken.getCATokenInfo().getKeySequence(); // get from CAtoken to make sure it is fresh
        if (cainfo.getSignedBy() == CAInfo.SELFSIGNED) {
            try {
                // create selfsigned certificate
                Certificate cacertificate = null;

                log.debug("CAAdminSessionBean : " + cainfo.getSubjectDN());

                UserDataVO cadata = new UserDataVO("nobody", cainfo.getSubjectDN(), cainfo.getSubjectDN().hashCode(), caAltName, null, 0, 0, 0, cainfo
                        .getCertificateProfileId(), null, null, 0, 0, null);

                cacertificate = ca.generateCertificate(cadata, catoken.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN), -1, cainfo.getValidity(), certprofile,
                        sequence);

                log.debug("CAAdminSessionBean : " + CertTools.getSubjectDN(cacertificate));

                // Build Certificate Chain
                certificatechain = new ArrayList<Certificate>();
                certificatechain.add(cacertificate);

                // set status to active
                castatus = SecConst.CA_ACTIVE;
            } catch (CATokenOfflineException e) {
                String msg = intres.getLocalizedMessage("error.catokenoffline", cainfo.getName());
                logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CACREATED, msg, e);
                throw e;
            } catch (Exception fe) {
                String msg = intres.getLocalizedMessage("caadmin.errorcreateca", cainfo.getName());
                logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CACREATED, msg, fe);
                throw new EJBException(fe);
            }
        }
        if (cainfo.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA) {
            certificatechain = new ArrayList<Certificate>();
            // set status to waiting certificate response.
            castatus = SecConst.CA_WAITING_CERTIFICATE_RESPONSE;
        }

        if (cainfo.getSignedBy() > CAInfo.SPECIALCAIDBORDER || cainfo.getSignedBy() < 0) {
            // Create CA signed by other internal CA.
            try {
              CAData signcadata = CAData.findByIdOrThrow(entityManager, Integer.valueOf(cainfo.getSignedBy()));
                CA signca = signcadata.getCA();
                // Check that the signer is valid
                checkSignerValidity(admin, signcadata);
                // Create CA certificate
                Certificate cacertificate = null;

                UserDataVO cadata = new UserDataVO("nobody", cainfo.getSubjectDN(), cainfo.getSubjectDN().hashCode(), caAltName, null, 0, 0, 0, cainfo
                        .getCertificateProfileId(), null, null, 0, 0, null);

                cacertificate = signca.generateCertificate(cadata, catoken.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN), -1, cainfo.getValidity(), certprofile,
                        sequence);

                // Build Certificate Chain
                Collection<Certificate> rootcachain = signca.getCertificateChain();
                certificatechain = new ArrayList<Certificate>();
                certificatechain.add(cacertificate);
                certificatechain.addAll(rootcachain);
                // set status to active
                castatus = SecConst.CA_ACTIVE;
View Full Code Here

        }

        // Get CA from database
        try {
          CAData cadata = CAData.findByIdOrThrow(entityManager, Integer.valueOf(cainfo.getCAId()));
            CA ca = cadata.getCA();

            // Update CA values
            ca.updateCA(cainfo);
            // Store CA in database
            cadata.setCA(ca);
            // Try to activate the CA token after we have edited the CA
            try {
                CATokenContainer catoken = ca.getCAToken();
                CATokenInfo catokeninfo = cainfo.getCATokenInfo();
                String authCode = catokeninfo.getAuthenticationCode();
                String keystorepass = getDefaultKeyStorePassIfSWAndEmpty(authCode, catokeninfo);
                if (keystorepass != null) {
                    catoken.activate(keystorepass);
                } else {
                    log.debug("Not trying to activate CAToken after editing, authCode == null.");
                }
            } catch (CATokenAuthenticationFailedException ctaf) {
                String msg = intres.getLocalizedMessage("caadmin.errorcreatetokenpin");
                logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg, ctaf);
            } catch (CATokenOfflineException ctoe) {
                String msg = intres.getLocalizedMessage("error.catokenoffline", cainfo.getName());
                logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg, ctoe);
            }
            // No OCSP Certificate exists that can be renewed.
            if (xkmsrenewcert) {
                XKMSCAServiceInfo info = (XKMSCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE);
                Certificate xkmscert = (Certificate) info.getXKMSSignerCertificatePath().get(0);
                ArrayList<Certificate> xkmscertificate = new ArrayList<Certificate>();
                xkmscertificate.add(xkmscert);
                // Publish the extended service certificate, but only for active
                // services
                if ((info.getStatus() == ExtendedCAServiceInfo.STATUS_ACTIVE) && (!xkmscertificate.isEmpty())) {
                    publishCACertificate(admin, xkmscertificate, ca.getCRLPublishers(), ca.getSubjectDN());
                }
            }
            if (cmsrenewcert) {
                CmsCAServiceInfo info = (CmsCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE);
                Certificate cmscert = (Certificate) info.getCertificatePath().get(0);
                ArrayList<Certificate> cmscertificate = new ArrayList<Certificate>();
                cmscertificate.add(cmscert);
                // Publish the extended service certificate, but only for active
                // services
                if ((info.getStatus() == ExtendedCAServiceInfo.STATUS_ACTIVE) && (!cmscertificate.isEmpty())) {
                    publishCACertificate(admin, cmscertificate, ca.getCRLPublishers(), ca.getSubjectDN());
                }
            }
            // Log Action
            String msg = intres.getLocalizedMessage("caadmin.editedca", cainfo.getName());
            logSession.log(admin, cainfo.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_INFO_CAEDITED, msg);
View Full Code Here

            String msg = intres.getLocalizedMessage("caadmin.canotexistsid", Integer.valueOf(caid));
            throw new CADoesntExistsException(msg);
        }
        CAInfo cainfo = null;
        try {
            CA ca = caSession.getCA(admin, caid);      
            cainfo = ca.getCAInfo();
            int status = cainfo.getStatus();
            boolean includeInHealthCheck = cainfo.getIncludeInHealthCheck();
            int tokenstatus = ICAToken.STATUS_OFFLINE;
            if (doSignTest && status == SecConst.CA_ACTIVE && includeInHealthCheck) {
                // Only do a real test signature if the CA is supposed to be
                // active and if it is included in healthchecking
                // Otherwise we will only waste resources
                if (log.isDebugEnabled()) {
                    log.debug("Making test signature with CAs token. CA=" + ca.getName() + ", doSignTest=" + doSignTest + ", CA status=" + status
                            + ", includeInHealthCheck=" + includeInHealthCheck);
                }
                CATokenContainer catoken = ca.getCAToken();
                tokenstatus = catoken.getCATokenInfo().getCATokenStatus();
            } else {
                // if (log.isDebugEnabled()) {
                // log.debug("Not making test signature with CAs token. doSignTest="+doSignTest+", CA status="+status+", includeInHealthCheck="+includeInHealthCheck);
                // }
View Full Code Here

        // Get CA info.
        CAData cadata = null;
        try {
          cadata = CAData.findByIdOrThrow(entityManager, Integer.valueOf(caid));
            CA ca = cadata.getCA();
            String caname = ca.getName();

            Collection<Certificate> chain = null;
            if ((cachainin != null) && (cachainin.size() > 0)) {
                chain = CertTools.createCertChain(cachainin);
                log.debug("Setting request certificate chain of size: " + chain.size());
                ca.setRequestCertificateChain(chain);
            } else {
                log.debug("Empty request certificate chain parameter.");
                // create empty list if input was null
                chain = new ArrayList<Certificate>();
            }
            // AR+ patch to make SPOC independent of external CVCA certificates for automatic renewals
            // i.e. if we don't pass a CA certificate as parameter we try to find a suitable CA certificate in the database, among existing CAs
            // (can be a simple imported CA-certificate of external CA)
            if (chain.isEmpty() &&
              ca.getCAType() == CAInfo.CATYPE_CVC &&
                ca.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA &&
                ca.getStatus() == SecConst.CA_ACTIVE){
              CardVerifiableCertificate dvcert = (CardVerifiableCertificate)ca.getCACertificate();
          String ca_ref = dvcert.getCVCertificate().getCertificateBody().getAuthorityReference().getConcatenated();
              log.debug("DV renewal missing CVCA cert, try finding CA for:"+ ca_ref);
            Iterator<Integer> cas = caSession.getAvailableCAs(admin).iterator();
            while (cas.hasNext()){
              CA cvca = caSession.getCA(admin,cas.next());
              if (cvca.getCAType() == CAInfo.CATYPE_CVC && cvca.getSignedBy() == CAInfo.SELFSIGNED){
                CardVerifiableCertificate cvccert = (CardVerifiableCertificate)cvca.getCACertificate();
                if (ca_ref.equals (cvccert.getCVCertificate().getCertificateBody().getHolderReference().getConcatenated())){
                        log.debug("Added missing CVCA to rewnewal request: "+ cvca.getName());
                  chain.add(cvccert);
                  break;
                }
              }
             }
View Full Code Here

        byte[] returnval = null;
        String caname = "" + caid;
        CAData signedbydata = CAData.findByIdOrThrow(entityManager, Integer.valueOf(caid));
        try {
            caname = signedbydata.getName();
            CA signedbyCA = signedbydata.getCA();
            returnval = signedbyCA.signRequest(request, usepreviouskey, createlinkcert);
            String msg = intres.getLocalizedMessage("caadmin.certreqsigned", caname);
            logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_INFO_SIGNEDREQUEST, msg);
        } catch (Exception e) {
            String msg = intres.getLocalizedMessage("caadmin.errorcertreqsign", caname);
            logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_SIGNEDREQUEST, msg, e);
View Full Code Here

            String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
            logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg);
            throw new EjbcaException(msg);
        }
        try {
            CA ca = cadata.getCA();
            try {
                if (responsemessage instanceof X509ResponseMessage) {
                    cacert = ((X509ResponseMessage) responsemessage).getCertificate();
                } else {
                    String msg = intres.getLocalizedMessage("caadmin.errorcertrespillegalmsg", responsemessage != null ? responsemessage.getClass().getName()
                            : "null");
                    logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg);
                    throw new EjbcaException(msg);
                }

                // If signed by external CA, process the received certificate
                // and store it, activating the CA
                if (ca.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA) {
                    // Check that CA DN is equal to the certificate response.
                    if (!CertTools.getSubjectDN(cacert).equals(CertTools.stringToBCDNString(ca.getSubjectDN()))) {
                        String msg = intres.getLocalizedMessage("caadmin.errorcertrespwrongdn", CertTools.getSubjectDN(cacert), ca.getSubjectDN());
                        logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg);
                        throw new EjbcaException(msg);
                    }

                    ArrayList<Certificate> tmpchain = new ArrayList<Certificate>();
                    tmpchain.add(cacert);
                    // If we have a chain given as parameter, we will use that.
                    // If no parameter is given we assume that the request chain
                    // was stored when the request was created.
                    Collection<Certificate> reqchain = null;
                    if ((cachain != null) && (cachain.size() > 0)) {
                        reqchain = CertTools.createCertChain(cachain);
                        log.debug("Using CA certificate chain from parameter of size: " + reqchain.size());
                    } else {
                        reqchain = ca.getRequestCertificateChain();
                        log.debug("Using pre-stored CA certificate chain.");
                        if (reqchain == null) {
                            String msg = intres.getLocalizedMessage("caadmin.errornorequestchain", caid, ca.getSubjectDN());
                            log.info(msg);
                            throw new CertPathValidatorException(msg);
                        }
                    }
                    log.debug("Picked up request certificate chain of size: " + reqchain.size());
                    tmpchain.addAll(reqchain);
                    Collection<Certificate> chain = CertTools.createCertChain(tmpchain);
                    log.debug("Storing certificate chain of size: " + chain.size());
                    // Before importing the certificate we want to make sure
                    // that the public key matches the CAs private key
                    CATokenContainer catoken = ca.getCAToken();
                    // If it is a DV certificate signed by a CVCA, enrich the
                    // public key for EC parameters from the CVCA's certificate
                    PublicKey pk = cacert.getPublicKey();
                    if (StringUtils.equals(cacert.getType(), "CVC")) {
                        if (pk.getAlgorithm().equals("ECDSA")) {
                            CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cacert;
                            try {
                                if ((cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate().getAuthorizationField().getRole() == AuthorizationRoleEnum.DV_D)
                                        || (cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate().getAuthorizationField().getRole() == AuthorizationRoleEnum.DV_F)) {
                                    log.debug("Enriching DV public key with EC parameters from CVCA");
                                    Certificate cvcacert = (Certificate) reqchain.iterator().next();
                                    pk = KeyTools.getECPublicKeyWithParams(pk, cvcacert.getPublicKey());
                                }
                            } catch (InvalidKeySpecException e) {
                                log.debug("Strange CVCA certificate that we can't get the key from, continuing anyway...", e);
                            } catch (NoSuchFieldException e) {
                                log.debug("Strange DV certificate with no AutheorizationRole, continuing anyway...", e);
                            }
                        } else {
                            log.debug("Key is not ECDSA, don't try to enrich with EC parameters.");
                        }
                    } else {
                        log.debug("Cert is not CVC, no need to enrich with EC parameters.");
                    }
                    try {
                        KeyTools.testKey(catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), pk, catoken.getProvider());
                    } catch (Exception e1) {
                        log.debug("The received certificate response does not match the CAs private signing key for purpose CAKEYPURPOSE_CERTSIGN, trying CAKEYPURPOSE_CERTSIGN_NEXT...");
                        if (e1 instanceof InvalidKeyException) {
                            log.trace(e1);
                        } else {
                            // If it's not invalid key, we want to see more of
                            // the error
                            log.debug("Error: ", e1);
                        }
                        try {
                            KeyTools.testKey(catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN_NEXT), pk, catoken.getProvider());
                            // This was OK, so we must also activate the next
                            // signing key when importing this certificate
                            catoken.activateNextSignKey(tokenAuthenticationCode);
                            ca.setCAToken(catoken);
                            // In order to generate a certificate with this
                            // keystore we must make sure it is activated
                            ca.getCAToken().activate(tokenAuthenticationCode);
                        } catch (Exception e2) {
                            log.debug("The received certificate response does not match the CAs private signing key for purpose CAKEYPURPOSE_CERTSIGN_NEXT either, giving up.");
                            if ((e2 instanceof InvalidKeyException) || (e2 instanceof IllegalArgumentException)) {
                                log.trace(e2);
                            } else {
                                // If it's not invalid key or missing authentication code,
                                // we want to see more of the error
                                log.debug("Error: ", e2);
                            }
                            throw new EjbcaException(ErrorCode.INVALID_KEY, e2);
                        }
                    }
                    ca.setCertificateChain(chain);

                    // Publish CA Certificate
                    publishCACertificate(admin, chain, ca.getCRLPublishers(), ca.getSubjectDN());

                    // Set status to active, so we can sign certificates for the
                    // external services below.
                    cadata.setStatus(SecConst.CA_ACTIVE);
                    ca.setStatus(SecConst.CA_ACTIVE);

                    // activate External CA Services
                    Iterator<Integer> iter = ca.getExternalCAServiceTypes().iterator();
                    while (iter.hasNext()) {
                        int type = iter.next().intValue();
                        try {
                            ca.initExternalService(type, ca);
                            ArrayList<Certificate> extcacertificate = new ArrayList<Certificate>();
                            ExtendedCAServiceInfo info = null;
                            if (type == ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE) {
                                info = (OCSPCAServiceInfo) ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_OCSPEXTENDEDSERVICE);
                                // The OCSP certificate is the same as the
                                // singing certificate
                            }
                            if (type == ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE) {
                                info = ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_XKMSEXTENDEDSERVICE);
                                extcacertificate.add(((XKMSCAServiceInfo) info).getXKMSSignerCertificatePath().get(0));
                            }
                            if (type == ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE) {
                                info = ca.getExtendedCAServiceInfo(ExtendedCAServiceInfo.TYPE_CMSEXTENDEDSERVICE);
                                extcacertificate.add(((CmsCAServiceInfo) info).getCertificatePath().get(0));
                            }
                            // Publish the extended service certificate, but
                            // only for active services
                            if ((info != null) && (info.getStatus() == ExtendedCAServiceInfo.STATUS_ACTIVE) && (!extcacertificate.isEmpty())) {
                                publishCACertificate(admin, extcacertificate, ca.getCRLPublishers(), ca.getSubjectDN());
                            }
                        } catch (CATokenOfflineException e) {
                            String msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", Integer.valueOf(caid));
                            logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null,
                                    LogConstants.EVENT_ERROR_CACREATED, msg, e);
                            throw e;
                        } catch (Exception fe) {
                            String msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", Integer.valueOf(caid));
                            logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null,
                                    LogConstants.EVENT_ERROR_CACREATED, msg, fe);
                            throw new EJBException(fe);
                        }
                    }

                    // Set expire time
                    ca.setExpireTime(CertTools.getNotAfter(cacert));
                    cadata.setExpireTime(CertTools.getNotAfter(cacert).getTime());
                    // Save CA
                    cadata.setCA(ca);

                    // Create initial CRL
                    crlCreateSession.createCRLs(admin, ca, ca.getCAInfo());
                } else {
                    String msg = intres.getLocalizedMessage("caadmin.errorcreatecaservice", Integer.valueOf(caid));
                    // Cannot create certificate request for internal CA
                    logSession.log(admin, caid, LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg);
                    throw new EjbcaException(msg);
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);
                    certchain.addAll(rootcachain);

                    if (!processinternalca) {
                        // If this is an internal CA, we don't create it and set
                        // a NULL token, since the CA is already created
                        if (cainfo instanceof X509CAInfo) {
                            log.info("Creating a X509 CA (process request)");
                            ca = new X509CA((X509CAInfo) cainfo);
                        } else if (cainfo instanceof CVCCAInfo) {
                            // CVC CA is a special type of CA for EAC electronic
                            // passports
                            log.info("Creating a CVC CA (process request)");
                            CVCCAInfo cvccainfo = (CVCCAInfo) cainfo;
                            // Create CVCCA
                            ca = new CVCCA(cvccainfo);
                        } else {
                            ca = null;
                        }
                        ca.setCertificateChain(certchain);
                        CATokenContainer token = new CATokenContainerImpl(new NullCATokenInfo(), cainfo.getCAId());
                        ca.setCAToken(token);

                        // set status to active
                        entityManager.persist(new CAData(cainfo.getSubjectDN(), cainfo.getName(), SecConst.CA_EXTERNAL, ca));
                        //cadatahome.create(cainfo.getSubjectDN(), cainfo.getName(), SecConst.CA_EXTERNAL, ca);
                    } else {
                        if (oldcadata.getStatus() == SecConst.CA_EXTERNAL) {
                            // If it is an external CA we will not import the
                            // certificate later on here, so we want to
                            // update the CA in this instance with the new
                            // certificate so it is visible
                            ca = oldcadata.getCA();
                            ca.setCertificateChain(certchain);
                            if (log.isDebugEnabled()) {
                                log.debug("Storing new certificate chain for external CA " + cainfo.getName() + ", CA token type: "
                                        + ca.getCAToken().getCATokenType());
                            }
                            oldcadata.setCA(ca);
                        } else {
                            // If it is an internal CA so we are "simulating"
                            // signing a real external CA we don't do anything
                            // because that CA is waiting to import a
                            // certificate
                            if (log.isDebugEnabled()) {
                                log.debug("Not storing new certificate chain or updating CA for internal CA, simulating external: " + cainfo.getName());
                            }
                            ca = null;
                        }
                    }
                    // Publish CA certificates.
                    publishCACertificate(admin, certchain, signca.getCRLPublishers(), ca != null ? ca.getSubjectDN() : null);
                    // External CAs will not have any CRLs in this system, so we don't have to try to publish any CRLs
                } catch (CATokenOfflineException e) {
                    String msg = intres.getLocalizedMessage("caadmin.errorprocess", cainfo.getName());
                    log.error(msg, e);
                    logSession.log(admin, admin.getCaId(), LogConstants.MODULE_CA, new java.util.Date(), null, null, LogConstants.EVENT_ERROR_CAEDITED, msg, e);
View Full Code Here

    }

    @Override
    public void importCACertificate(Admin admin, String caname, Collection<Certificate> certificates) throws CreateException {
        Certificate caCertificate = (Certificate) certificates.iterator().next();
        CA ca = null;
        CAInfo cainfo = null;

        // Parameters common for both X509 and CVC CAs
        ArrayList<Integer> approvalsettings = new ArrayList<Integer>();
        int numofreqapprovals = 1;
        boolean finishuser = false;
        Collection<ExtendedCAServiceInfo> extendedcaserviceinfos = new ArrayList<ExtendedCAServiceInfo>();
        ArrayList<Integer> crlpublishers = new ArrayList<Integer>();
        long crlperiod = 0 * SimpleTime.MILLISECONDS_PER_HOUR;
        long crlIssueInterval = 0 * SimpleTime.MILLISECONDS_PER_HOUR;
        long crlOverlapTime = 10 * SimpleTime.MILLISECONDS_PER_HOUR;
        long deltacrlperiod = 0 * SimpleTime.MILLISECONDS_PER_HOUR;
        int certprofileid = CertTools.isSelfSigned(caCertificate) ? SecConst.CERTPROFILE_FIXED_ROOTCA : SecConst.CERTPROFILE_FIXED_SUBCA;
        String subjectdn = CertTools.getSubjectDN(caCertificate);
        int validity = 0;
        int signedby = CertTools.isSelfSigned(caCertificate) ? CAInfo.SELFSIGNED : CAInfo.SIGNEDBYEXTERNALCA;
        String description = "CA created by certificate import.";
        log.info("Preparing to import of CA with Subject DN " + subjectdn);

        if (caCertificate instanceof X509Certificate) {
            X509Certificate x509CaCertificate = (X509Certificate) caCertificate;
            String subjectaltname = null;
            try {
                subjectaltname = CertTools.getSubjectAlternativeName(x509CaCertificate);
            } catch (CertificateParsingException e) {
                log.error("", e);
            } catch (IOException e) {
                log.error("", e);
            }

            // Process certificate policies.
            ArrayList<CertificatePolicy> policies = new ArrayList<CertificatePolicy>();
            CertificateProfile certprof = certificateProfileSession.getCertificateProfile(admin, certprofileid);
            if (certprof.getCertificatePolicies() != null && certprof.getCertificatePolicies().size() > 0) {
                policies.addAll(certprof.getCertificatePolicies());
            }

            boolean useauthoritykeyidentifier = false;
            boolean authoritykeyidentifiercritical = false;

            boolean usecrlnumber = false;
            boolean crlnumbercritical = false;

            boolean useutf8policytext = false;
            boolean useprintablestringsubjectdn = false;
            boolean useldapdnorder = true; // Default value
            boolean usecrldistpointoncrl = false;
            boolean crldistpointoncrlcritical = false;

            cainfo = new X509CAInfo(subjectdn, caname, SecConst.CA_EXTERNAL, new Date(), subjectaltname, certprofileid, validity, CertTools
                    .getNotAfter(x509CaCertificate), CAInfo.CATYPE_X509, signedby, null, null, description, -1, null, policies, crlperiod, crlIssueInterval,
                    crlOverlapTime, deltacrlperiod, crlpublishers, useauthoritykeyidentifier, authoritykeyidentifiercritical, usecrlnumber, crlnumbercritical,
                    "", "", "", "", finishuser, extendedcaserviceinfos, useutf8policytext, approvalsettings, numofreqapprovals, useprintablestringsubjectdn,
                    useldapdnorder, usecrldistpointoncrl, crldistpointoncrlcritical, false, true, // isDoEnforceUniquePublicKeys
                    true, // isDoEnforceUniqueDistinguishedName
                    false, // isDoEnforceUniqueSubjectDNSerialnumber
                    true, // useCertReqHistory
                    true, // useUserStorage
                    true, // useCertificateStorage
                    null //cmpRaAuthSecret
            );
        } else if (StringUtils.equals(caCertificate.getType(), "CVC")) {
            cainfo = new CVCCAInfo(subjectdn, caname, 0, new Date(), certprofileid, validity, null, CAInfo.CATYPE_CVC, signedby, null, null, description, -1,
                    null, crlperiod, crlIssueInterval, crlOverlapTime, deltacrlperiod, crlpublishers, finishuser, extendedcaserviceinfos, approvalsettings,
                    numofreqapprovals, false, true, // isDoEnforceUniquePublicKeys
                    true, // isDoEnforceUniqueDistinguishedName
                    false, // isDoEnforceUniqueSubjectDNSerialnumber
                    true, // useCertReqHistory
                    true, // useUserStorage
                    true // useCertificateStorage
            );
        }
        if (cainfo instanceof X509CAInfo) {
            log.info("Creating a X509 CA (process request)");
            ca = new X509CA((X509CAInfo) cainfo);
        } else if (cainfo instanceof CVCCAInfo) {
            // CVC CA is a special type of CA for EAC electronic passports
            log.info("Creating a CVC CA (process request)");
            CVCCAInfo cvccainfo = (CVCCAInfo) cainfo;
            ca = new CVCCA(cvccainfo);
        }
        ca.setCertificateChain(certificates);
        CATokenContainer token = new CATokenContainerImpl(new NullCATokenInfo(), cainfo.getCAId());
        ca.setCAToken(token);
        // set status to active
        entityManager.persist(new CAData(cainfo.getSubjectDN(), cainfo.getName(), SecConst.CA_EXTERNAL, ca));
        // Publish CA certificates.
        publishCACertificate(admin, certificates, null, ca.getSubjectDN());
    }
View Full Code Here

            throw new AuthorizationDeniedException(msg);
        }

        // Get CA info.
        CAData cadata = CAData.findByIdOrThrow(entityManager, Integer.valueOf(caid));
        CA ca = cadata.getCA();
        if (ca.getStatus() == SecConst.CA_OFFLINE) {
          String msg = intres.getLocalizedMessage("error.catokenoffline", cadata.getName());
          throw new CATokenOfflineException(msg);
        }
        ArrayList<ExtendedCAServiceInfo> infos = new ArrayList<ExtendedCAServiceInfo>();
        infos.add(info);
View Full Code Here

TOP

Related Classes of org.ejbca.core.model.ca.caadmin.CA

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.