]> WPIA git - gigi.git/blobdiff - util-testing/org/cacert/gigi/util/SimpleSigner.java
fix: Avoid NPE if the CA's files cannot be listed
[gigi.git] / util-testing / org / cacert / gigi / util / SimpleSigner.java
index d7bfee5fafdab8aab2c8cab356a5a13395d5cff1..1cc9e9eeae6e8e7851e540113a6cc1da1fda9ce8 100644 (file)
@@ -13,8 +13,6 @@ import java.math.BigInteger;
 import java.nio.file.Paths;
 import java.security.GeneralSecurityException;
 import java.security.KeyFactory;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
 import java.security.NoSuchAlgorithmException;
 import java.security.PrivateKey;
 import java.security.PublicKey;
@@ -27,7 +25,6 @@ import java.sql.SQLException;
 import java.sql.Timestamp;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
-import java.util.Arrays;
 import java.util.Base64;
 import java.util.Calendar;
 import java.util.Date;
@@ -43,9 +40,9 @@ import javax.security.auth.x500.X500Principal;
 
 import org.cacert.gigi.crypto.SPKAC;
 import org.cacert.gigi.database.DatabaseConnection;
+import org.cacert.gigi.database.DatabaseConnection.Link;
 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.dbObjects.Certificate.SANType;
 import org.cacert.gigi.dbObjects.Certificate.SubjectAlternateName;
