Search in sources :

Example 1 with ValidityMode

use of org.xipki.ca.server.mgmt.api.ValidityMode in project xipki by xipki.

the class X509Ca method createGrantedCertTemplate.

private GrantedCertTemplate createGrantedCertTemplate(CertTemplateData certTemplate, RequestorInfo requestor, boolean keyUpdate) throws OperationException {
    ParamUtil.requireNonNull("certTemplate", certTemplate);
    if (caInfo.getRevocationInfo() != null) {
        throw new OperationException(ErrorCode.NOT_PERMITTED, "CA is revoked");
    }
    IdentifiedX509Certprofile certprofile = getX509Certprofile(certTemplate.getCertprofileName());
    if (certprofile == null) {
        throw new OperationException(ErrorCode.UNKNOWN_CERT_PROFILE, "unknown cert profile " + certTemplate.getCertprofileName());
    }
    ConcurrentContentSigner signer = caInfo.getSigner(certprofile.getSignatureAlgorithms());
    if (signer == null) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CA does not support any signature algorithm restricted by the cert profile");
    }
    final NameId certprofileIdent = certprofile.getIdent();
    if (certprofile.getVersion() != X509CertVersion.v3) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, "unknown cert version " + certprofile.getVersion());
    }
    if (certprofile.isOnlyForRa()) {
        if (requestor == null || !requestor.isRa()) {
            throw new OperationException(ErrorCode.NOT_PERMITTED, "profile " + certprofileIdent + " not applied to non-RA");
        }
    }
    X500Name requestedSubject = removeEmptyRdns(certTemplate.getSubject());
    if (!certprofile.isSerialNumberInReqPermitted()) {
        RDN[] rdns = requestedSubject.getRDNs(ObjectIdentifiers.DN_SN);
        if (rdns != null && rdns.length > 0) {
            throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "subjectDN SerialNumber in request is not permitted");
        }
    }
    Date now = new Date();
    Date reqNotBefore;
    if (certTemplate.getNotBefore() != null && certTemplate.getNotBefore().after(now)) {
        reqNotBefore = certTemplate.getNotBefore();
    } else {
        reqNotBefore = now;
    }
    Date grantedNotBefore = certprofile.getNotBefore(reqNotBefore);
    // notBefore in the past is not permitted
    if (grantedNotBefore.before(now)) {
        grantedNotBefore = now;
    }
    if (certprofile.hasMidnightNotBefore()) {
        grantedNotBefore = setToMidnight(grantedNotBefore, certprofile.getTimezone());
    }
    if (grantedNotBefore.before(caInfo.getNotBefore())) {
        grantedNotBefore = caInfo.getNotBefore();
        if (certprofile.hasMidnightNotBefore()) {
            grantedNotBefore = setToMidnight(grantedNotBefore, certprofile.getTimezone());
        }
    }
    long time = caInfo.getNoNewCertificateAfter();
    if (grantedNotBefore.getTime() > time) {
        throw new OperationException(ErrorCode.NOT_PERMITTED, "CA is not permitted to issue certifate after " + new Date(time));
    }
    SubjectPublicKeyInfo grantedPublicKeyInfo;
    try {
        grantedPublicKeyInfo = X509Util.toRfc3279Style(certTemplate.getPublicKeyInfo());
    } catch (InvalidKeySpecException ex) {
        LogUtil.warn(LOG, ex, "invalid SubjectPublicKeyInfo");
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid SubjectPublicKeyInfo");
    }
    // public key
    try {
        grantedPublicKeyInfo = certprofile.checkPublicKey(grantedPublicKeyInfo);
    } catch (BadCertTemplateException ex) {
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
    }
    // CHECK weak public key, like RSA key (ROCA)
    if (grantedPublicKeyInfo.getAlgorithm().getAlgorithm().equals(PKCSObjectIdentifiers.rsaEncryption)) {
        try {
            ASN1Sequence seq = ASN1Sequence.getInstance(grantedPublicKeyInfo.getPublicKeyData().getOctets());
            if (seq.size() != 2) {
                throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid format of RSA public key");
            }
            BigInteger modulus = ASN1Integer.getInstance(seq.getObjectAt(0)).getPositiveValue();
            if (RSABrokenKey.isAffected(modulus)) {
                throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "RSA public key is too weak");
            }
        } catch (IllegalArgumentException ex) {
            throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid format of RSA public key");
        }
    }
    Date gsmckFirstNotBefore = null;
    if (certprofile.getspecialCertprofileBehavior() == SpecialX509CertprofileBehavior.gematik_gSMC_K) {
        gsmckFirstNotBefore = grantedNotBefore;
        RDN[] cnRdns = requestedSubject.getRDNs(ObjectIdentifiers.DN_CN);
        if (cnRdns != null && cnRdns.length > 0) {
            String requestedCn = X509Util.rdnValueToString(cnRdns[0].getFirst().getValue());
            Long gsmckFirstNotBeforeInSecond = certstore.getNotBeforeOfFirstCertStartsWithCommonName(requestedCn, certprofileIdent);
            if (gsmckFirstNotBeforeInSecond != null) {
                gsmckFirstNotBefore = new Date(gsmckFirstNotBeforeInSecond * MS_PER_SECOND);
            }
            // append the commonName with '-' + yyyyMMdd
            SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMdd");
            dateF.setTimeZone(new SimpleTimeZone(0, "Z"));
            String yyyyMMdd = dateF.format(gsmckFirstNotBefore);
            String suffix = "-" + yyyyMMdd;
            // append the -yyyyMMdd to the commonName
            RDN[] rdns = requestedSubject.getRDNs();
            for (int i = 0; i < rdns.length; i++) {
                if (ObjectIdentifiers.DN_CN.equals(rdns[i].getFirst().getType())) {
                    rdns[i] = new RDN(ObjectIdentifiers.DN_CN, new DERUTF8String(requestedCn + suffix));
                }
            }
            requestedSubject = new X500Name(rdns);
        }
    // end if
    }
    // end if
    // subject
    SubjectInfo subjectInfo;
    try {
        subjectInfo = certprofile.getSubject(requestedSubject);
    } catch (CertprofileException ex) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, "exception in cert profile " + certprofileIdent);
    } catch (BadCertTemplateException ex) {
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex);
    }
    X500Name grantedSubject = subjectInfo.getGrantedSubject();
    // make sure that empty subject is not permitted
    ASN1ObjectIdentifier[] attrTypes = grantedSubject.getAttributeTypes();
    if (attrTypes == null || attrTypes.length == 0) {
        throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "empty subject is not permitted");
    }
    // make sure that the grantedSubject does not equal the CA's subject
    if (X509Util.canonicalizName(grantedSubject).equals(caInfo.getPublicCaInfo().getC14nSubject())) {
        throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate with the same subject as CA is not allowed");
    }
    boolean duplicateKeyPermitted = caInfo.isDuplicateKeyPermitted();
    if (duplicateKeyPermitted && !certprofile.isDuplicateKeyPermitted()) {
        duplicateKeyPermitted = false;
    }
    byte[] subjectPublicKeyData = grantedPublicKeyInfo.getPublicKeyData().getBytes();
    long fpPublicKey = FpIdCalculator.hash(subjectPublicKeyData);
    if (keyUpdate) {
        CertStatus certStatus = certstore.getCertStatusForSubject(caIdent, grantedSubject);
        if (certStatus == CertStatus.REVOKED) {
            throw new OperationException(ErrorCode.CERT_REVOKED);
        } else if (certStatus == CertStatus.UNKNOWN) {
            throw new OperationException(ErrorCode.UNKNOWN_CERT);
        }
    } else {
        if (!duplicateKeyPermitted) {
            if (certstore.isCertForKeyIssued(caIdent, fpPublicKey)) {
                throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given public key already issued");
            }
        }
    // duplicateSubject check will be processed later
    }
    // end if(keyUpdate)
    StringBuilder msgBuilder = new StringBuilder();
    if (subjectInfo.getWarning() != null) {
        msgBuilder.append(", ").append(subjectInfo.getWarning());
    }
    CertValidity validity = certprofile.getValidity();
    if (validity == null) {
        validity = caInfo.getMaxValidity();
    } else if (validity.compareTo(caInfo.getMaxValidity()) > 0) {
        validity = caInfo.getMaxValidity();
    }
    Date maxNotAfter = validity.add(grantedNotBefore);
    if (maxNotAfter.getTime() > MAX_CERT_TIME_MS) {
        maxNotAfter = new Date(MAX_CERT_TIME_MS);
    }
    // CHECKSTYLE:SKIP
    Date origMaxNotAfter = maxNotAfter;
    if (certprofile.getspecialCertprofileBehavior() == SpecialX509CertprofileBehavior.gematik_gSMC_K) {
        String str = certprofile.setParameter(SpecialX509CertprofileBehavior.PARAMETER_MAXLIFTIME);
        long maxLifetimeInDays = Long.parseLong(str);
        Date maxLifetime = new Date(gsmckFirstNotBefore.getTime() + maxLifetimeInDays * DAY_IN_MS - MS_PER_SECOND);
        if (maxNotAfter.after(maxLifetime)) {
            maxNotAfter = maxLifetime;
        }
    }
    Date grantedNotAfter = certTemplate.getNotAfter();
    if (grantedNotAfter != null) {
        if (grantedNotAfter.after(maxNotAfter)) {
            grantedNotAfter = maxNotAfter;
            msgBuilder.append(", notAfter modified");
        }
    } else {
        grantedNotAfter = maxNotAfter;
    }
    if (grantedNotAfter.after(caInfo.getNotAfter())) {
        ValidityMode mode = caInfo.getValidityMode();
        if (mode == ValidityMode.CUTOFF) {
            grantedNotAfter = caInfo.getNotAfter();
        } else if (mode == ValidityMode.STRICT) {
            throw new OperationException(ErrorCode.NOT_PERMITTED, "notAfter outside of CA's validity is not permitted");
        } else if (mode == ValidityMode.LAX) {
        // permitted
        } else {
            throw new RuntimeException("should not reach here, unknown CA ValidityMode " + mode);
        }
    // end if (mode)
    }
    if (certprofile.hasMidnightNotBefore() && !maxNotAfter.equals(origMaxNotAfter)) {
        Calendar cal = Calendar.getInstance(certprofile.getTimezone());
        cal.setTime(new Date(grantedNotAfter.getTime() - DAY_IN_MS));
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 0);
        grantedNotAfter = cal.getTime();
    }
    String warning = null;
    if (msgBuilder.length() > 2) {
        warning = msgBuilder.substring(2);
    }
    GrantedCertTemplate gct = new GrantedCertTemplate(certTemplate.getExtensions(), certprofile, grantedNotBefore, grantedNotAfter, requestedSubject, grantedPublicKeyInfo, fpPublicKey, subjectPublicKeyData, signer, warning);
    gct.setGrantedSubject(grantedSubject);
    return gct;
}
Also used : DERUTF8String(org.bouncycastle.asn1.DERUTF8String) NameId(org.xipki.ca.api.NameId) CertValidity(org.xipki.ca.api.profile.CertValidity) X500Name(org.bouncycastle.asn1.x500.X500Name) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) ValidityMode(org.xipki.ca.server.mgmt.api.ValidityMode) SimpleTimeZone(java.util.SimpleTimeZone) CertprofileException(org.xipki.ca.api.profile.CertprofileException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) RDN(org.bouncycastle.asn1.x500.RDN) OperationException(org.xipki.ca.api.OperationException) Calendar(java.util.Calendar) SubjectInfo(org.xipki.ca.api.profile.x509.SubjectInfo) Date(java.util.Date) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) ConcurrentContentSigner(org.xipki.security.ConcurrentContentSigner) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) BadCertTemplateException(org.xipki.ca.api.BadCertTemplateException) BigInteger(java.math.BigInteger) SimpleDateFormat(java.text.SimpleDateFormat) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 2 with ValidityMode

