Search in sources :

Example 6 with DataAccessException

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

the class CertStoreQueryExecutor method getLatestSerialNumber.

// method isHealthy
String getLatestSerialNumber(X500Name nameWithSn) throws OperationException {
    RDN[] rdns1 = nameWithSn.getRDNs();
    RDN[] rdns2 = new RDN[rdns1.length];
    for (int i = 0; i < rdns1.length; i++) {
        RDN rdn = rdns1[i];
        rdns2[i] = rdn.getFirst().getType().equals(ObjectIdentifiers.DN_SERIALNUMBER) ? new RDN(ObjectIdentifiers.DN_SERIALNUMBER, new DERPrintableString("%")) : rdn;
    }
    String namePattern = X509Util.getRfc4519Name(new X500Name(rdns2));
    final String sql = sqls.sqlLatestSerialForSubjectLike;
    ResultSet rs = null;
    PreparedStatement ps;
    try {
        ps = borrowPreparedStatement(sql);
    } catch (DataAccessException ex) {
        throw new OperationException(ErrorCode.DATABASE_FAILURE, ex.getMessage());
    }
    String subjectStr;
    try {
        ps.setString(1, namePattern);
        rs = ps.executeQuery();
        if (!rs.next()) {
            return null;
        }
        subjectStr = rs.getString("SUBJECT");
    } catch (SQLException ex) {
        throw new OperationException(ErrorCode.DATABASE_FAILURE, ex.getMessage());
    } finally {
        releaseDbResources(ps, rs);
    }
    X500Name lastName = new X500Name(subjectStr);
    RDN[] rdns = lastName.getRDNs(ObjectIdentifiers.DN_SERIALNUMBER);
    if (rdns == null || rdns.length == 0) {
        return null;
    }
    return X509Util.rdnValueToString(rdns[0].getFirst().getValue());
}
Also used : SQLException(java.sql.SQLException) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DEROctetString(org.bouncycastle.asn1.DEROctetString) X500Name(org.bouncycastle.asn1.x500.X500Name) RDN(org.bouncycastle.asn1.x500.RDN) DataAccessException(org.xipki.datasource.DataAccessException) OperationException(org.xipki.ca.api.OperationException)

Example 7 with DataAccessException

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

the class ResponseCacher method storeIssuer.

synchronized Integer storeIssuer(X509Certificate issuerCert) throws CertificateException, InvalidConfException, DataAccessException {
    if (!master) {
        throw new IllegalStateException("storeIssuer is not permitted in slave mode");
    }
    for (Integer id : issuerStore.getIds()) {
        if (issuerStore.getIssuerForId(id).getCert().equals(issuerCert)) {
            return id;
        }
    }
    byte[] encodedCert = issuerCert.getEncoded();
    String sha1FpCert = HashAlgo.SHA1.base64Hash(encodedCert);
    int maxId = (int) datasource.getMax(null, "ISSUER", "ID");
    int id = maxId + 1;
    try {
        final String sql = SQL_ADD_ISSUER;
        PreparedStatement ps = null;
        try {
            ps = prepareStatement(sql);
            int idx = 1;
            ps.setInt(idx++, id);
            ps.setString(idx++, sha1FpCert);
            ps.setString(idx++, Base64.encodeToString(encodedCert));
            ps.execute();
            IssuerEntry newInfo = new IssuerEntry(id, issuerCert);
            issuerStore.addIssuer(newInfo);
            return id;
        } catch (SQLException ex) {
            throw datasource.translate(sql, ex);
        } finally {
            datasource.releaseResources(ps, null);
        }
    } catch (DataAccessException ex) {
        if (ex.getReason().isDescendantOrSelfOf(Reason.DuplicateKey)) {
            return id;
        }
        throw ex;
    }
}
Also used : BigInteger(java.math.BigInteger) IssuerEntry(org.xipki.ocsp.api.IssuerEntry) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) DataAccessException(org.xipki.datasource.DataAccessException)

Example 8 with DataAccessException

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

the class ResponseCacher method updateCacheStore0.

/**
 * update the cache store.
 * @return whether the ResponseCacher is on service.
 */
