Search in sources :

Example 6 with CertValidity

use of org.xipki.ca.api.profile.CertValidity 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 7 with CertValidity

use of org.xipki.ca.api.profile.CertValidity 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)

Example 8 with CertValidity

use of org.xipki.ca.api.profile.CertValidity in project xipki by xipki.

the class X509Ca method revokeSuspendedCerts0.

private int revokeSuspendedCerts0(AuditEvent event, String msgId) throws OperationException {
    if (!masterMode) {
        throw new OperationException(ErrorCode.NOT_PERMITTED, "CA could not remove expired certificates in slave mode");
    }
    final int numEntries = 100;
    CertValidity val = caInfo.revokeSuspendedCertsControl().getUnchangedSince();
    long ms;
    switch(val.getUnit()) {
        case DAY:
            ms = val.getValidity() * DAY_IN_MS;
            break;
        case HOUR:
            ms = val.getValidity() * DAY_IN_MS / 24;
            break;
        case YEAR:
            ms = val.getValidity() * 365 * DAY_IN_MS;
            break;
        default:
            throw new RuntimeException("should not reach here, unknown Validity Unit " + val.getUnit());
    }
    // seconds
    final long latestLastUpdatedAt = (System.currentTimeMillis() - ms) / 1000;
    final CrlReason reason = caInfo.revokeSuspendedCertsControl().getTargetReason();
    int sum = 0;
    while (true) {
        List<BigInteger> serials = certstore.getSuspendedCertSerials(caIdent, latestLastUpdatedAt, numEntries);
        if (CollectionUtil.isEmpty(serials)) {
            return sum;
        }
        for (BigInteger serial : serials) {
            boolean revoked = false;
            try {
                revoked = revokeSuspendedCert(serial, reason, msgId) != null;
                if (revoked) {
                    sum++;
                }
            } catch (OperationException ex) {
                LOG.info("revoked {} suspended certificates of CA {}", sum, caIdent);
                LogUtil.error(LOG, ex, "could not revoke suspended certificate with serial" + serial);
                throw ex;
            }
        // end try
        }
    // end for
    }
// end while (true)
}
Also used : CertValidity(org.xipki.ca.api.profile.CertValidity) BigInteger(java.math.BigInteger) CrlReason(org.xipki.security.CrlReason) OperationException(org.xipki.ca.api.OperationException) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint)

Example 9 with CertValidity

use of org.xipki.ca.api.profile.CertValidity in project xipki by xipki.

the class X509CertprofileQa method checkCert.