@@ -93,19 +90,6 @@ public class SimpleSigner {
     }
 
     public static void main(String[] args) throws IOException, SQLException, InterruptedException {
-        if (false) {
-            try {
-                KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
-                kpg.initialize(2048);
-                KeyPair kp = kpg.generateKeyPair();
-                X500Principal xp = new X500Principal(genX500Name(Certificate.buildDN("CN", "uiae")).getEncoded());
-                byte[] i = generateCert(kp.getPublic(), kp.getPrivate(), Certificate.buildDN("CN", "uiae"), xp, Arrays.<SubjectAlternateName>asList(), new Date(), new Date(System.currentTimeMillis() + 1000 * 60 * 60), Digest.SHA512, "clientAuth");
-                System.out.println(Base64.getMimeEncoder().encodeToString(i));
-            } catch (GeneralSecurityException e) {
-                e.printStackTrace();
-            }
-            return;
-        }
         Properties p = new Properties();
         try (Reader reader = new InputStreamReader(new FileInputStream("config/gigi.properties"), "UTF-8")) {
             p.load(reader);
@@ -133,36 +117,52 @@ public class SimpleSigner {
             throw new IllegalStateException("already running");
         }
         running = true;
-        readyCerts = DatabaseConnection.getInstance().prepare("SELECT certs.id AS id, certs.csr_name, jobs.id AS jobid, csr_type, md, `executeFrom`, `executeTo`, profile FROM jobs " + //
-                "INNER JOIN certs ON certs.id=jobs.`targetId` " + //
-                "INNER JOIN profiles ON profiles.id=certs.profile " + //
-                "WHERE jobs.state='open' "//
-                + "AND task='sign'");
 
-        getSANSs = DatabaseConnection.getInstance().prepare("SELECT contents, type FROM `subjectAlternativeNames` " + //
-                "WHERE `certId`=?");
+        runner = new Thread() {
 
-        updateMail = DatabaseConnection.getInstance().prepare("UPDATE certs SET crt_name=?," + " created=NOW(), serial=?, caid=? WHERE id=?");
-        warnMail = DatabaseConnection.getInstance().prepare("UPDATE jobs SET warning=warning+1, state=IF(warning<3, 'open','error') WHERE id=?");
+            @Override
+            public void run() {
+                try (Link l = DatabaseConnection.newLink(false)) {
+                    readyCerts = new GigiPreparedStatement("SELECT certs.id AS id, certs.csr_name, jobs.id AS jobid, csr_type, md, `executeFrom`, `executeTo`, profile FROM jobs " + //
+                            "INNER JOIN certs ON certs.id=jobs.`targetId` " + //
+                            "INNER JOIN profiles ON profiles.id=certs.profile " + //
+                            "WHERE jobs.state='open' "//
+                            + "AND task='sign'");
 
-        revoke = DatabaseConnection.getInstance().prepare("SELECT certs.id, certs.csr_name,jobs.id FROM jobs INNER JOIN certs ON jobs.`targetId`=certs.id" + " WHERE jobs.state='open' AND task='revoke'");
-        revokeCompleted = DatabaseConnection.getInstance().prepare("UPDATE certs SET revoked=NOW() WHERE id=?");
+                    getSANSs = new GigiPreparedStatement("SELECT contents, type FROM `subjectAlternativeNames` " + //
+                            "WHERE `certId`=?");
 
-        finishJob = DatabaseConnection.getInstance().prepare("UPDATE jobs SET state='done' WHERE id=?");
+                    updateMail = new GigiPreparedStatement("UPDATE certs SET crt_name=?," + " created=NOW(), serial=?, caid=? WHERE id=?");
+                    warnMail = new GigiPreparedStatement("UPDATE jobs SET warning=warning+1, state=IF(warning<3, 'open','error') WHERE id=?");
 
-        locateCA = DatabaseConnection.getInstance().prepare("SELECT id FROM cacerts WHERE keyname=?");
+                    revoke = new GigiPreparedStatement("SELECT certs.id, certs.csr_name,jobs.id FROM jobs INNER JOIN certs ON jobs.`targetId`=certs.id" + " WHERE jobs.state='open' AND task='revoke'");
+                    revokeCompleted = new GigiPreparedStatement("UPDATE certs SET revoked=NOW() WHERE id=?");
 
-        runner = new Thread() {
+                    finishJob = new GigiPreparedStatement("UPDATE jobs SET state='done' WHERE id=?");
 
-            @Override
-            public void run() {
-                work();
+                    locateCA = new GigiPreparedStatement("SELECT id FROM cacerts WHERE keyname=?");
+
+                    work();
+                } catch (InterruptedException e) {
+                    throw new Error(e);
+                }
             }
 
         };
         runner.start();
     }
 
+    public static void ping() {
+        synchronized (SimpleSigner.class) {
+            SimpleSigner.class.notifyAll();
+            try {
+                SimpleSigner.class.wait(2000);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+        }
+    }
+
     private synchronized static void work() {
         try {
             gencrl();
@@ -177,6 +177,7 @@ public class SimpleSigner {
                 signCertificates();
                 revokeCertificates();
 
+                SimpleSigner.class.notifyAll();
                 SimpleSigner.class.wait(5000);
             } catch (IOException e) {
                 e.printStackTrace();
@@ -193,7 +194,6 @@ public class SimpleSigner {
         boolean worked = false;
         while (rs.next()) {
             int id = rs.getInt(1);
-            File crt = KeyStorage.locateCrt(id);
             worked = true;
             System.out.println("Revoke faked: " + id);
             revokeCompleted.setInt(1, id);
@@ -211,7 +211,8 @@ public class SimpleSigner {
             return;
         }
         String[] call = new String[] {
-                "openssl", "ca",//
+                "openssl",
+                "ca",//
                 "-cert",
                 "../unassured.crt",//
                 "-keyfile",
@@ -231,8 +232,6 @@ public class SimpleSigner {
         }
     }
 
-    private static int counter = 0;
-
     private static void signCertificates() throws SQLException {
         GigiResultSet rs = readyCerts.executeQuery();
 
@@ -294,18 +293,18 @@ public class SimpleSigner {
                 try (FileInputStream inStream = new FileInputStream("signer/profiles/" + s)) {
                     caP.load(inStream);
                 }
-                String ca = caP.getProperty("ca") + "_2015_1";
 
                 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()) {
-                    String name = rs2.getString("name");
-                    if (name.equals("EMAIL")) {
-                        name = "emailAddress";
+                try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT name, value FROM `certAvas` WHERE `certId`=?")) {
+                    ps.setInt(1, rs.getInt("id"));
+                    GigiResultSet rs2 = ps.executeQuery();
+                    while (rs2.next()) {
+                        String name = rs2.getString("name");
+                        if (name.equals("EMAIL")) {
+                            name = "emailAddress";
+                        }
+                        subj.put(name, rs2.getString("value"));
                     }
-                    subj.put(name, rs2.getString("value"));
                 }
                 if (subj.size() == 0) {
                     subj.put("CN", "<empty>");
@@ -328,9 +327,21 @@ public class SimpleSigner {
                     PKCS10 p10 = new PKCS10(PEM.decode("(NEW )?CERTIFICATE REQUEST", new String(data, "UTF-8")));
                     pk = p10.getSubjectPublicKeyInfo();
                 }
-                PrivateKey i = loadOpensslKey(new File("signer/ca/" + ca + "/ca.key"));
+                String ca = caP.getProperty("ca") + "_2015_1";
+                File parent = new File("signer/ca");
+                File[] caFiles = parent.listFiles();
+                if (null == caFiles) {
+                    caFiles = new File[0];
+                }
+                for (File f : caFiles) {
+                    if (f.getName().startsWith(caP.getProperty("ca"))) {
+                        ca = f.getName();
+                        break;
+                    }
+                }
+                File caKey = new File(parent, ca + "/ca.key");
+                PrivateKey i = loadOpensslKey(caKey);
 
-                String[] call;
                 X509Certificate root = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new FileInputStream("signer/ca/" + ca + "/ca.crt"));
                 byte[] cert = generateCert(pk, i, subj, root.getSubjectX500Principal(), altnames, fromDate, toDate, Digest.valueOf(rs.getString("md").toUpperCase()), caP.getProperty("eku"));
                 PrintWriter out = new PrintWriter(crt);
@@ -338,18 +349,6 @@ public class SimpleSigner {
                 out.println(Base64.getMimeEncoder().encodeToString(cert));
                 out.println("-----END CERTIFICATE-----");
                 out.close();
-                // synchronized (sdf) {
-                /*
-                 * call = new String[] { "openssl", "ca",// "-in", "../../" +
-                 * csrname,// "-cert", "../" + ca + ".crt",// "-keyfile", "../"
-                 * + ca + ".key",// "-out", "../../" + crt.getPath(),// "-utf8",
-                 * "-startdate", sdf.format(fromDate),// "-enddate",
-                 * sdf.format(toDate),// "-batch",// "-md",
-                 * rs.getString("md"),// "-extfile", "../" + f.getName(),//
-                 * "-subj", Certificate.stringifyDN(subj),// "-config",
-                 * "../selfsign.config"// };
-                 */
-                // }
 
                 try (InputStream is = new FileInputStream(crt)) {
                     locateCA.setString(1, ca);
@@ -404,7 +403,7 @@ public class SimpleSigner {
         return i;
     }
 
-    private static synchronized byte[] generateCert(PublicKey pk, PrivateKey prk, Map<String, String> subj, X500Principal issuer, List<SubjectAlternateName> altnames, Date fromDate, Date toDate, Digest digest, String eku) throws IOException, GeneralSecurityException {
+    public static synchronized byte[] generateCert(PublicKey pk, PrivateKey prk, Map<String, String> subj, X500Principal issuer, List<SubjectAlternateName> altnames, Date fromDate, Date toDate, Digest digest, String eku) throws IOException, GeneralSecurityException {
         File f = Paths.get("signer", "serial").toFile();
         if ( !f.exists()) {
             try (FileOutputStream fos = new FileOutputStream(f)) {
@@ -490,17 +489,20 @@ public class SimpleSigner {
             // ByteArrayInputStream(cert.toByteArray()));
             // c.verify(pk); only for self-signeds
 
-            return cert.toByteArray();
+            byte[] res = cert.toByteArray();
+            cert.close();
+            return res;
         }
 
     }
 
     private static byte[] generateKU() throws IOException {
-        DerOutputStream dos = new DerOutputStream();
-        dos.putBitString(new byte[] {
-            (byte) 0b10101000
-        });
-        return dos.toByteArray();
+        try (DerOutputStream dos = new DerOutputStream()) {
+            dos.putBitString(new byte[] {
+                    (byte) 0b10101000
+            });
+            return dos.toByteArray();
+        }
     }
 
     private static byte[] generateEKU(String eku) throws IOException {
@@ -521,6 +523,9 @@ public class SimpleSigner {
             case "emailProtection":
                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.4");
                 break;
+            case "OCSPSigning":
+                oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.9");
+                break;
 
             default:
                 throw new Error(name);
@@ -533,7 +538,7 @@ public class SimpleSigner {
         return dos.toByteArray();
     }
 
-    private static X500Name genX500Name(Map<String, String> subj) throws IOException {
+    public static X500Name genX500Name(Map<String, String> subj) throws IOException {
         LinkedList<RDN> rdns = new LinkedList<>();
         for (Entry<String, String> i : subj.entrySet()) {
             RDN rdn = genRDN(i);
@@ -585,9 +590,11 @@ public class SimpleSigner {
             };
             break;
         default:
+            dos.close();
             throw new Error("unknown RDN-type: " + key);
         }
         RDN rdn = new RDN(new AVA(new ObjectIdentifier(oid), new DerValue(dos.toByteArray())));
+        dos.close();
         return rdn;
     }
 
@@ -608,6 +615,7 @@ public class SimpleSigner {
             } else if (san.getType() == SANType.EMAIL) {
                 type = (byte) GeneralNameInterface.NAME_RFC822;
             } else {
+                SANContent.close();
                 throw new Error("" + san.getType());
             }
             SANContent.write(DerValue.createTag(DerValue.TAG_CONTEXT, false, type), san.getName().getBytes("UTF-8"));
@@ -615,6 +623,8 @@ public class SimpleSigner {
         DerOutputStream SANSeqContent = new DerOutputStream();
         SANSeqContent.write(DerValue.tag_Sequence, SANContent);
         byte[] byteArray = SANSeqContent.toByteArray();
+        SANContent.close();
+        SANSeqContent.close();
         return byteArray;
     }
 }