]> WPIA git - gigi.git/blobdiff - src/org/cacert/gigi/dbObjects/Certificate.java
fix: SQL change database call pattern
[gigi.git] / src / org / cacert / gigi / dbObjects / Certificate.java
index 59d0aded9b329c9396c5690d5690c5d84f1b3f3e..8e66c7f30c3d98c3b123ef9f6f5c73114aa95905 100644 (file)
@@ -9,21 +9,20 @@ import java.security.GeneralSecurityException;
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
 import java.sql.Date;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Map.Entry;
 
 import org.cacert.gigi.GigiApiException;
-import org.cacert.gigi.database.DatabaseConnection;
-import org.cacert.gigi.util.Job;
+import org.cacert.gigi.database.GigiPreparedStatement;
+import org.cacert.gigi.database.GigiResultSet;
 import org.cacert.gigi.util.KeyStorage;
 import org.cacert.gigi.util.Notary;
 
-public class Certificate {
+public class Certificate implements IdCachable {
 
     public enum SANType {
         EMAIL("email"), DNS("DNS");
@@ -109,13 +108,11 @@ public class Certificate {
 
     private int id;
 
-    private int ownerId;
+    private CertificateOwner owner;
 
     private String serial;
 
-    private String dn;
-
-    private String md;
+    private Digest md;
 
     private String csrName;
 
@@ -129,45 +126,87 @@ public class Certificate {
 
     private CertificateProfile profile;
 
-    public Certificate(int ownerId, String dn, String md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) {
-        this.ownerId = ownerId;
+    private HashMap<String, String> dn;
+
+    private String dnString;
+
+    private CACertificate ca;
+
+    public Certificate(CertificateOwner owner, User actor, HashMap<String, String> dn, Digest md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException, IOException {
+        if ( !profile.canBeIssuedBy(owner, actor)) {
+            throw new GigiApiException("You are not allowed to issue these certificates.");
+        }
+        this.owner = owner;
         this.dn = dn;
+        if (dn.size() == 0) {
+            throw new GigiApiException("DN must not be empty");
+        }
+        dnString = stringifyDN(dn);
         this.md = md;
         this.csr = csr;
         this.csrType = csrType;
         this.profile = profile;
         this.sans = Arrays.asList(sans);
-    }
+        synchronized (Certificate.class) {
+
+            try (GigiPreparedStatement inserter = new GigiPreparedStatement("INSERT INTO certs SET md=?::`mdType`, csr_type=?::`csrType`, crt_name='', memid=?, profile=?")) {
+                inserter.setString(1, md.toString().toLowerCase());
+                inserter.setString(2, csrType.toString());
+                inserter.setInt(3, owner.getId());
+                inserter.setInt(4, profile.getId());
+                inserter.execute();
+                id = inserter.lastInsertId();
+            }
 
-    private Certificate(String serial) {
-        try {
-            PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id,subject, md, csr_name, crt_name,memid, profile FROM `certs` WHERE serial=?");
-            ps.setString(1, serial);
-            ResultSet rs = ps.executeQuery();
-            if ( !rs.next()) {
-                throw new IllegalArgumentException("Invalid mid " + serial);
+            try (GigiPreparedStatement san = new GigiPreparedStatement("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`")) {
+                for (SubjectAlternateName subjectAlternateName : sans) {
+                    san.setInt(1, id);
+                    san.setString(2, subjectAlternateName.getName());
+                    san.setString(3, subjectAlternateName.getType().getOpensslName());
+                    san.execute();
+                }
+            }
+
+            try (GigiPreparedStatement insertAVA = new GigiPreparedStatement("INSERT INTO `certAvas` SET `certId`=?, name=?, value=?")) {
+                insertAVA.setInt(1, id);
+                for (Entry<String, String> e : dn.entrySet()) {
+                    insertAVA.setString(2, e.getKey());
+                    insertAVA.setString(3, e.getValue());
+                    insertAVA.execute();
+                }
+            }
+            File csrFile = KeyStorage.locateCsr(id);
+            csrName = csrFile.getPath();
+            try (FileOutputStream fos = new FileOutputStream(csrFile)) {
+                fos.write(csr.getBytes("UTF-8"));
             }
-            this.id = rs.getInt(1);
-            dn = rs.getString(2);
-            md = rs.getString(3);
-            csrName = rs.getString(4);
-            crtName = rs.getString(5);
-            ownerId = rs.getInt(6);
-            profile = CertificateProfile.getById(rs.getInt(7));
-            this.serial = serial;
-
-            PreparedStatement ps2 = DatabaseConnection.getInstance().prepare("SELECT contents, type FROM `subjectAlternativeNames` WHERE certId=?");
+            try (GigiPreparedStatement updater = new GigiPreparedStatement("UPDATE `certs` SET `csr_name`=? WHERE id=?")) {
+                updater.setString(1, csrName);
+                updater.setInt(2, id);
+                updater.execute();
+            }
+
+            cache.put(this);
+        }
+    }
+
+    private Certificate(GigiResultSet rs) {
+        this.id = rs.getInt("id");
+        dnString = rs.getString("subject");
+        md = Digest.valueOf(rs.getString("md").toUpperCase());
+        csrName = rs.getString("csr_name");
+        crtName = rs.getString("crt_name");
+        owner = CertificateOwner.getById(rs.getInt("memid"));
+        profile = CertificateProfile.getById(rs.getInt("profile"));
+        this.serial = rs.getString("serial");
+
+        try (GigiPreparedStatement ps2 = new GigiPreparedStatement("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?")) {
             ps2.setInt(1, id);
-            ResultSet rs2 = ps2.executeQuery();
+            GigiResultSet rs2 = ps2.executeQuery();
             sans = new LinkedList<>();
             while (rs2.next()) {
                 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
             }
-            rs2.close();
-
-            rs.close();
-        } catch (SQLException e) {
-            e.printStackTrace();
         }
     }
 
@@ -198,26 +237,25 @@ public class Certificate {
 
     }
 
-    public CertificateStatus getStatus() throws SQLException {
-        if (id == 0) {
-            return CertificateStatus.DRAFT;
-        }
-        PreparedStatement searcher = DatabaseConnection.getInstance().prepare("SELECT crt_name, created, revoked, serial FROM certs WHERE id=?");
-        searcher.setInt(1, id);
-        ResultSet rs = searcher.executeQuery();
-        if ( !rs.next()) {
-            throw new IllegalStateException("Certificate not in Database");
-        }
+    public synchronized CertificateStatus getStatus() {
+        try (GigiPreparedStatement searcher = new GigiPreparedStatement("SELECT crt_name, created, revoked, serial, caid FROM certs WHERE id=?")) {
+            searcher.setInt(1, id);
+            GigiResultSet rs = searcher.executeQuery();
+            if ( !rs.next()) {
+                throw new IllegalStateException("Certificate not in Database");
+            }
 
-        crtName = rs.getString(1);
-        serial = rs.getString(4);
-        if (rs.getTime(2) == null) {
-            return CertificateStatus.DRAFT;
-        }
-        if (rs.getTime(2) != null && rs.getTime(3) == null) {
-            return CertificateStatus.ISSUED;
+            crtName = rs.getString(1);
+            serial = rs.getString(4);
+            if (rs.getTimestamp(2) == null) {
+                return CertificateStatus.DRAFT;
+            }
+            ca = CACertificate.getById(rs.getInt("caid"));
+            if (rs.getTimestamp(2) != null && rs.getTimestamp(3) == null) {
+                return CertificateStatus.ISSUED;
+            }
+            return CertificateStatus.REVOKED;
         }
-        return CertificateStatus.REVOKED;
     }
 
     /**
@@ -231,49 +269,20 @@ public class Certificate {
      * @return A job which can be used to monitor the progress of this task.
      * @throws IOException
      *             for problems with writing the CSR/SPKAC
-     * @throws SQLException
-     *             for problems with writing to the DB
      * @throws GigiApiException
      *             if the period is bogus
      */
-    public Job issue(Date start, String period) throws IOException, SQLException, GigiApiException {
+    public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
         if (getStatus() != CertificateStatus.DRAFT) {
             throw new IllegalStateException();
         }
-        Notary.writeUserAgreement(ownerId, "CCA", "issue certificate", "", true, 0);
-
-        PreparedStatement inserter = DatabaseConnection.getInstance().prepare("INSERT INTO certs SET md=?, subject=?, csr_type=?, crt_name='', memid=?, profile=?");
-        inserter.setString(1, md);
-        inserter.setString(2, dn);
-        inserter.setString(3, csrType.toString());
-        inserter.setInt(4, ownerId);
-        inserter.setInt(5, profile.getId());
-        inserter.execute();
-        id = DatabaseConnection.lastInsertId(inserter);
-        File csrFile = KeyStorage.locateCsr(id);
-        csrName = csrFile.getPath();
-        FileOutputStream fos = new FileOutputStream(csrFile);
-        fos.write(csr.getBytes());
-        fos.close();
-
-        // TODO draft to insert SANs
-        PreparedStatement san = DatabaseConnection.getInstance().prepare("INSERT INTO subjectAlternativeNames SET certId=?, contents=?, type=?");
-        for (SubjectAlternateName subjectAlternateName : sans) {
-            san.setInt(1, id);
-            san.setString(2, subjectAlternateName.getName());
-            san.setString(3, subjectAlternateName.getType().getOpensslName());
-            san.execute();
-        }
+        Notary.writeUserAgreement(actor, "CCA", "issue certificate", "", true, 0);
 
-        PreparedStatement updater = DatabaseConnection.getInstance().prepare("UPDATE certs SET csr_name=? WHERE id=?");
-        updater.setString(1, csrName);
-        updater.setInt(2, id);
-        updater.execute();
         return Job.sign(this, start, period);
 
     }
 
-    public Job revoke() throws SQLException {
+    public Job revoke() {
         if (getStatus() != CertificateStatus.ISSUED) {
             throw new IllegalStateException();
         }
@@ -281,9 +290,17 @@ public class Certificate {
 
     }
 
-    public X509Certificate cert() throws IOException, GeneralSecurityException, SQLException {
+    public CACertificate getParent() {
+        CertificateStatus status = getStatus();
+        if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
+            throw new IllegalStateException(status + " is not wanted here.");
+        }
+        return ca;
+    }
+
+    public X509Certificate cert() throws IOException, GeneralSecurityException {
         CertificateStatus status = getStatus();
-        if (status != CertificateStatus.ISSUED) {
+        if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
             throw new IllegalStateException(status + " is not wanted here.");
         }
         InputStream is = null;
@@ -309,24 +326,21 @@ public class Certificate {
     }
 
     public String getSerial() {
-        try {
-            getStatus();
-        } catch (SQLException e) {
-            e.printStackTrace();
-        } // poll changes
+        getStatus();
+        // poll changes
         return serial;
     }
 
     public String getDistinguishedName() {
-        return dn;
+        return dnString;
     }
 
-    public String getMessageDigest() {
+    public Digest getMessageDigest() {
         return md;
     }
 
-    public int getOwnerId() {
-        return ownerId;
+    public CertificateOwner getOwner() {
+        return owner;
     }
 
     public List<SubjectAlternateName> getSANs() {
@@ -337,14 +351,87 @@ public class Certificate {
         return profile;
     }
 
-    public static Certificate getBySerial(String serial) {
-        // TODO caching?
+    public synchronized static Certificate getBySerial(String serial) {
+        if (serial == null || "".equals(serial)) {
+            return null;
+        }
+        String concat = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
+        try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT certs.id, " + concat + " as `subject`, `md`, `csr_name`, `crt_name`,`memid`, `profile`, `certs`.`serial` FROM `certs` LEFT JOIN `certAvas` ON `certAvas`.`certId`=`certs`.`id` WHERE `serial`=? GROUP BY `certs`.`id`")) {
+            ps.setString(1, serial);
+            GigiResultSet rs = ps.executeQuery();
+            if ( !rs.next()) {
+                return null;
+            }
+            int id = rs.getInt(1);
+            Certificate c1 = cache.get(id);
+            if (c1 != null) {
+                return c1;
+            }
+            Certificate certificate = new Certificate(rs);
+            cache.put(certificate);
+            return certificate;
+        }
+    }
+
+    private static ObjectCache<Certificate> cache = new ObjectCache<>();
+
+    public synchronized static Certificate getById(int id) {
+        Certificate cacheRes = cache.get(id);
+        if (cacheRes != null) {
+            return cacheRes;
+        }
+
         try {
-            return new Certificate(serial);
+            String concat = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
+            try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT certs.id, " + concat + " as subject, md, csr_name, crt_name,memid, profile, certs.serial FROM `certs` LEFT JOIN `certAvas` ON `certAvas`.`certId`=certs.id WHERE certs.id=? GROUP BY certs.id")) {
+                ps.setInt(1, id);
+                GigiResultSet rs = ps.executeQuery();
+                if ( !rs.next()) {
+                    return null;
+                }
+
+                Certificate c = new Certificate(rs);
+                cache.put(c);
+                return c;
+            }
         } catch (IllegalArgumentException e) {
 
         }
         return null;
     }
 
+    public static String escapeAVA(String value) {
+
+        return value.replace("\\", "\\\\").replace("/", "\\/");
+    }
+
+    public static String stringifyDN(HashMap<String, String> contents) {
+        StringBuffer res = new StringBuffer();
+        for (Entry<String, String> i : contents.entrySet()) {
+            res.append("/" + i.getKey() + "=");
+            res.append(escapeAVA(i.getValue()));
+        }
+        return res.toString();
+    }
+
+    public static HashMap<String, String> buildDN(String... contents) {
+        HashMap<String, String> res = new HashMap<>();
+        for (int i = 0; i + 1 < contents.length; i += 2) {
+            res.put(contents[i], contents[i + 1]);
+        }
+        return res;
+    }
+
+    public java.util.Date getRevocationDate() {
+        if (getStatus() == CertificateStatus.REVOKED) {
+            try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT revoked FROM certs WHERE id=?")) {
+                prep.setInt(1, getId());
+                GigiResultSet res = prep.executeQuery();
+                if (res.next()) {
+                    return new java.util.Date(res.getDate("revoked").getTime());
+                }
+            }
+        }
+        return null;
+    }
 }