Search in sources :

Example 1 with DataAccessException

use of org.xipki.datasource.DataAccessException in project xipki by xipki.

the class DbCertStatusStore method getCertStatus.

// method initIssuerStore
@Override
public CertStatusInfo getCertStatus(Date time, RequestIssuer reqIssuer, BigInteger serialNumber, boolean includeCertHash, boolean includeRit, boolean inheritCaRevocation) throws OcspStoreException {
    if (serialNumber.signum() != 1) {
        // non-positive serial number
        return CertStatusInfo.getUnknownCertStatusInfo(new Date(), null);
    }
    if (!initialized) {
        throw new OcspStoreException("initialization of CertStore is still in process");
    }
    if (initializationFailed) {
        throw new OcspStoreException("initialization of CertStore failed");
    }
    String sql;
    try {
        IssuerEntry issuer = issuerStore.getIssuerForFp(reqIssuer);
        if (issuer == null) {
            return null;
        }
        if (includeCertHash) {
            sql = includeRit ? sqlCsWithCertHash : sqlCsNoRitWithCertHash;
        } else {
            sql = includeRit ? sqlCs : sqlCsNoRit;
        }
        CrlInfo crlInfo = issuer.getCrlInfo();
        Date thisUpdate;
        Date nextUpdate = null;
        if (crlInfo != null && crlInfo.isUseCrlUpdates()) {
            thisUpdate = crlInfo.getThisUpdate();
            // this.nextUpdate is still in the future (10 seconds buffer)
            if (crlInfo.getNextUpdate().getTime() - System.currentTimeMillis() > 10 * 1000) {
                nextUpdate = crlInfo.getNextUpdate();
            }
        } else {
            thisUpdate = new Date();
        }
        ResultSet rs = null;
        CertStatusInfo certStatusInfo = null;
        boolean unknown = true;
        boolean ignore = false;
        String certprofile = null;
        String b64CertHash = null;
        boolean revoked = false;
        int reason = 0;
        long revTime = 0;
        long invalTime = 0;
        PreparedStatement ps = datasource.prepareStatement(datasource.getConnection(), sql);
        try {
            ps.setInt(1, issuer.getId());
            ps.setString(2, serialNumber.toString(16));
            rs = ps.executeQuery();
            if (rs.next()) {
                unknown = false;
                long timeInSec = time.getTime() / 1000;
                if (!ignore && ignoreNotYetValidCert) {
                    long notBeforeInSec = rs.getLong("NBEFORE");
                    if (notBeforeInSec != 0 && timeInSec < notBeforeInSec) {
                        ignore = true;
                    }
                }
                if (!ignore && ignoreExpiredCert) {
                    long notAfterInSec = rs.getLong("NAFTER");
                    if (notAfterInSec != 0 && timeInSec > notAfterInSec) {
                        ignore = true;
                    }
                }
                if (!ignore) {
                    if (includeCertHash) {
                        b64CertHash = rs.getString("HASH");
                    }
                    revoked = rs.getBoolean("REV");
                    if (revoked) {
                        reason = rs.getInt("RR");
                        revTime = rs.getLong("RT");
                        if (includeRit) {
                            invalTime = rs.getLong("RIT");
                        }
                    }
                }
            }
        // end if (rs.next())
        } catch (SQLException ex) {
            throw datasource.translate(sql, ex);
        } finally {
            releaseDbResources(ps, rs);
        }
        if (unknown) {
            if (unknownSerialAsGood) {
                certStatusInfo = CertStatusInfo.getGoodCertStatusInfo(certHashAlgo, null, thisUpdate, nextUpdate, null);
            } else {
                certStatusInfo = CertStatusInfo.getUnknownCertStatusInfo(thisUpdate, nextUpdate);
            }
        } else {
            if (ignore) {
                certStatusInfo = CertStatusInfo.getIgnoreCertStatusInfo(thisUpdate, nextUpdate);
            } else {
                byte[] certHash = (b64CertHash == null) ? null : Base64.decodeFast(b64CertHash);
                if (revoked) {
                    Date invTime = (invalTime == 0 || invalTime == revTime) ? null : new Date(invalTime * 1000);
                    CertRevocationInfo revInfo = new CertRevocationInfo(reason, new Date(revTime * 1000), invTime);
                    certStatusInfo = CertStatusInfo.getRevokedCertStatusInfo(revInfo, certHashAlgo, certHash, thisUpdate, nextUpdate, certprofile);
                } else {
                    certStatusInfo = CertStatusInfo.getGoodCertStatusInfo(certHashAlgo, certHash, thisUpdate, nextUpdate, certprofile);
                }
            }
        }
        if (includeCrlId && crlInfo != null) {
            certStatusInfo.setCrlId(crlInfo.getCrlId());
        }
        if (includeArchiveCutoff) {
            if (retentionInterval != 0) {
                Date date;
                // expired certificate remains in status store for ever
                if (retentionInterval < 0) {
                    date = issuer.getNotBefore();
                } else {
                    long nowInMs = System.currentTimeMillis();
                    long dateInMs = Math.max(issuer.getNotBefore().getTime(), nowInMs - DAY * retentionInterval);
                    date = new Date(dateInMs);
                }
                certStatusInfo.setArchiveCutOff(date);
            }
        }
        if ((!inheritCaRevocation) || issuer.getRevocationInfo() == null) {
            return certStatusInfo;
        }
        CertRevocationInfo caRevInfo = issuer.getRevocationInfo();
        CertStatus certStatus = certStatusInfo.getCertStatus();
        boolean replaced = false;
        if (certStatus == CertStatus.GOOD || certStatus == CertStatus.UNKNOWN) {
            replaced = true;
        } else if (certStatus == CertStatus.REVOKED) {
            if (certStatusInfo.getRevocationInfo().getRevocationTime().after(caRevInfo.getRevocationTime())) {
                replaced = true;
            }
        }
        if (replaced) {
            CertRevocationInfo newRevInfo;
            if (caRevInfo.getReason() == CrlReason.CA_COMPROMISE) {
                newRevInfo = caRevInfo;
            } else {
                newRevInfo = new CertRevocationInfo(CrlReason.CA_COMPROMISE, caRevInfo.getRevocationTime(), caRevInfo.getInvalidityTime());
            }
            certStatusInfo = CertStatusInfo.getRevokedCertStatusInfo(newRevInfo, certStatusInfo.getCertHashAlgo(), certStatusInfo.getCertHash(), certStatusInfo.getThisUpdate(), certStatusInfo.getNextUpdate(), certStatusInfo.getCertprofile());
        }
        return certStatusInfo;
    } catch (DataAccessException ex) {
        throw new OcspStoreException(ex.getMessage(), ex);
    }
}
Also used : IssuerEntry(org.xipki.ocsp.api.IssuerEntry) OcspStoreException(org.xipki.ocsp.api.OcspStoreException) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) CertStatusInfo(org.xipki.ocsp.api.CertStatusInfo) Date(java.util.Date) CertRevocationInfo(org.xipki.security.CertRevocationInfo) CrlInfo(org.xipki.ocsp.api.CrlInfo) CertStatus(org.xipki.ocsp.api.CertStatus) ResultSet(java.sql.ResultSet) DataAccessException(org.xipki.datasource.DataAccessException)