// constructor
public ValidationResult checkCert(byte[] certBytes, X509IssuerInfo issuerInfo, X500Name requestedSubject, SubjectPublicKeyInfo requestedPublicKey, Extensions requestedExtensions) {
    ParamUtil.requireNonNull("certBytes", certBytes);
    ParamUtil.requireNonNull("issuerInfo", issuerInfo);
    ParamUtil.requireNonNull("requestedSubject", requestedSubject);
    ParamUtil.requireNonNull("requestedPublicKey", requestedPublicKey);
    List<ValidationIssue> resultIssues = new LinkedList<ValidationIssue>();
    Certificate bcCert;
    TBSCertificate tbsCert;
    X509Certificate cert;
    ValidationIssue issue;
    // certificate size
    issue = new ValidationIssue("X509.SIZE", "certificate size");
    resultIssues.add(issue);
    Integer maxSize = certProfile.getMaxSize();
    if (maxSize != 0) {
        int size = certBytes.length;
        if (size > maxSize) {
            issue.setFailureMessage(String.format("certificate exceeds the maximal allowed size: %d > %d", size, maxSize));
        }
    }
    // certificate encoding
    issue = new ValidationIssue("X509.ENCODING", "certificate encoding");
    resultIssues.add(issue);
    try {
        bcCert = Certificate.getInstance(certBytes);
        tbsCert = bcCert.getTBSCertificate();
        cert = X509Util.parseCert(certBytes);
    } catch (CertificateException ex) {
        issue.setFailureMessage("certificate is not corrected encoded");
        return new ValidationResult(resultIssues);
    }
    // syntax version
    issue = new ValidationIssue("X509.VERSION", "certificate version");
    resultIssues.add(issue);
    int versionNumber = tbsCert.getVersionNumber();
    X509CertVersion expVersion = certProfile.getVersion();
    if (versionNumber != expVersion.getVersionNumber()) {
        issue.setFailureMessage("is '" + versionNumber + "' but expected '" + expVersion.getVersionNumber() + "'");
    }
    // serialNumber
    issue = new ValidationIssue("X509.serialNumber", "certificate serial number");
    resultIssues.add(issue);
    BigInteger serialNumber = tbsCert.getSerialNumber().getValue();
    if (serialNumber.signum() != 1) {
        issue.setFailureMessage("not positive");
    } else {
        if (serialNumber.bitLength() >= 160) {
            issue.setFailureMessage("serial number has more than 20 octets");
        }
    }
    // signatureAlgorithm
    List<String> signatureAlgorithms = certProfile.getSignatureAlgorithms();
    if (CollectionUtil.isNonEmpty(signatureAlgorithms)) {
        issue = new ValidationIssue("X509.SIGALG", "signature algorithm");
        resultIssues.add(issue);
        AlgorithmIdentifier sigAlgId = bcCert.getSignatureAlgorithm();
        AlgorithmIdentifier tbsSigAlgId = tbsCert.getSignature();
        if (!tbsSigAlgId.equals(sigAlgId)) {
            issue.setFailureMessage("Certificate.tbsCertificate.signature != Certificate.signatureAlgorithm");
        }
        try {
            String sigAlgo = AlgorithmUtil.getSignatureAlgoName(sigAlgId);
            if (!issue.isFailed()) {
                if (!signatureAlgorithms.contains(sigAlgo)) {
                    issue.setFailureMessage("signatureAlgorithm '" + sigAlgo + "' is not allowed");
                }
            }
            // check parameters
            if (!issue.isFailed()) {
                AlgorithmIdentifier expSigAlgId = AlgorithmUtil.getSigAlgId(sigAlgo);
                if (!expSigAlgId.equals(sigAlgId)) {
                    issue.setFailureMessage("invalid parameters");
                }
            }
        } catch (NoSuchAlgorithmException ex) {
            issue.setFailureMessage("unsupported signature algorithm " + sigAlgId.getAlgorithm().getId());
        }
    }
    // notBefore encoding
    issue = new ValidationIssue("X509.NOTBEFORE.ENCODING", "notBefore encoding");
    checkTime(tbsCert.getStartDate(), issue);
    // notAfter encoding
    issue = new ValidationIssue("X509.NOTAFTER.ENCODING", "notAfter encoding");
    checkTime(tbsCert.getStartDate(), issue);
    // notBefore
    if (certProfile.isNotBeforeMidnight()) {
        issue = new ValidationIssue("X509.NOTBEFORE", "notBefore midnight");
        resultIssues.add(issue);
        Calendar cal = Calendar.getInstance(UTC);
        cal.setTime(cert.getNotBefore());
        int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        int second = cal.get(Calendar.SECOND);
        if (hourOfDay != 0 || minute != 0 || second != 0) {
            issue.setFailureMessage(" '" + cert.getNotBefore() + "' is not midnight time (UTC)");
        }
    }
    // validity
    issue = new ValidationIssue("X509.VALIDITY", "cert validity");
    resultIssues.add(issue);
    if (cert.getNotAfter().before(cert.getNotBefore())) {
        issue.setFailureMessage("notAfter must not be before notBefore");
    } else if (cert.getNotBefore().before(issuerInfo.getCaNotBefore())) {
        issue.setFailureMessage("notBefore must not be before CA's notBefore");
    } else {
        CertValidity validity = certProfile.getValidity();
        Date expectedNotAfter = validity.add(cert.getNotBefore());
        if (expectedNotAfter.getTime() > MAX_CERT_TIME_MS) {
            expectedNotAfter = new Date(MAX_CERT_TIME_MS);
        }
        if (issuerInfo.isCutoffNotAfter() && expectedNotAfter.after(issuerInfo.getCaNotAfter())) {
            expectedNotAfter = issuerInfo.getCaNotAfter();
        }
        if (Math.abs(expectedNotAfter.getTime() - cert.getNotAfter().getTime()) > 60 * SECOND) {
            issue.setFailureMessage("cert validity is not within " + validity.toString());
        }
    }
    // subjectPublicKeyInfo
    resultIssues.addAll(publicKeyChecker.checkPublicKey(bcCert.getSubjectPublicKeyInfo(), requestedPublicKey));
    // Signature
    issue = new ValidationIssue("X509.SIG", "whether certificate is signed by CA");
    resultIssues.add(issue);
    try {
        cert.verify(issuerInfo.getCert().getPublicKey(), "BC");
    } catch (Exception ex) {
        issue.setFailureMessage("invalid signature");
    }
    // issuer
    issue = new ValidationIssue("X509.ISSUER", "certificate issuer");
    resultIssues.add(issue);
    if (!cert.getIssuerX500Principal().equals(issuerInfo.getCert().getSubjectX500Principal())) {
        issue.setFailureMessage("issue in certificate does not equal the subject of CA certificate");
    }
    // subject
    resultIssues.addAll(subjectChecker.checkSubject(bcCert.getSubject(), requestedSubject));
    // issuerUniqueID
    issue = new ValidationIssue("X509.IssuerUniqueID", "issuerUniqueID");
    resultIssues.add(issue);
    if (tbsCert.getIssuerUniqueId() != null) {
        issue.setFailureMessage("is present but not permitted");
    }
    // subjectUniqueID
    issue = new ValidationIssue("X509.SubjectUniqueID", "subjectUniqueID");
    resultIssues.add(issue);
    if (tbsCert.getSubjectUniqueId() != null) {
        issue.setFailureMessage("is present but not permitted");
    }
    // extensions
    issue = new ValidationIssue("X509.GrantedSubject", "grantedSubject");
    resultIssues.add(issue);
    resultIssues.addAll(extensionsChecker.checkExtensions(bcCert, issuerInfo, requestedExtensions, requestedSubject));
    return new ValidationResult(resultIssues);
}
Also used : CertValidity(org.xipki.ca.api.profile.CertValidity) Calendar(java.util.Calendar) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ValidationResult(org.xipki.common.qa.ValidationResult) ValidationIssue(org.xipki.common.qa.ValidationIssue) LinkedList(java.util.LinkedList) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) CertprofileException(org.xipki.ca.api.profile.CertprofileException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) BigInteger(java.math.BigInteger) X509CertVersion(org.xipki.ca.api.profile.x509.X509CertVersion) BigInteger(java.math.BigInteger) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) TBSCertificate(org.bouncycastle.asn1.x509.TBSCertificate)

Aggregations

CertValidity (org.xipki.ca.api.profile.CertValidity)9 Date (java.util.Date)5 OperationException (org.xipki.ca.api.OperationException)5 X509Certificate (java.security.cert.X509Certificate)4 ValidityMode (org.xipki.ca.server.mgmt.api.ValidityMode)4 ConfPairs (org.xipki.common.ConfPairs)4 BigInteger (java.math.BigInteger)3 CertificateException (java.security.cert.CertificateException)3 NameId (org.xipki.ca.api.NameId)3 CertprofileException (org.xipki.ca.api.profile.CertprofileException)3 CaStatus (org.xipki.ca.server.mgmt.api.CaStatus)3 IOException (java.io.IOException)2 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 SQLException (java.sql.SQLException)2 Calendar (java.util.Calendar)2 X500Name (org.bouncycastle.asn1.x500.X500Name)2 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)2 Certificate (org.bouncycastle.asn1.x509.Certificate)2