use of org.xipki.ca.server.mgmt.api.ValidityMode in project xipki by xipki.

the class CaUpdateCmd method getChangeCaEntry.

protected X509ChangeCaEntry getChangeCaEntry() throws Exception {
    X509ChangeCaEntry entry = new X509ChangeCaEntry(new NameId(null, caName));
    if (snBitLen != null) {
        ParamUtil.requireRange("sn-bitlen", snBitLen, 63, 159);
        entry.setSerialNoBitLen(snBitLen);
    }
    if (caStatus != null) {
        entry.setStatus(CaStatus.forName(caStatus));
    }
    if (expirationPeriod != null && expirationPeriod < 0) {
        throw new IllegalCmdParamException("invalid expirationPeriod: " + expirationPeriod);
    } else {
        entry.setExpirationPeriod(expirationPeriod);
    }
    if (keepExpiredCertInDays != null) {
        entry.setKeepExpiredCertInDays(keepExpiredCertInDays);
    }
    if (certFile != null) {
        entry.setCert(X509Util.parseCert(certFile));
    }
    if (signerConf != null) {
        String tmpSignerType = signerType;
        if (tmpSignerType == null) {
            CaEntry caEntry = caManager.getCa(caName);
            if (caEntry == null) {
                throw new IllegalCmdParamException("please specify the signerType");
            }
            tmpSignerType = caEntry.getSignerType();
        }
        signerConf = ShellUtil.canonicalizeSignerConf(tmpSignerType, signerConf, passwordResolver, securityFactory);
        entry.setSignerConf(signerConf);
    }
    if (duplicateKeyS != null) {
        boolean permitted = isEnabled(duplicateKeyS, true, "duplicate-key");
        entry.setDuplicateKeyPermitted(permitted);
    }
    if (duplicateSubjectS != null) {
        boolean permitted = isEnabled(duplicateSubjectS, true, "duplicate-subject");
        entry.setDuplicateSubjectPermitted(permitted);
    }
    if (saveReqS != null) {
        boolean saveReq = isEnabled(saveReqS, true, "save-req");
        entry.setSaveRequest(saveReq);
    }
    if (CollectionUtil.isNonEmpty(permissions)) {
        int intPermission = ShellUtil.getPermission(permissions);
        entry.setPermission(intPermission);
    }
    entry.setCrlUris(getUris(crlUris));
    entry.setDeltaCrlUris(getUris(deltaCrlUris));
    entry.setOcspUris(getUris(ocspUris));
    entry.setCaCertUris(getUris(caCertUris));
    if (validityModeS != null) {
        ValidityMode validityMode = ValidityMode.forName(validityModeS);
        entry.setValidityMode(validityMode);
    }
    if (maxValidity != null) {
        entry.setMaxValidity(CertValidity.getInstance(maxValidity));
    }
    if (crlSignerName != null) {
        entry.setCrlSignerName(crlSignerName);
    }
    if (cmpControlName != null) {
        entry.setCmpControlName(cmpControlName);
    }
    if (responderName != null) {
        entry.setResponderName(responderName);
    }
    if (extraControl != null) {
        entry.setExtraControl(new ConfPairs(extraControl).unmodifiable());
    }
    if (numCrls != null) {
        entry.setNumCrls(numCrls);
    }
    return entry;
}
Also used : X509ChangeCaEntry(org.xipki.ca.server.mgmt.api.x509.X509ChangeCaEntry) CaEntry(org.xipki.ca.server.mgmt.api.CaEntry) ValidityMode(org.xipki.ca.server.mgmt.api.ValidityMode) NameId(org.xipki.ca.api.NameId) IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) ConfPairs(org.xipki.common.ConfPairs) X509ChangeCaEntry(org.xipki.ca.server.mgmt.api.x509.X509ChangeCaEntry)