Example 2 with DataAccessException

use of org.xipki.datasource.DataAccessException in project xipki by xipki.

the class DbCertStatusStore method init.

@Override
public void init(String conf, DataSourceWrapper datasource) throws OcspStoreException {
    ParamUtil.requireNonNull("conf", conf);
    this.datasource = ParamUtil.requireNonNull("datasource", datasource);
    sqlCs = datasource.buildSelectFirstSql(1, "NBEFORE,NAFTER,REV,RR,RT,RIT FROM CERT WHERE IID=? AND SN=?");
    sqlCsNoRit = datasource.buildSelectFirstSql(1, "NBEFORE,NAFTER,REV,RR,RT FROM CERT WHERE IID=? AND SN=?");
    sqlCsWithCertHash = datasource.buildSelectFirstSql(1, "NBEFORE,NAFTER,REV,RR,RT,RIT,HASH FROM CERT WHERE IID=? AND SN=?");
    sqlCsNoRitWithCertHash = datasource.buildSelectFirstSql(1, "NBEFORE,NAFTER,REV,RR,RT,HASH FROM CERT WHERE IID=? AND SN=?");
    try {
        this.certHashAlgo = getCertHashAlgo(datasource);
    } catch (DataAccessException ex) {
        throw new OcspStoreException("Could not retrieve the certhash's algorithm from the database", ex);
    }
    StoreConf storeConf = new StoreConf(conf);
    try {
        Set<X509Certificate> includeIssuers = null;
        Set<X509Certificate> excludeIssuers = null;
        if (CollectionUtil.isNonEmpty(storeConf.getCaCertsIncludes())) {
            includeIssuers = parseCerts(storeConf.getCaCertsIncludes());
        }
        if (CollectionUtil.isNonEmpty(storeConf.getCaCertsExcludes())) {
            excludeIssuers = parseCerts(storeConf.getCaCertsExcludes());
        }
        this.issuerFilter = new IssuerFilter(includeIssuers, excludeIssuers);
    } catch (CertificateException ex) {
        throw new OcspStoreException(ex.getMessage(), ex);
    }
    // end try
    initIssuerStore();
    if (this.scheduledThreadPoolExecutor != null) {
        this.scheduledThreadPoolExecutor.shutdownNow();
    }
    StoreUpdateService storeUpdateService = new StoreUpdateService();
    List<Runnable> scheduledServices = getScheduledServices();
    int size = 1;
    if (scheduledServices != null) {
        size += scheduledServices.size();
    }
    this.scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(size);
    Random random = new Random();
    this.scheduledThreadPoolExecutor.scheduleAtFixedRate(storeUpdateService, 60 + random.nextInt(60), 60, TimeUnit.SECONDS);
    if (scheduledServices != null) {
        for (Runnable service : scheduledServices) {
            this.scheduledThreadPoolExecutor.scheduleAtFixedRate(service, 60 + random.nextInt(60), 60, TimeUnit.SECONDS);
        }
    }
}
Also used : IssuerFilter(org.xipki.ocsp.api.IssuerFilter) OcspStoreException(org.xipki.ocsp.api.OcspStoreException) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate) Random(java.util.Random) DataAccessException(org.xipki.datasource.DataAccessException)

