]> WPIA git - gigi.git/commitdiff
Update Certificate-DN-API (for escape-safe-strings)
authorFelix Dörre <felix@dogcraft.de>
Sat, 1 Nov 2014 16:23:23 +0000 (17:23 +0100)
committerJanis Streib <janis@dogcraft.de>
Wed, 31 Dec 2014 01:35:58 +0000 (02:35 +0100)
doc/tableStructure.sql
src/org/cacert/gigi/dbObjects/Certificate.java
src/org/cacert/gigi/pages/account/certs/CertificateIssueForm.java
tests/org/cacert/gigi/TestCertificate.java
tests/org/cacert/gigi/TestCrossDomainAccess.java
tests/org/cacert/gigi/TestSeparateSessionScope.java
tests/org/cacert/gigi/ping/TestSSL.java
util/org/cacert/gigi/util/SimpleSigner.java

index 6eb7ae3c90e1d3f70eaced4cb551a785f53699dd..5c79a162f7c7fe993f2a391e7acc656e6fa04ca0 100644 (file)
@@ -139,8 +139,6 @@ CREATE TABLE `certs` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `memid` int(11) NOT NULL DEFAULT '0',
   `serial` varchar(50) NOT NULL DEFAULT '',
-  `CN` varchar(255) NOT NULL DEFAULT '',
-  `subject` varchar(1024) NOT NULL,
   `keytype` char(2) NOT NULL DEFAULT 'NS',
   `codesign` tinyint(1) NOT NULL DEFAULT '0',
   `md` enum('md5','sha1','sha256','sha512') NOT NULL DEFAULT 'sha512',
@@ -168,6 +166,16 @@ CREATE TABLE `certs` (
   KEY `emailcrt` (`crt_name`)
 ) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
 