Example 3 with ValidityMode

use of org.xipki.ca.server.mgmt.api.ValidityMode in project xipki by xipki.

the class CaAddOrGenAction method getCaEntry.

protected X509CaEntry getCaEntry() throws Exception {
    ParamUtil.requireRange("sn-bitlen", snBitLen, 63, 159);
    if (nextCrlNumber < 1) {
        throw new IllegalCmdParamException("invalid CRL number: " + nextCrlNumber);
    }
    if (numCrls < 0) {
        throw new IllegalCmdParamException("invalid numCrls: " + numCrls);
    }
    if (expirationPeriod < 0) {
        throw new IllegalCmdParamException("invalid expirationPeriod: " + expirationPeriod);
    }
    if ("PKCS12".equalsIgnoreCase(signerType) || "JKS".equalsIgnoreCase(signerType)) {
        signerConf = ShellUtil.canonicalizeSignerConf(signerType, signerConf, passwordResolver, securityFactory);
    }
    X509CaUris caUris = new X509CaUris(caCertUris, ocspUris, crlUris, deltaCrlUris);
    X509CaEntry entry = new X509CaEntry(new NameId(null, caName), snBitLen, nextCrlNumber, signerType, signerConf, caUris, numCrls.intValue(), expirationPeriod.intValue());
    entry.setKeepExpiredCertInDays(keepExpiredCertInDays.intValue());
    boolean duplicateKeyPermitted = isEnabled(duplicateKeyS, true, "duplicate-key");
    entry.setDuplicateKeyPermitted(duplicateKeyPermitted);
    boolean duplicateSubjectPermitted = isEnabled(duplicateSubjectS, true, "duplicate-subject");
    entry.setDuplicateSubjectPermitted(duplicateSubjectPermitted);
    boolean saveReq = isEnabled(saveReqS, false, "save-req");
    entry.setSaveRequest(saveReq);
    ValidityMode validityMode = ValidityMode.forName(validityModeS);
    entry.setValidityMode(validityMode);
    CaStatus status = CaStatus.forName(caStatus);
    entry.setStatus(status);
    if (crlSignerName != null) {
        entry.setCrlSignerName(crlSignerName);
    }
    if (responderName != null) {
        entry.setResponderName(responderName);
    }
    CertValidity tmpMaxValidity = CertValidity.getInstance(maxValidity);
    entry.setMaxValidity(tmpMaxValidity);
    entry.setKeepExpiredCertInDays(keepExpiredCertInDays);
    if (cmpControlName != null) {
        entry.setCmpControlName(cmpControlName);
    }
    int intPermission = ShellUtil.getPermission(permissions);
    entry.setPermission(intPermission);
    if (extraControl != null) {
        extraControl = extraControl.trim();
    }
    if (StringUtil.isNotBlank(extraControl)) {
        entry.setExtraControl(new ConfPairs(extraControl).unmodifiable());
    }
    return entry;
}
Also used : X509CaUris(org.xipki.ca.server.mgmt.api.x509.X509CaUris) ValidityMode(org.xipki.ca.server.mgmt.api.ValidityMode) NameId(org.xipki.ca.api.NameId) CertValidity(org.xipki.ca.api.profile.CertValidity) IllegalCmdParamException(org.xipki.console.karaf.IllegalCmdParamException) ConfPairs(org.xipki.common.ConfPairs) CaStatus(org.xipki.ca.server.mgmt.api.CaStatus) X509CaEntry(org.xipki.ca.server.mgmt.api.x509.X509CaEntry)