Example 3 with DataAccessException

use of org.xipki.datasource.DataAccessException in project xipki by xipki.

the class CaManagerQueryExecutor method addRequestor.

// method addCmpControl
void addRequestor(RequestorEntry dbEntry) throws CaMgmtException {
    ParamUtil.requireNonNull("dbEntry", dbEntry);
    try {
        int id = (int) datasource.getMax(null, "REQUESTOR", "ID");
        dbEntry.getIdent().setId(id + 1);
    } catch (DataAccessException ex) {
        throw new CaMgmtException(ex);
    }
    final String sql = "INSERT INTO REQUESTOR (ID,NAME,CERT) VALUES (?,?,?)";
    PreparedStatement ps = null;
    try {
        ps = prepareStatement(sql);
        int idx = 1;
        ps.setInt(idx++, dbEntry.getIdent().getId());
        ps.setString(idx++, dbEntry.getIdent().getName());
        ps.setString(idx++, Base64.encodeToString(dbEntry.getCert().getEncoded()));
        if (ps.executeUpdate() == 0) {
            throw new CaMgmtException("could not add requestor " + dbEntry.getIdent());
        }
        if (LOG.isInfoEnabled()) {
            LOG.info("added requestor '{}': {}", dbEntry.getIdent(), dbEntry.toString(false));
        }
    } catch (SQLException ex) {
        throw new CaMgmtException(datasource, sql, ex);
    } catch (CertificateEncodingException ex) {
        throw new CaMgmtException(ex);
    } finally {
        datasource.releaseResources(ps, null);
    }
}
Also used : CaMgmtException(org.xipki.ca.server.mgmt.api.CaMgmtException) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) CertificateEncodingException(java.security.cert.CertificateEncodingException) DataAccessException(org.xipki.datasource.DataAccessException)