private boolean updateCacheStore0() {
    try {
        if (this.issuerStore == null) {
            return initIssuerStore();
        }
        // check for new issuers
        PreparedStatement ps = null;
        ResultSet rs = null;
        Set<Integer> ids = new HashSet<>();
        try {
            ps = prepareStatement(SQL_SELECT_ISSUER_ID);
            rs = ps.executeQuery();
            if (master) {
                // whether the database is accessible
                return true;
            }
            while (rs.next()) {
                ids.add(rs.getInt("ID"));
            }
        } catch (SQLException ex) {
            LogUtil.error(LOG, datasource.translate(SQL_SELECT_ISSUER_ID, ex), "could not executing updateCacheStore()");
            return false;
        } catch (Exception ex) {
            LogUtil.error(LOG, ex, "could not executing updateCacheStore()");
            return false;
        } finally {
            datasource.releaseResources(ps, rs, false);
        }
        // add the new issuers
        ps = null;
        rs = null;
        Set<Integer> currentIds = issuerStore.getIds();
        for (Integer id : ids) {
            if (currentIds.contains(id)) {
                continue;
            }
            try {
                if (ps == null) {
                    ps = prepareStatement(sqlSelectIssuerCert);
                }
                ps.setInt(1, id);
                rs = ps.executeQuery();
                rs.next();
                String b64Cert = rs.getString("CERT");
                X509Certificate cert = X509Util.parseBase64EncodedCert(b64Cert);
                IssuerEntry caInfoEntry = new IssuerEntry(id, cert);
                issuerStore.addIssuer(caInfoEntry);
                LOG.info("added issuer {}", id);
            } catch (SQLException ex) {
                LogUtil.error(LOG, datasource.translate(sqlSelectIssuerCert, ex), "could not executing updateCacheStore()");
                return false;
            } catch (Exception ex) {
                LogUtil.error(LOG, ex, "could not executing updateCacheStore()");
                return false;
            } finally {
                datasource.releaseResources(null, rs, false);
            }
        }
        if (ps != null) {
            datasource.releaseResources(ps, null, false);
        }
    } catch (DataAccessException ex) {
        LogUtil.error(LOG, ex, "could not executing updateCacheStore()");
        return false;
    } catch (CertificateException ex) {
        // don't set the onService to false.
        LogUtil.error(LOG, ex, "could not executing updateCacheStore()");
    }
    return true;
}
Also used : BigInteger(java.math.BigInteger) IssuerEntry(org.xipki.ocsp.api.IssuerEntry) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) CertificateException(java.security.cert.CertificateException) InvalidConfException(org.xipki.common.InvalidConfException) SQLException(java.sql.SQLException) DataAccessException(org.xipki.datasource.DataAccessException) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate) DataAccessException(org.xipki.datasource.DataAccessException) HashSet(java.util.HashSet)

Example 9 with DataAccessException

use of org.xipki.datasource.DataAccessException 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 10 with DataAccessException

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

the class CaManagerQueryExecutor method addCertprofile.

// method addCaAlias
void addCertprofile(CertprofileEntry dbEntry) throws CaMgmtException {
    ParamUtil.requireNonNull("dbEntry", dbEntry);
    final String sql = "INSERT INTO PROFILE (ID,NAME,ART,TYPE,CONF) VALUES (?,?,?,?,?)";
    try {
        int id = (int) datasource.getMax(null, "PROFILE", "ID");
        dbEntry.getIdent().setId(id + 1);
    } catch (DataAccessException ex) {
        throw new CaMgmtException(ex);
    }
    PreparedStatement ps = null;
    try {
        ps = prepareStatement(sql);
        int idx = 1;
        ps.setInt(idx++, dbEntry.getIdent().getId());
        ps.setString(idx++, dbEntry.getIdent().getName());
        ps.setInt(idx++, CertArt.X509PKC.getCode());
        ps.setString(idx++, dbEntry.getType());
        String conf = dbEntry.getConf();
        ps.setString(idx++, conf);
        if (ps.executeUpdate() == 0) {
            throw new CaMgmtException("could not add CertProfile " + dbEntry.getIdent());
        }
        LOG.info("added profile '{}': {}", 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)

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