Example 4 with ValidityMode

use of org.xipki.ca.server.mgmt.api.ValidityMode in project xipki by xipki.

the class CaManagerQueryExecutor method changeCa.

// method addPublisherToCa
void changeCa(ChangeCaEntry changeCaEntry, SecurityFactory securityFactory) throws CaMgmtException {
    ParamUtil.requireNonNull("changeCaEntry", changeCaEntry);
    ParamUtil.requireNonNull("securityFactory", securityFactory);
    if (!(changeCaEntry instanceof X509ChangeCaEntry)) {
        throw new CaMgmtException("unsupported ChangeCAEntry " + changeCaEntry.getClass().getName());
    }
    X509ChangeCaEntry entry = (X509ChangeCaEntry) changeCaEntry;
    X509Certificate cert = entry.getCert();
    if (cert != null) {
        boolean anyCertIssued;
        try {
            anyCertIssued = datasource.columnExists(null, "CERT", "CA_ID", entry.getIdent().getId());
        } catch (DataAccessException ex) {
            throw new CaMgmtException(ex);
        }
        if (anyCertIssued) {
            throw new CaMgmtException("Cannot change the certificate of CA, since it has issued certificates");
        }
    }
    Integer serialNoBitLen = entry.getSerialNoBitLen();
    CaStatus status = entry.getStatus();
    List<String> crlUris = entry.getCrlUris();
    List<String> deltaCrlUris = entry.getDeltaCrlUris();
    List<String> ocspUris = entry.getOcspUris();
    List<String> caCertUris = entry.getCaCertUris();
    CertValidity maxValidity = entry.getMaxValidity();
    String signerType = entry.getSignerType();
    String signerConf = entry.getSignerConf();
    String crlsignerName = entry.getCrlSignerName();
    String responderName = entry.getResponderName();
    String cmpcontrolName = entry.getCmpControlName();
    Boolean duplicateKeyPermitted = entry.getDuplicateKeyPermitted();
    Boolean duplicateSubjectPermitted = entry.getDuplicateSubjectPermitted();
    Boolean saveReq = entry.getSaveRequest();
    Integer permission = entry.getPermission();
    Integer numCrls = entry.getNumCrls();
    Integer expirationPeriod = entry.getExpirationPeriod();
    Integer keepExpiredCertInDays = entry.getKeepExpiredCertInDays();
    ValidityMode validityMode = entry.getValidityMode();
    ConfPairs extraControl = entry.getExtraControl();
    if (signerType != null || signerConf != null || cert != null) {
        final String sql = "SELECT SIGNER_TYPE,CERT,SIGNER_CONF FROM CA WHERE ID=?";
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            stmt = prepareStatement(sql);
            stmt.setInt(1, entry.getIdent().getId());
            rs = stmt.executeQuery();
            if (!rs.next()) {
                throw new CaMgmtException("unknown CA '" + entry.getIdent());
            }
            String tmpSignerType = rs.getString("SIGNER_TYPE");
            String tmpSignerConf = rs.getString("SIGNER_CONF");
            String tmpB64Cert = rs.getString("CERT");
            if (signerType != null) {
                tmpSignerType = signerType;
            }
            if (signerConf != null) {
                tmpSignerConf = getRealString(signerConf);
                if (tmpSignerConf != null) {
                    tmpSignerConf = CaManagerImpl.canonicalizeSignerConf(tmpSignerType, tmpSignerConf, null, securityFactory);
                }
            }
            X509Certificate tmpCert;
            if (cert != null) {
                tmpCert = cert;
            } else {
                try {
                    tmpCert = X509Util.parseBase64EncodedCert(tmpB64Cert);
                } catch (CertificateException ex) {
                    throw new CaMgmtException("could not parse the stored certificate for CA '" + changeCaEntry.getIdent() + "'" + ex.getMessage(), ex);
                }
            }
            try {
                List<String[]> signerConfs = CaEntry.splitCaSignerConfs(tmpSignerConf);
                for (String[] m : signerConfs) {
                    securityFactory.createSigner(tmpSignerType, new SignerConf(m[1]), tmpCert);
                }
            } catch (XiSecurityException | ObjectCreationException ex) {
                throw new CaMgmtException("could not create signer for CA '" + changeCaEntry.getIdent() + "'" + ex.getMessage(), ex);
            }
        } catch (SQLException ex) {
            throw new CaMgmtException(datasource, sql, ex);
        } finally {
            datasource.releaseResources(stmt, rs);
        }
    }
    // end if (signerType)
    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("UPDATE CA SET ");
    AtomicInteger index = new AtomicInteger(1);
    Integer idxSnSize = addToSqlIfNotNull(sqlBuilder, index, serialNoBitLen, "SN_SIZE");
    Integer idxStatus = addToSqlIfNotNull(sqlBuilder, index, status, "STATUS");
    Integer idxSubject = addToSqlIfNotNull(sqlBuilder, index, cert, "SUBJECT");
    Integer idxCert = addToSqlIfNotNull(sqlBuilder, index, cert, "CERT");
    Integer idxCrlUris = addToSqlIfNotNull(sqlBuilder, index, crlUris, "CRL_URIS");
    Integer idxDeltaCrlUris = addToSqlIfNotNull(sqlBuilder, index, deltaCrlUris, "DELTACRL_URIS");
    Integer idxOcspUris = addToSqlIfNotNull(sqlBuilder, index, ocspUris, "OCSP_URIS");
    Integer idxCaCertUris = addToSqlIfNotNull(sqlBuilder, index, caCertUris, "CACERT_URIS");
    Integer idxMaxValidity = addToSqlIfNotNull(sqlBuilder, index, maxValidity, "MAX_VALIDITY");
    Integer idxSignerType = addToSqlIfNotNull(sqlBuilder, index, signerType, "SIGNER_TYPE");
    Integer idxCrlsignerName = addToSqlIfNotNull(sqlBuilder, index, crlsignerName, "CRLSIGNER_NAME");
    Integer idxResponderName = addToSqlIfNotNull(sqlBuilder, index, responderName, "RESPONDER_NAME");
    Integer idxCmpcontrolName = addToSqlIfNotNull(sqlBuilder, index, cmpcontrolName, "CMPCONTROL_NAME");
    Integer idxDuplicateKey = addToSqlIfNotNull(sqlBuilder, index, duplicateKeyPermitted, "DUPLICATE_KEY");
    Integer idxDuplicateSubject = addToSqlIfNotNull(sqlBuilder, index, duplicateKeyPermitted, "DUPLICATE_SUBJECT");
    Integer idxSaveReq = addToSqlIfNotNull(sqlBuilder, index, saveReq, "SAVE_REQ");
    Integer idxPermission = addToSqlIfNotNull(sqlBuilder, index, permission, "PERMISSION");
    Integer idxNumCrls = addToSqlIfNotNull(sqlBuilder, index, numCrls, "NUM_CRLS");
    Integer idxExpirationPeriod = addToSqlIfNotNull(sqlBuilder, index, expirationPeriod, "EXPIRATION_PERIOD");
    Integer idxExpiredCerts = addToSqlIfNotNull(sqlBuilder, index, keepExpiredCertInDays, "KEEP_EXPIRED_CERT_DAYS");
    Integer idxValidityMode = addToSqlIfNotNull(sqlBuilder, index, validityMode, "VALIDITY_MODE");
    Integer idxExtraControl = addToSqlIfNotNull(sqlBuilder, index, extraControl, "EXTRA_CONTROL");
    Integer idxSignerConf = addToSqlIfNotNull(sqlBuilder, index, signerConf, "SIGNER_CONF");
    // delete the last ','
    sqlBuilder.deleteCharAt(sqlBuilder.length() - 1);
    sqlBuilder.append(" WHERE ID=?");
    if (index.get() == 1) {
        throw new IllegalArgumentException("nothing to change");
    }
    int idxId = index.get();
    final String sql = sqlBuilder.toString();
    StringBuilder sb = new StringBuilder();
    PreparedStatement ps = null;
    try {
        ps = prepareStatement(sql);
        if (idxSnSize != null) {
            sb.append("sn_size: '").append(serialNoBitLen).append("'; ");
            ps.setInt(idxSnSize, serialNoBitLen.intValue());
        }
        if (idxStatus != null) {
            sb.append("status: '").append(status.name()).append("'; ");
            ps.setString(idxStatus, status.name());
        }
        if (idxCert != null) {
            String subject = X509Util.getRfc4519Name(cert.getSubjectX500Principal());
            sb.append("cert: '").append(subject).append("'; ");
            ps.setString(idxSubject, subject);
            String base64Cert = Base64.encodeToString(cert.getEncoded());
            ps.setString(idxCert, base64Cert);
        }
        if (idxCrlUris != null) {
            String txt = StringUtil.collectionAsStringByComma(crlUris);
            sb.append("crlUri: '").append(txt).append("'; ");
            ps.setString(idxCrlUris, txt);
        }
        if (idxDeltaCrlUris != null) {
            String txt = StringUtil.collectionAsStringByComma(deltaCrlUris);
            sb.append("deltaCrlUri: '").append(txt).append("'; ");
            ps.setString(idxDeltaCrlUris, txt);
        }
        if (idxOcspUris != null) {
            String txt = StringUtil.collectionAsStringByComma(ocspUris);
            sb.append("ocspUri: '").append(txt).append("'; ");
            ps.setString(idxOcspUris, txt);
        }
        if (idxCaCertUris != null) {
            String txt = StringUtil.collectionAsStringByComma(caCertUris);
            sb.append("caCertUri: '").append(txt).append("'; ");
            ps.setString(idxCaCertUris, txt);
        }
        if (idxMaxValidity != null) {
            String txt = maxValidity.toString();
            sb.append("maxValidity: '").append(txt).append("'; ");
            ps.setString(idxMaxValidity, txt);
        }
        if (idxSignerType != null) {
            sb.append("signerType: '").append(signerType).append("'; ");
            ps.setString(idxSignerType, signerType);
        }
        if (idxSignerConf != null) {
            sb.append("signerConf: '").append(SignerConf.toString(signerConf, false, true)).append("'; ");
            ps.setString(idxSignerConf, signerConf);
        }
        if (idxCrlsignerName != null) {
            String txt = getRealString(crlsignerName);
            sb.append("crlSigner: '").append(txt).append("'; ");
            ps.setString(idxCrlsignerName, txt);
        }
        if (idxResponderName != null) {
            String txt = getRealString(responderName);
            sb.append("responder: '").append(txt).append("'; ");
            ps.setString(idxResponderName, txt);
        }
        if (idxCmpcontrolName != null) {
            String txt = getRealString(cmpcontrolName);
            sb.append("cmpControl: '").append(txt).append("'; ");
            ps.setString(idxCmpcontrolName, txt);
        }
        if (idxDuplicateKey != null) {
            sb.append("duplicateKey: '").append(duplicateKeyPermitted).append("'; ");
            setBoolean(ps, idxDuplicateKey, duplicateKeyPermitted);
        }
        if (idxDuplicateSubject != null) {
            sb.append("duplicateSubject: '").append(duplicateSubjectPermitted).append("'; ");
            setBoolean(ps, idxDuplicateSubject, duplicateSubjectPermitted);
        }
        if (idxSaveReq != null) {
            sb.append("saveReq: '").append(saveReq).append("'; ");
            setBoolean(ps, idxSaveReq, saveReq);
        }
        if (idxPermission != null) {
            sb.append("permission: '").append(permission).append("'; ");
            ps.setInt(idxPermission, permission);
        }
        if (idxNumCrls != null) {
            sb.append("numCrls: '").append(numCrls).append("'; ");
            ps.setInt(idxNumCrls, numCrls);
        }
        if (idxExpirationPeriod != null) {
            sb.append("expirationPeriod: '").append(expirationPeriod).append("'; ");
            ps.setInt(idxExpirationPeriod, expirationPeriod);
        }
        if (idxExpiredCerts != null) {
            sb.append("keepExpiredCertDays: '").append(keepExpiredCertInDays).append("'; ");
            ps.setInt(idxExpiredCerts, keepExpiredCertInDays);
        }
        if (idxValidityMode != null) {
            String txt = validityMode.name();
            sb.append("validityMode: '").append(txt).append("'; ");
            ps.setString(idxValidityMode, txt);
        }
        if (idxExtraControl != null) {
            sb.append("extraControl: '").append(extraControl).append("'; ");
            ps.setString(idxExtraControl, extraControl.getEncoded());
        }
        ps.setInt(idxId, changeCaEntry.getIdent().getId());
        if (ps.executeUpdate() == 0) {
            throw new CaMgmtException("could not change CA " + entry.getIdent());
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1).deleteCharAt(sb.length() - 1);
        }
        LOG.info("changed CA '{}': {}", changeCaEntry.getIdent(), sb);
    } catch (SQLException ex) {
        throw new CaMgmtException(datasource, sql, ex);
    } catch (CertificateEncodingException ex) {
        throw new CaMgmtException(ex);
    } finally {
        datasource.releaseResources(ps, null);
    }
}
Also used : CertValidity(org.xipki.ca.api.profile.CertValidity) SQLException(java.sql.SQLException) CertificateException(java.security.cert.CertificateException) CaStatus(org.xipki.ca.server.mgmt.api.CaStatus) ValidityMode(org.xipki.ca.server.mgmt.api.ValidityMode) XiSecurityException(org.xipki.security.exception.XiSecurityException) ResultSet(java.sql.ResultSet) DataAccessException(org.xipki.datasource.DataAccessException) ConfPairs(org.xipki.common.ConfPairs) SignerConf(org.xipki.security.SignerConf) PreparedStatement(java.sql.PreparedStatement) CertificateEncodingException(java.security.cert.CertificateEncodingException) X509ChangeCaEntry(org.xipki.ca.server.mgmt.api.x509.X509ChangeCaEntry) X509Certificate(java.security.cert.X509Certificate) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CaMgmtException(org.xipki.ca.server.mgmt.api.CaMgmtException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ObjectCreationException(org.xipki.common.ObjectCreationException)

Example 5 with ValidityMode

use of org.xipki.ca.server.mgmt.api.ValidityMode in project xipki by xipki.

the class CaManagerQueryExecutor method createCaInfo.

// method createResponder
X509CaInfo createCaInfo(String name, boolean masterMode, CertificateStore certstore) throws CaMgmtException {
    final String sql = sqls.sqlSelectCa;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        stmt = prepareStatement(sql);
        stmt.setString(1, name);
        rs = stmt.executeQuery();
        if (!rs.next()) {
            throw new CaMgmtException("uknown CA " + name);
        }
        int artCode = rs.getInt("ART");
        if (artCode != CertArt.X509PKC.getCode()) {
            throw new CaMgmtException("CA " + name + " is not X509CA, and is not supported");
        }
        String crlUris = rs.getString("CRL_URIS");
        String deltaCrlUris = rs.getString("DELTACRL_URIS");
        CertRevocationInfo revocationInfo = null;
        boolean revoked = rs.getBoolean("REV");
        if (revoked) {
            int revReason = rs.getInt("RR");
            long revTime = rs.getInt("RT");
            long revInvalidityTime = rs.getInt("RIT");
            Date revInvTime = (revInvalidityTime == 0) ? null : new Date(revInvalidityTime * 1000);
            revocationInfo = new CertRevocationInfo(revReason, new Date(revTime * 1000), revInvTime);
        }
        List<String> tmpCrlUris = null;
        if (StringUtil.isNotBlank(crlUris)) {
            tmpCrlUris = StringUtil.splitByComma(crlUris);
        }
        List<String> tmpDeltaCrlUris = null;
        if (StringUtil.isNotBlank(deltaCrlUris)) {
            tmpDeltaCrlUris = StringUtil.splitByComma(deltaCrlUris);
        }
        String ocspUris = rs.getString("OCSP_URIS");
        List<String> tmpOcspUris = null;
        if (StringUtil.isNotBlank(ocspUris)) {
            tmpOcspUris = StringUtil.splitByComma(ocspUris);
        }
        String caCertUris = rs.getString("CACERT_URIS");
        List<String> tmpCaCertUris = null;
        if (StringUtil.isNotBlank(caCertUris)) {
            tmpCaCertUris = StringUtil.splitByComma(caCertUris);
        }
        X509CaUris caUris = new X509CaUris(tmpCaCertUris, tmpOcspUris, tmpCrlUris, tmpDeltaCrlUris);
        int id = rs.getInt("ID");
        int serialNoSize = rs.getInt("SN_SIZE");
        long nextCrlNo = rs.getLong("NEXT_CRLNO");
        String signerType = rs.getString("SIGNER_TYPE");
        String signerConf = rs.getString("SIGNER_CONF");
        int numCrls = rs.getInt("NUM_CRLS");
        int expirationPeriod = rs.getInt("EXPIRATION_PERIOD");
        X509CaEntry entry = new X509CaEntry(new NameId(id, name), serialNoSize, nextCrlNo, signerType, signerConf, caUris, numCrls, expirationPeriod);
        String b64cert = rs.getString("CERT");
        X509Certificate cert = generateCert(b64cert);
        entry.setCert(cert);
        String status = rs.getString("STATUS");
        CaStatus caStatus = CaStatus.forName(status);
        entry.setStatus(caStatus);
        String maxValidityS = rs.getString("MAX_VALIDITY");
        CertValidity maxValidity = CertValidity.getInstance(maxValidityS);
        entry.setMaxValidity(maxValidity);
        int keepExpiredCertDays = rs.getInt("KEEP_EXPIRED_CERT_DAYS");
        entry.setKeepExpiredCertInDays(keepExpiredCertDays);
        String crlsignerName = rs.getString("CRLSIGNER_NAME");
        if (StringUtil.isNotBlank(crlsignerName)) {
            entry.setCrlSignerName(crlsignerName);
        }
        String responderName = rs.getString("RESPONDER_NAME");
        if (StringUtil.isNotBlank(responderName)) {
            entry.setResponderName(responderName);
        }
        String extraControl = rs.getString("EXTRA_CONTROL");
        if (StringUtil.isNotBlank(extraControl)) {
            entry.setExtraControl(new ConfPairs(extraControl).unmodifiable());
        }
        String cmpcontrolName = rs.getString("CMPCONTROL_NAME");
        if (StringUtil.isNotBlank(cmpcontrolName)) {
            entry.setCmpControlName(cmpcontrolName);
        }
        boolean duplicateKeyPermitted = (rs.getInt("DUPLICATE_KEY") != 0);
        entry.setDuplicateKeyPermitted(duplicateKeyPermitted);
        boolean duplicateSubjectPermitted = (rs.getInt("DUPLICATE_SUBJECT") != 0);
        entry.setDuplicateSubjectPermitted(duplicateSubjectPermitted);
        boolean saveReq = (rs.getInt("SAVE_REQ") != 0);
        entry.setSaveRequest(saveReq);
        int permission = rs.getInt("PERMISSION");
        entry.setPermission(permission);
        entry.setRevocationInfo(revocationInfo);
        String validityModeS = rs.getString("VALIDITY_MODE");
        ValidityMode validityMode = null;
        if (validityModeS != null) {
            validityMode = ValidityMode.forName(validityModeS);
        }
        if (validityMode == null) {
            validityMode = ValidityMode.STRICT;
        }
        entry.setValidityMode(validityMode);
        try {
            return new X509CaInfo(entry, certstore);
        } catch (OperationException ex) {
            throw new CaMgmtException(ex);
        }
    } catch (SQLException ex) {
        throw new CaMgmtException(datasource, sql, ex);
    } finally {
        datasource.releaseResources(stmt, rs);
    }
}
Also used : NameId(org.xipki.ca.api.NameId) CertValidity(org.xipki.ca.api.profile.CertValidity) SQLException(java.sql.SQLException) ConfPairs(org.xipki.common.ConfPairs) PreparedStatement(java.sql.PreparedStatement) CaStatus(org.xipki.ca.server.mgmt.api.CaStatus) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) CertRevocationInfo(org.xipki.security.CertRevocationInfo) CaMgmtException(org.xipki.ca.server.mgmt.api.CaMgmtException) X509CaUris(org.xipki.ca.server.mgmt.api.x509.X509CaUris) ValidityMode(org.xipki.ca.server.mgmt.api.ValidityMode) ResultSet(java.sql.ResultSet) OperationException(org.xipki.ca.api.OperationException) X509CaEntry(org.xipki.ca.server.mgmt.api.x509.X509CaEntry)

Aggregations

ValidityMode (org.xipki.ca.server.mgmt.api.ValidityMode)5 NameId (org.xipki.ca.api.NameId)4 CertValidity (org.xipki.ca.api.profile.CertValidity)4 ConfPairs (org.xipki.common.ConfPairs)4 CaStatus (org.xipki.ca.server.mgmt.api.CaStatus)3 X509Certificate (java.security.cert.X509Certificate)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 SQLException (java.sql.SQLException)2 Date (java.util.Date)2 OperationException (org.xipki.ca.api.OperationException)2 CaMgmtException (org.xipki.ca.server.mgmt.api.CaMgmtException)2 X509CaEntry (org.xipki.ca.server.mgmt.api.x509.X509CaEntry)2 X509CaUris (org.xipki.ca.server.mgmt.api.x509.X509CaUris)2 X509ChangeCaEntry (org.xipki.ca.server.mgmt.api.x509.X509ChangeCaEntry)2 IllegalCmdParamException (org.xipki.console.karaf.IllegalCmdParamException)2 BigInteger (java.math.BigInteger)1 CertificateEncodingException (java.security.cert.CertificateEncodingException)1 CertificateException (java.security.cert.CertificateException)1 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)1