Example 4 with DataAccessException

use of org.xipki.datasource.DataAccessException in project xipki by xipki.

the class CaManagerQueryExecutor method addPublisher.

// method addEnvParam
void addPublisher(PublisherEntry dbEntry) throws CaMgmtException {
    ParamUtil.requireNonNull("dbEntry", dbEntry);
    final String sql = "INSERT INTO PUBLISHER (ID,NAME,TYPE,CONF) VALUES (?,?,?,?)";
    try {
        int id = (int) datasource.getMax(null, "PUBLISHER", "ID");
        dbEntry.getIdent().setId(id + 1);
    } catch (DataAccessException ex) {
        throw new CaMgmtException(ex);
    }
    String name = dbEntry.getIdent().getName();
    PreparedStatement ps = null;
    try {
        ps = prepareStatement(sql);
        int idx = 1;
        ps.setInt(idx++, dbEntry.getIdent().getId());
        ps.setString(idx++, name);
        ps.setString(idx++, dbEntry.getType());
        String conf = dbEntry.getConf();
        ps.setString(idx++, conf);
        if (ps.executeUpdate() == 0) {
            throw new CaMgmtException("could not add publisher " + dbEntry.getIdent());
        }
        LOG.info("added publisher '{}': {}", dbEntry.getIdent(), dbEntry);
    } catch (SQLException ex) {
        throw new CaMgmtException(datasource, sql, ex);
    } finally {
        datasource.releaseResources(ps, null);
    }
}
Also used : CaMgmtException(org.xipki.ca.server.mgmt.api.CaMgmtException) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) DataAccessException(org.xipki.datasource.DataAccessException)

Example 5 with DataAccessException

use of org.xipki.datasource.DataAccessException in project xipki by xipki.

the class CaManagerImpl method init.