+
+DROP TABLE IF EXISTS `certAvas`;
+CREATE TABLE `certAvas` (
+  `certid` int(11) NOT NULL,
+  `name` varchar(20) NOT NULL,
+  `value` varchar(255) NOT NULL,
+
+  PRIMARY KEY (`certid`, `name`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
 DROP TABLE IF EXISTS `clientcerts`;
 CREATE TABLE `clientcerts` (
   `id` int(11) NOT NULL,
index 0c63c2cdee088add0a37f51154cd01a41863d76d..6971b5e9f528d6fe6ee36490eba6697913a0c8d6 100644 (file)
@@ -11,8 +11,10 @@ import java.security.cert.X509Certificate;
 import java.sql.Date;
 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;
@@ -112,8 +114,6 @@ public class Certificate {
 
     private String serial;
 
-    private String dn;
-
     private String md;
 
     private String csrName;
@@ -128,12 +128,20 @@ public class Certificate {
 
     private CertificateProfile profile;
 
-    public Certificate(User owner, String dn, String md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException {
+    private HashMap<String, String> dn;
+
+    private String dnString;
+
+    public Certificate(User owner, HashMap<String, String> dn, String md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException {
         if ( !owner.canIssue(profile)) {
             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;
@@ -142,14 +150,16 @@ public class Certificate {
     }
 
     private Certificate(String serial) {
-        GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id,subject, md, csr_name, crt_name,memid, profile FROM `certs` WHERE serial=?");
+        //
+        String concat = "group_concat(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')))";
+        GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT certs.id, " + concat + " as subject, md, csr_name, crt_name,memid, profile 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()) {
             throw new IllegalArgumentException("Invalid mid " + serial);
         }
         this.id = rs.getInt(1);
-        dn = rs.getString(2);
+        dnString = rs.getString(2);
         md = rs.getString(3);
         csrName = rs.getString(4);
         crtName = rs.getString(5);
@@ -238,21 +248,14 @@ public class Certificate {
         }
         Notary.writeUserAgreement(owner, "CCA", "issue certificate", "", true, 0);
 
-        GigiPreparedStatement inserter = DatabaseConnection.getInstance().prepare("INSERT INTO certs SET md=?, subject=?, csr_type=?, crt_name='', memid=?, profile=?");
+        GigiPreparedStatement inserter = DatabaseConnection.getInstance().prepare("INSERT INTO certs SET md=?, csr_type=?, crt_name='', memid=?, profile=?");
         inserter.setString(1, md);
-        inserter.setString(2, dn);
-        inserter.setString(3, csrType.toString());
-        inserter.setInt(4, owner.getId());
-        inserter.setInt(5, profile.getId());
+        inserter.setString(2, csrType.toString());
+        inserter.setInt(3, owner.getId());
+        inserter.setInt(4, profile.getId());
         inserter.execute();
         id = inserter.lastInsertId();
-        File csrFile = KeyStorage.locateCsr(id);
-        csrName = csrFile.getPath();
-        FileOutputStream fos = new FileOutputStream(csrFile);
-        fos.write(csr.getBytes());
-        fos.close();
 
-        // TODO draft to insert SANs
         GigiPreparedStatement san = DatabaseConnection.getInstance().prepare("INSERT INTO subjectAlternativeNames SET certId=?, contents=?, type=?");
         for (SubjectAlternateName subjectAlternateName : sans) {
             san.setInt(1, id);
@@ -261,6 +264,19 @@ public class Certificate {
             san.execute();
         }
 
+        GigiPreparedStatement insertAVA = DatabaseConnection.getInstance().prepare("INSERT 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();
+        FileOutputStream fos = new FileOutputStream(csrFile);
+        fos.write(csr.getBytes());
+        fos.close();
+
         GigiPreparedStatement updater = DatabaseConnection.getInstance().prepare("UPDATE certs SET csr_name=? WHERE id=?");
         updater.setString(1, csrName);
         updater.setInt(2, id);
@@ -311,7 +327,7 @@ public class Certificate {
     }
 
     public String getDistinguishedName() {
-        return dn;
+        return dnString;
     }
 
     public String getMessageDigest() {
@@ -340,4 +356,25 @@ public class Certificate {
         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;
+    }
 }
index f6b35f9644d0c61a5c430db7bd87740034d133e6..8076afe90ecbdf7cbcb5d525b7fad15479192db2 100644 (file)
@@ -133,11 +133,6 @@ public class CertificateIssueForm extends Form {
         return result;
     }
 
-    public static String escapeAVA(String value) {
-
-        return value.replace("\\", "\\\\").replace("/", "\\/");
-    }
-
     @Override
     public boolean submit(PrintWriter out, HttpServletRequest req) {
         String csr = req.getParameter("CSR");
@@ -298,10 +293,9 @@ public class CertificateIssueForm extends Form {
                         outputError(out, req, "The real name entered cannot be verified with your account.");
                     }
 
-                    final StringBuffer subject = new StringBuffer();
+                    HashMap<String, String> subject = new HashMap<>();
                     if (server && pDNS != null) {
-                        subject.append("/commonName=");
-                        subject.append(escapeAVA(pDNS));
+                        subject.put("CN", pDNS);
                         if (pMail != null) {
                             outputError(out, req, "No email is included in this certificate.");
                         }
@@ -310,24 +304,17 @@ public class CertificateIssueForm extends Form {
                             outputError(out, req, "No real name is included in this certificate.");
                         }
                     } else {
-                        subject.append("/commonName=");
-                        subject.append(escapeAVA(CN));
+                        subject.put("CN", CN);
                         if (pMail != null) {
-                            subject.append("/emailAddress=");
-                            subject.append(escapeAVA(pMail));
+                            subject.put("EMAIL", pMail);
                         }
                     }
                     if (org != null) {
-                        subject.append("/O=");
-                        subject.append(escapeAVA(org.getName()));
-                        subject.append("/C=");
-                        subject.append(escapeAVA(org.getState()));
-                        subject.append("/ST=");
-                        subject.append(escapeAVA(org.getProvince()));
-                        subject.append("/L=");
-                        subject.append(escapeAVA(org.getCity()));
-                        subject.append("/OU=");
-                        subject.append(escapeAVA(ou));
+                        subject.put("O", org.getName());
+                        subject.put("C", org.getState());
+                        subject.put("ST", org.getProvince());
+                        subject.put("L", org.getCity());
+                        subject.put("OU", ou);
                     }
                     if (req.getParameter("CCA") == null) {
                         outputError(out, req, "You need to accept the CCA.");
@@ -336,7 +323,7 @@ public class CertificateIssueForm extends Form {
                         return false;
                     }
 
-                    result = new Certificate(LoginPage.getUser(req), subject.toString(), selectedDigest.toString(), //
+                    result = new Certificate(LoginPage.getUser(req), subject, selectedDigest.toString(), //
                             this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
                     result.issue(issueDate.getFrom(), issueDate.getTo()).waitFor(60000);
                     return true;
index f494befbe5994fbba1c5ac2128be279214cf3030..fd58dc3c6270705d52f3170f2a96a037e40d594a 100644 (file)
@@ -31,7 +31,7 @@ public class TestCertificate extends ManagedTest {
     public void testClientCertLoginStates() throws IOException, GeneralSecurityException, SQLException, InterruptedException, GigiApiException {
         KeyPair kp = generateKeypair();
         String key1 = generatePEMCSR(kp, "CN=testmail@example.com");
-        Certificate c = new Certificate(u, "/CN=testmail@example.com", "sha256", key1, CSRType.CSR, CertificateProfile.getById(1));
+        Certificate c = new Certificate(u, Certificate.buildDN("CN", "testmail@example.com"), "sha256", key1, CSRType.CSR, CertificateProfile.getById(1));
         final PrivateKey pk = kp.getPrivate();
         c.issue(null, "2y").waitFor(60000);
         final X509Certificate ce = c.cert();
@@ -42,7 +42,7 @@ public class TestCertificate extends ManagedTest {
     public void testSANs() throws IOException, GeneralSecurityException, SQLException, InterruptedException, GigiApiException {
         KeyPair kp = generateKeypair();
         String key = generatePEMCSR(kp, "CN=testmail@example.com");
-        Certificate c = new Certificate(u, "/CN=testmail@example.com", "sha256", key, CSRType.CSR, CertificateProfile.getById(1),//
+        Certificate c = new Certificate(u, Certificate.buildDN("CN", "testmail@example.com"), "sha256", key, CSRType.CSR, CertificateProfile.getById(1),//
                 new SubjectAlternateName(SANType.EMAIL, "testmail@example.com"), new SubjectAlternateName(SANType.DNS, "testmail.example.com"));
 
         testFails(CertificateStatus.DRAFT, c);
@@ -93,7 +93,7 @@ public class TestCertificate extends ManagedTest {
     public void testCertLifeCycle() throws IOException, GeneralSecurityException, SQLException, InterruptedException, GigiApiException {
         KeyPair kp = generateKeypair();
         String key = generatePEMCSR(kp, "CN=testmail@example.com");
-        Certificate c = new Certificate(u, "/CN=testmail@example.com", "sha256", key, CSRType.CSR, CertificateProfile.getById(1));
+        Certificate c = new Certificate(u, Certificate.buildDN("CN", "testmail@example.com"), "sha256", key, CSRType.CSR, CertificateProfile.getById(1));
         final PrivateKey pk = kp.getPrivate();
 
         testFails(CertificateStatus.DRAFT, c);
index f20ee261a448c2a60a4d9cf239d413d8af263a41..28c0b20a7b207294d16a4372d785f5c6fcf5ecc9 100644 (file)
@@ -50,7 +50,7 @@ public class TestCrossDomainAccess extends ManagedTest {
         int id = createVerifiedUser("Kurti", "Hansel", email, TEST_PASSWORD);
         KeyPair kp = generateKeypair();
         String key1 = generatePEMCSR(kp, "CN=" + email);
-        Certificate c = new Certificate(User.getById(id), "/CN=" + email, "sha256", key1, CSRType.CSR, CertificateProfile.getById(1));
+        Certificate c = new Certificate(User.getById(id), Certificate.buildDN("CN", email), "sha256", key1, CSRType.CSR, CertificateProfile.getById(1));
         final PrivateKey pk = kp.getPrivate();
         c.issue(null, "2y").waitFor(60000);
         final X509Certificate ce = c.cert();
index 1e583b788b62ed9759aab3040f47e8424573ee09..20dd6ae9de11d557633dc7abdbf2f005ad8b0c5a 100644 (file)
@@ -27,7 +27,7 @@ public class TestSeparateSessionScope extends ManagedTest {
         String cookie = login(mail, TEST_PASSWORD);
         KeyPair kp = generateKeypair();
         String csr = generatePEMCSR(kp, "CN=felix@dogcraft.de");
-        Certificate c = new Certificate(User.getById(user), "/CN=testmail@example.com", "sha256", csr, CSRType.CSR, CertificateProfile.getById(1));
+        Certificate c = new Certificate(User.getById(user), Certificate.buildDN("CN", "testmail@example.com"), "sha256", csr, CSRType.CSR, CertificateProfile.getById(1));
         final PrivateKey pk = kp.getPrivate();
         c.issue(null, "2y").waitFor(60000);
         final X509Certificate ce = c.cert();
index 71ee55ebd64659757f53be836f8cbbfe32a0c611..007d570b435b6ff32e15420f209610cb47d94c5b 100644 (file)
@@ -139,7 +139,7 @@ public class TestSSL extends PingTest {
     private void createCertificate(String test, CertificateProfile profile) throws GeneralSecurityException, IOException, SQLException, InterruptedException, GigiApiException {
         kp = generateKeypair();
         String csr = generatePEMCSR(kp, "CN=" + test);
-        c = new Certificate(User.getById(userid), "/CN=" + test, "sha256", csr, CSRType.CSR, profile);
+        c = new Certificate(User.getById(userid), Certificate.buildDN("CN", test), "sha256", csr, CSRType.CSR, profile);
         c.issue(null, "2y").waitFor(60000);
     }
 
index d3b168a995547ebdc19af869cac4d59cade577e5..04602d82c7b66db2ba0c8799a0366903219f68e4 100644 (file)
@@ -18,12 +18,14 @@ import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import java.util.Date;
+import java.util.HashMap;
 import java.util.Properties;
 import java.util.TimeZone;
 
 import org.cacert.gigi.database.DatabaseConnection;
 import org.cacert.gigi.database.GigiPreparedStatement;
 import org.cacert.gigi.database.GigiResultSet;
+import org.cacert.gigi.dbObjects.Certificate;
 import org.cacert.gigi.dbObjects.Certificate.CSRType;
 import org.cacert.gigi.output.DateSelector;
 
@@ -77,7 +79,7 @@ public class SimpleSigner {
             throw new IllegalStateException("already running");
         }
         running = true;
-        readyCerts = DatabaseConnection.getInstance().prepare("SELECT certs.id AS id, certs.csr_name, certs.subject, jobs.id AS jobid, csr_type, md, keyUsage, extendedKeyUsage, executeFrom, executeTo, rootcert FROM jobs " + //
+        readyCerts = DatabaseConnection.getInstance().prepare("SELECT certs.id AS id, certs.csr_name, jobs.id AS jobid, csr_type, md, keyUsage, extendedKeyUsage, executeFrom, executeTo, rootcert FROM jobs " + //
                 "INNER JOIN certs ON certs.id=jobs.targetId " + //
                 "INNER JOIN profiles ON profiles.id=certs.profile " + //
                 "WHERE jobs.state='open' "//
@@ -257,7 +259,17 @@ public class SimpleSigner {
                 } else if (rootcert == 1) {
                     ca = "assured";
                 }
-
+                HashMap<String, String> subj = new HashMap<>();
+                GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT name, value FROM certAvas WHERE certId=?");
+                ps.setInt(1, rs.getInt("id"));
+                GigiResultSet rs2 = ps.executeQuery();
+                while (rs2.next()) {
+                    subj.put(rs2.getString("name"), rs2.getString("value"));
+                }
+                if (subj.size() == 0) {
+                    subj.put("CN", "<empty>");
+                    System.out.println("WARNING: DN was empty");
+                }
                 String[] call = new String[] {
                         "openssl", "ca",//
                         "-in",
@@ -280,7 +292,7 @@ public class SimpleSigner {
                         "../" + f.getName(),//
 
                         "-subj",
-                        rs.getString("subject"),//
+                        Certificate.stringifyDN(subj),//
                         "-config",
                         "../selfsign.config"//