private void init() throws CaMgmtException {
    if (securityFactory == null) {
        throw new IllegalStateException("securityFactory is not set");
    }
    if (datasourceFactory == null) {
        throw new IllegalStateException("datasourceFactory is not set");
    }
    if (x509CertProfileFactoryRegister == null) {
        throw new IllegalStateException("x509CertProfileFactoryRegister is not set");
    }
    if (x509CertPublisherFactoryRegister == null) {
        throw new IllegalStateException("x509CertPublisherFactoryRegister is not set");
    }
    if (caConfFile == null) {
        throw new IllegalStateException("caConfFile is not set");
    }
    Properties caConfProps = new Properties();
    try {
        caConfProps.load(new FileInputStream(IoUtil.expandFilepath(caConfFile)));
    } catch (IOException ex) {
        throw new CaMgmtException("could not parse CA configuration" + caConfFile, ex);
    }
    String caModeStr = caConfProps.getProperty("ca.mode");
    if (caModeStr != null) {
        if ("slave".equalsIgnoreCase(caModeStr)) {
            masterMode = false;
        } else if ("master".equalsIgnoreCase(caModeStr)) {
            masterMode = true;
        } else {
            throw new CaMgmtException(concat("invalid ca.mode '", caModeStr, "'"));
        }
    } else {
        masterMode = true;
    }
    int shardId;
    String shardIdStr = caConfProps.getProperty("ca.shardId");
    if (StringUtil.isBlank(shardIdStr)) {
        throw new CaMgmtException("ca.shardId is not set");
    }
    LOG.info("ca.shardId: {}", shardIdStr);
    try {
        shardId = Integer.parseInt(shardIdStr);
    } catch (NumberFormatException ex) {
        throw new CaMgmtException(concat("invalid ca.shardId '", shardIdStr, "'"));
    }
    if (shardId < 0 || shardId > 127) {
        throw new CaMgmtException("ca.shardId is not in [0, 127]");
    }
    if (this.datasources == null) {
        this.datasources = new ConcurrentHashMap<>();
        for (Object objKey : caConfProps.keySet()) {
            String key = (String) objKey;
            if (!StringUtil.startsWithIgnoreCase(key, "datasource.")) {
                continue;
            }
            String datasourceFile = caConfProps.getProperty(key);
            try {
                String datasourceName = key.substring("datasource.".length());
                DataSourceWrapper datasource = datasourceFactory.createDataSourceForFile(datasourceName, datasourceFile, securityFactory.getPasswordResolver());
                Connection conn = datasource.getConnection();
                datasource.returnConnection(conn);
                this.datasources.put(datasourceName, datasource);
            } catch (DataAccessException | PasswordResolverException | IOException | RuntimeException ex) {
                throw new CaMgmtException(concat(ex.getClass().getName(), " while parsing datasource ", datasourceFile, ": ", ex.getMessage()), ex);
            }
        }
        this.datasource = this.datasources.get("ca");
    }
    if (this.datasource == null) {
        throw new CaMgmtException("no datasource named 'ca' configured");
    }
    this.queryExecutor = new CaManagerQueryExecutor(this.datasource);
    initEnvironmentParamters();
    String envEpoch = envParameterResolver.getParameter(ENV_EPOCH);
    if (masterMode) {
        lockCa(true);
        if (envEpoch == null) {
            final long day = 24L * 60 * 60 * 1000;
            envEpoch = queryExecutor.setEpoch(new Date(System.currentTimeMillis() - day));
            LOG.info("set environment {} to {}", ENV_EPOCH, envEpoch);
        }
        queryExecutor.addRequestorIfNeeded(RequestorInfo.NAME_BY_CA);
        queryExecutor.addRequestorIfNeeded(RequestorInfo.NAME_BY_USER);
    } else {
        if (envEpoch == null) {
            throw new CaMgmtException("The CA system must be started first with ca.mode = master");
        }
    }
    LOG.info("use EPOCH: {}", envEpoch);
    long epoch = DateUtil.parseUtcTimeyyyyMMdd(envEpoch).getTime();
    UniqueIdGenerator idGen = new UniqueIdGenerator(epoch, shardId);
    try {
        this.certstore = new CertificateStore(datasource, idGen);
    } catch (DataAccessException ex) {
        throw new CaMgmtException(ex.getMessage(), ex);
    }
    initCaAliases();
    initCertprofiles();
    initPublishers();
    initCmpControls();
    initRequestors();
    initResponders();
    initCrlSigners();
    initCas();
    initSceps();
}
Also used : Connection(java.sql.Connection) IOException(java.io.IOException) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) Date(java.util.Date) CaMgmtException(org.xipki.ca.server.mgmt.api.CaMgmtException) CertificateStore(org.xipki.ca.server.impl.store.CertificateStore) PasswordResolverException(org.xipki.password.PasswordResolverException) DataSourceWrapper(org.xipki.datasource.DataSourceWrapper) DataAccessException(org.xipki.datasource.DataAccessException)

Aggregations

DataAccessException (org.xipki.datasource.DataAccessException)21 PreparedStatement (java.sql.PreparedStatement)18 SQLException (java.sql.SQLException)14 CaMgmtException (org.xipki.ca.server.mgmt.api.CaMgmtException)9 ResultSet (java.sql.ResultSet)6 Connection (java.sql.Connection)5 BigInteger (java.math.BigInteger)3 CertificateEncodingException (java.security.cert.CertificateEncodingException)3 CertificateException (java.security.cert.CertificateException)3 X509Certificate (java.security.cert.X509Certificate)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 ConfPairs (org.xipki.common.ConfPairs)3 IssuerEntry (org.xipki.ocsp.api.IssuerEntry)3 Date (java.util.Date)2 DataSourceWrapper (org.xipki.datasource.DataSourceWrapper)2 OcspStoreException (org.xipki.ocsp.api.OcspStoreException)2 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 Statement (java.sql.Statement)1