]> WPIA git - gigi.git/blob - util-testing/org/cacert/gigi/util/SimpleSigner.java
upd: greatly improve speed at all cert-generating test cases
[gigi.git] / util-testing / org / cacert / gigi / util / SimpleSigner.java
1 package org.cacert.gigi.util;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileNotFoundException;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.InputStreamReader;
10 import java.io.PrintWriter;
11 import java.io.Reader;
12 import java.math.BigInteger;
13 import java.nio.file.Paths;
14 import java.security.GeneralSecurityException;
15 import java.security.KeyFactory;
16 import java.security.NoSuchAlgorithmException;
17 import java.security.PrivateKey;
18 import java.security.PublicKey;
19 import java.security.Signature;
20 import java.security.cert.CertificateFactory;
21 import java.security.cert.X509Certificate;
22 import java.security.spec.InvalidKeySpecException;
23 import java.security.spec.PKCS8EncodedKeySpec;
24 import java.sql.SQLException;
25 import java.sql.Timestamp;
26 import java.text.ParseException;
27 import java.text.SimpleDateFormat;
28 import java.util.Base64;
29 import java.util.Calendar;
30 import java.util.Date;
31 import java.util.HashMap;
32 import java.util.LinkedList;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.Properties;
37 import java.util.TimeZone;
38
39 import javax.security.auth.x500.X500Principal;
40
41 import org.cacert.gigi.crypto.SPKAC;
42 import org.cacert.gigi.database.DatabaseConnection;
43 import org.cacert.gigi.database.DatabaseConnection.Link;
44 import org.cacert.gigi.database.GigiPreparedStatement;
45 import org.cacert.gigi.database.GigiResultSet;
46 import org.cacert.gigi.dbObjects.Certificate.CSRType;
47 import org.cacert.gigi.dbObjects.Certificate.SANType;
48 import org.cacert.gigi.dbObjects.Certificate.SubjectAlternateName;
49 import org.cacert.gigi.dbObjects.CertificateProfile;
50 import org.cacert.gigi.dbObjects.Digest;
51 import org.cacert.gigi.output.DateSelector;
52
53 import sun.security.pkcs10.PKCS10;
54 import sun.security.util.DerOutputStream;
55 import sun.security.util.DerValue;
56 import sun.security.util.ObjectIdentifier;
57 import sun.security.x509.AVA;
58 import sun.security.x509.AlgorithmId;
59 import sun.security.x509.GeneralNameInterface;
60 import sun.security.x509.RDN;
61 import sun.security.x509.X500Name;
62
63 public class SimpleSigner {
64
65     private static GigiPreparedStatement warnMail;
66
67     private static GigiPreparedStatement updateMail;
68
69     private static GigiPreparedStatement readyCerts;
70
71     private static GigiPreparedStatement getSANSs;
72
73     private static GigiPreparedStatement revoke;
74
75     private static GigiPreparedStatement revokeCompleted;
76
77     private static GigiPreparedStatement finishJob;
78
79     private static GigiPreparedStatement locateCA;
80
81     private static volatile boolean running = true;
82
83     private static Thread runner;
84
85     private static SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss'Z'");
86
87     static {
88         TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
89         sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
90     }
91
92     public static void main(String[] args) throws IOException, SQLException, InterruptedException {
93         Properties p = new Properties();
94         try (Reader reader = new InputStreamReader(new FileInputStream("config/gigi.properties"), "UTF-8")) {
95             p.load(reader);
96         }
97         DatabaseConnection.init(p);
98
99         runSigner();
100     }
101
102     public static void stopSigner() throws InterruptedException {
103         Thread capturedRunner;
104         synchronized (SimpleSigner.class) {
105             if (runner == null) {
106                 throw new IllegalStateException("already stopped");
107             }
108             capturedRunner = runner;
109             running = false;
110             SimpleSigner.class.notifyAll();
111         }
112         capturedRunner.join();
113     }
114
115     public synchronized static void runSigner() throws SQLException, IOException, InterruptedException {
116         if (runner != null) {
117             throw new IllegalStateException("already running");
118         }
119         running = true;
120
121         runner = new Thread() {
122
123             @Override
124             public void run() {
125                 try (Link l = DatabaseConnection.newLink(false)) {
126                     readyCerts = new GigiPreparedStatement("SELECT certs.id AS id, certs.csr_name, jobs.id AS jobid, csr_type, md, `executeFrom`, `executeTo`, profile FROM jobs " + //
127                             "INNER JOIN certs ON certs.id=jobs.`targetId` " + //
128                             "INNER JOIN profiles ON profiles.id=certs.profile " + //
129                             "WHERE jobs.state='open' "//
130                             + "AND task='sign'");
131
132                     getSANSs = new GigiPreparedStatement("SELECT contents, type FROM `subjectAlternativeNames` " + //
133                             "WHERE `certId`=?");
134
135                     updateMail = new GigiPreparedStatement("UPDATE certs SET crt_name=?," + " created=NOW(), serial=?, caid=? WHERE id=?");
136                     warnMail = new GigiPreparedStatement("UPDATE jobs SET warning=warning+1, state=IF(warning<3, 'open','error') WHERE id=?");
137
138                     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'");
139                     revokeCompleted = new GigiPreparedStatement("UPDATE certs SET revoked=NOW() WHERE id=?");
140
141                     finishJob = new GigiPreparedStatement("UPDATE jobs SET state='done' WHERE id=?");
142
143                     locateCA = new GigiPreparedStatement("SELECT id FROM cacerts WHERE keyname=?");
144
145                     work();
146                 } catch (InterruptedException e) {
147                     throw new Error(e);
148                 }
149             }
150
151         };
152         runner.start();
153     }
154
155     public static void ping() {
156         synchronized (SimpleSigner.class) {
157             SimpleSigner.class.notifyAll();
158             try {
159                 SimpleSigner.class.wait(2000);
160             } catch (InterruptedException e) {
161                 e.printStackTrace();
162             }
163         }
164     }
165
166     private synchronized static void work() {
167         try {
168             gencrl();
169         } catch (IOException e2) {
170             e2.printStackTrace();
171         } catch (InterruptedException e2) {
172             e2.printStackTrace();
173         }
174
175         while (running) {
176             try {
177                 signCertificates();
178                 revokeCertificates();
179
180                 SimpleSigner.class.notifyAll();
181                 SimpleSigner.class.wait(5000);
182             } catch (IOException e) {
183                 e.printStackTrace();
184             } catch (SQLException e) {
185                 e.printStackTrace();
186             } catch (InterruptedException e1) {
187             }
188         }
189         runner = null;
190     }
191
192     private static void revokeCertificates() throws SQLException, IOException, InterruptedException {
193         GigiResultSet rs = revoke.executeQuery();
194         boolean worked = false;
195         while (rs.next()) {
196             int id = rs.getInt(1);
197             worked = true;
198             System.out.println("Revoke faked: " + id);
199             revokeCompleted.setInt(1, id);
200             revokeCompleted.execute();
201             finishJob.setInt(1, rs.getInt(3));
202             finishJob.execute();
203         }
204         if (worked) {
205             gencrl();
206         }
207     }
208
209     private static void gencrl() throws IOException, InterruptedException {
210         if (true) {
211             return;
212         }
213         String[] call = new String[] {
214                 "openssl", "ca",//
215                 "-cert",
216                 "../unassured.crt",//
217                 "-keyfile",
218                 "../unassured.key",//
219                 "-gencrl",//
220                 "-crlhours",//
221                 "12",//
222                 "-out",
223                 "../unassured.crl",//
224                 "-config",
225                 "../selfsign.config"
226
227         };
228         Process p1 = Runtime.getRuntime().exec(call, null, new File("keys/unassured.ca"));
229         if (p1.waitFor() != 0) {
230             System.out.println("Error while generating crl.");
231         }
232     }
233
234     private static int counter = 0;
235
236     private static void signCertificates() throws SQLException {
237         GigiResultSet rs = readyCerts.executeQuery();
238
239         Calendar c = Calendar.getInstance();
240         c.setTimeZone(TimeZone.getTimeZone("UTC"));
241         while (rs.next()) {
242             String csrname = rs.getString("csr_name");
243             int id = rs.getInt("id");
244             System.out.println("sign: " + csrname);
245             try {
246                 String csrType = rs.getString("csr_type");
247                 CSRType ct = CSRType.valueOf(csrType);
248                 File crt = KeyStorage.locateCrt(id);
249
250                 Timestamp from = rs.getTimestamp("executeFrom");
251                 String length = rs.getString("executeTo");
252                 Date fromDate;
253                 Date toDate;
254                 if (from == null) {
255                     fromDate = new Date(System.currentTimeMillis());
256                 } else {
257                     fromDate = new Date(from.getTime());
258                 }
259                 if (length.endsWith("m") || length.endsWith("y")) {
260                     String num = length.substring(0, length.length() - 1);
261                     int inter = Integer.parseInt(num);
262                     c.setTime(fromDate);
263                     if (length.endsWith("m")) {
264                         c.add(Calendar.MONTH, inter);
265                     } else {
266                         c.add(Calendar.YEAR, inter);
267                     }
268                     toDate = c.getTime();
269                 } else {
270                     toDate = DateSelector.getDateFormat().parse(length);
271                 }
272
273                 getSANSs.setInt(1, id);
274                 GigiResultSet san = getSANSs.executeQuery();
275
276                 LinkedList<SubjectAlternateName> altnames = new LinkedList<>();
277                 while (san.next()) {
278                     altnames.add(new SubjectAlternateName(SANType.valueOf(san.getString("type").toUpperCase()), san.getString("contents")));
279                 }
280                 // TODO look them up!
281                 // cfg.println("keyUsage=critical," +
282                 // "digitalSignature, keyEncipherment, keyAgreement");
283                 // cfg.println("extendedKeyUsage=critical," + "clientAuth");
284                 // cfg.close();
285
286                 int profile = rs.getInt("profile");
287                 CertificateProfile cp = CertificateProfile.getById(profile);
288                 String s = cp.getId() + "";
289                 while (s.length() < 4) {
290                     s = "0" + s;
291                 }
292                 s += "-" + cp.getKeyName() + ".cfg";
293                 Properties caP = new Properties();
294                 try (FileInputStream inStream = new FileInputStream("signer/profiles/" + s)) {
295                     caP.load(inStream);
296                 }
297                 String ca = caP.getProperty("ca") + "_2015_1";
298
299                 HashMap<String, String> subj = new HashMap<>();
300                 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT name, value FROM `certAvas` WHERE `certId`=?")) {
301                     ps.setInt(1, rs.getInt("id"));
302                     GigiResultSet rs2 = ps.executeQuery();
303                     while (rs2.next()) {
304                         String name = rs2.getString("name");
305                         if (name.equals("EMAIL")) {
306                             name = "emailAddress";
307                         }
308                         subj.put(name, rs2.getString("value"));
309                     }
310                 }
311                 if (subj.size() == 0) {
312                     subj.put("CN", "<empty>");
313                     System.out.println("WARNING: DN was empty");
314                 }
315                 System.out.println(subj);
316
317                 PublicKey pk;
318                 byte[] data = IOUtils.readURL(new FileInputStream(csrname));
319                 if (ct == CSRType.SPKAC) {
320                     String dt = new String(data, "UTF-8");
321                     if (dt.startsWith("SPKAC=")) {
322                         dt = dt.substring(6);
323                         data = dt.getBytes("UTF-8");
324                         System.out.println(dt);
325                     }
326                     SPKAC sp = new SPKAC(Base64.getDecoder().decode(data));
327                     pk = sp.getPubkey();
328                 } else {
329                     PKCS10 p10 = new PKCS10(PEM.decode("(NEW )?CERTIFICATE REQUEST", new String(data, "UTF-8")));
330                     pk = p10.getSubjectPublicKeyInfo();
331                 }
332                 PrivateKey i = loadOpensslKey(new File("signer/ca/" + ca + "/ca.key"));
333
334                 X509Certificate root = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new FileInputStream("signer/ca/" + ca + "/ca.crt"));
335                 byte[] cert = generateCert(pk, i, subj, root.getSubjectX500Principal(), altnames, fromDate, toDate, Digest.valueOf(rs.getString("md").toUpperCase()), caP.getProperty("eku"));
336                 PrintWriter out = new PrintWriter(crt);
337                 out.println("-----BEGIN CERTIFICATE-----");
338                 out.println(Base64.getMimeEncoder().encodeToString(cert));
339                 out.println("-----END CERTIFICATE-----");
340                 out.close();
341
342                 try (InputStream is = new FileInputStream(crt)) {
343                     locateCA.setString(1, ca);
344                     GigiResultSet caRs = locateCA.executeQuery();
345                     if ( !caRs.next()) {
346                         throw new Error("ca " + ca + " was not found");
347                     }
348
349                     CertificateFactory cf = CertificateFactory.getInstance("X.509");
350                     X509Certificate crtp = (X509Certificate) cf.generateCertificate(is);
351                     BigInteger serial = crtp.getSerialNumber();
352                     updateMail.setString(1, crt.getPath());
353                     updateMail.setString(2, serial.toString(16));
354                     updateMail.setInt(3, caRs.getInt("id"));
355                     updateMail.setInt(4, id);
356                     updateMail.execute();
357
358                     finishJob.setInt(1, rs.getInt("jobid"));
359                     finishJob.execute();
360                     System.out.println("signed: " + id);
361                     continue;
362                 }
363
364             } catch (GeneralSecurityException e) {
365                 e.printStackTrace();
366             } catch (IOException e) {
367                 e.printStackTrace();
368             } catch (ParseException e) {
369                 e.printStackTrace();
370             }
371             System.out.println("Error with: " + id);
372             warnMail.setInt(1, rs.getInt("jobid"));
373             warnMail.execute();
374
375         }
376         rs.close();
377     }
378
379     private static PrivateKey loadOpensslKey(File f) throws FileNotFoundException, IOException, InvalidKeySpecException, NoSuchAlgorithmException {
380         byte[] p8b = PEM.decode("RSA PRIVATE KEY", new String(IOUtils.readURL(new FileInputStream(f))));
381         DerOutputStream dos = new DerOutputStream();
382         dos.putInteger(0);
383         new AlgorithmId(new ObjectIdentifier(new int[] {
384                 1, 2, 840, 113549, 1, 1, 1
385         })).encode(dos);
386         dos.putOctetString(p8b);
387         byte[] ctx = dos.toByteArray();
388         dos.reset();
389         dos.write(DerValue.tag_Sequence, ctx);
390         PKCS8EncodedKeySpec p8 = new PKCS8EncodedKeySpec(dos.toByteArray());
391         PrivateKey i = KeyFactory.getInstance("RSA").generatePrivate(p8);
392         return i;
393     }
394
395     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 {
396         File f = Paths.get("signer", "serial").toFile();
397         if ( !f.exists()) {
398             try (FileOutputStream fos = new FileOutputStream(f)) {
399                 fos.write("1".getBytes("UTF-8"));
400             }
401         }
402         try (FileInputStream fr = new FileInputStream(f)) {
403             byte[] serial = IOUtils.readURL(fr);
404             BigInteger ser = new BigInteger(new String(serial).trim());
405             ser = ser.add(BigInteger.ONE);
406
407             PrintWriter pw = new PrintWriter(f);
408             pw.println(ser);
409             pw.close();
410             if (digest != Digest.SHA256 && digest != Digest.SHA512) {
411                 System.err.println("assuming sha256 either way ;-): " + digest);
412                 digest = Digest.SHA256;
413             }
414             ObjectIdentifier sha512withrsa = new ObjectIdentifier(new int[] {
415                     1, 2, 840, 113549, 1, 1, digest == Digest.SHA256 ? 11 : 13
416             });
417             AlgorithmId aid = new AlgorithmId(sha512withrsa);
418             Signature s = Signature.getInstance(digest == Digest.SHA256 ? "SHA256withRSA" : "SHA512withRSA");
419
420             DerOutputStream cert = new DerOutputStream();
421             DerOutputStream content = new DerOutputStream();
422             {
423                 DerOutputStream version = new DerOutputStream();
424                 version.putInteger(2); // v3
425                 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0), version);
426             }
427             content.putInteger(ser); // Serial
428             aid.encode(content);
429
430             {
431                 content.write(issuer.getEncoded());
432             }
433             {
434                 DerOutputStream notAround = new DerOutputStream();
435                 notAround.putUTCTime(fromDate);
436                 notAround.putUTCTime(toDate);
437                 content.write(DerValue.tag_Sequence, notAround);
438             }
439             {
440
441                 X500Name xn = genX500Name(subj);
442                 content.write(xn.getEncoded());
443             }
444             {
445                 content.write(pk.getEncoded());
446             }
447             {
448                 DerOutputStream extensions = new DerOutputStream();
449                 {
450                     addExtension(extensions, new ObjectIdentifier(new int[] {
451                             2, 5, 29, 17
452                     }), generateSAN(altnames));
453                     addExtension(extensions, new ObjectIdentifier(new int[] {
454                             2, 5, 29, 15
455                     }), generateKU());
456                     addExtension(extensions, new ObjectIdentifier(new int[] {
457                             2, 5, 29, 37
458                     }), generateEKU(eku));
459                 }
460                 DerOutputStream extensionsSeq = new DerOutputStream();
461                 extensionsSeq.write(DerValue.tag_Sequence, extensions);
462                 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3), extensionsSeq);
463             }
464
465             DerOutputStream contentSeq = new DerOutputStream();
466
467             contentSeq.write(DerValue.tag_Sequence, content.toByteArray());
468
469             s.initSign(prk);
470             s.update(contentSeq.toByteArray());
471
472             aid.encode(contentSeq);
473             contentSeq.putBitString(s.sign());
474             cert.write(DerValue.tag_Sequence, contentSeq);
475
476             // X509Certificate c = (X509Certificate)
477             // CertificateFactory.getInstance("X509").generateCertificate(new
478             // ByteArrayInputStream(cert.toByteArray()));
479             // c.verify(pk); only for self-signeds
480
481             byte[] res = cert.toByteArray();
482             cert.close();
483             return res;
484         }
485
486     }
487
488     private static byte[] generateKU() throws IOException {
489         try (DerOutputStream dos = new DerOutputStream()) {
490             dos.putBitString(new byte[] {
491                 (byte) 0b10101000
492             });
493             return dos.toByteArray();
494         }
495     }
496
497     private static byte[] generateEKU(String eku) throws IOException {
498
499         DerOutputStream dos = new DerOutputStream();
500         for (String name : eku.split(",")) {
501             ObjectIdentifier oid;
502             switch (name) {
503             case "serverAuth":
504                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.1");
505                 break;
506             case "clientAuth":
507                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.2");
508                 break;
509             case "codeSigning":
510                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.3");
511                 break;
512             case "emailProtection":
513                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.4");
514                 break;
515             case "OCSPSigning":
516                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.9");
517                 break;
518
519             default:
520                 throw new Error(name);
521             }
522             dos.putOID(oid);
523         }
524         byte[] data = dos.toByteArray();
525         dos.reset();
526         dos.write(DerValue.tag_Sequence, data);
527         return dos.toByteArray();
528     }
529
530     public static X500Name genX500Name(Map<String, String> subj) throws IOException {
531         LinkedList<RDN> rdns = new LinkedList<>();
532         for (Entry<String, String> i : subj.entrySet()) {
533             RDN rdn = genRDN(i);
534             rdns.add(rdn);
535         }
536         return new X500Name(rdns.toArray(new RDN[rdns.size()]));
537     }
538
539     private static RDN genRDN(Entry<String, String> i) throws IOException {
540         DerOutputStream dos = new DerOutputStream();
541         dos.putUTF8String(i.getValue());
542         int[] oid;
543         String key = i.getKey();
544         switch (key) {
545         case "CN":
546             oid = new int[] {
547                     2, 5, 4, 3
548             };
549             break;
550         case "EMAIL":
551         case "emailAddress":
552             oid = new int[] {
553                     1, 2, 840, 113549, 1, 9, 1
554             };
555             break;
556         case "O":
557             oid = new int[] {
558                     2, 5, 4, 10
559             };
560             break;
561         case "OU":
562             oid = new int[] {
563                     2, 5, 4, 11
564             };
565             break;
566         case "ST":
567             oid = new int[] {
568                     2, 5, 4, 8
569             };
570             break;
571         case "L":
572             oid = new int[] {
573                     2, 5, 4, 7
574             };
575             break;
576         case "C":
577             oid = new int[] {
578                     2, 5, 4, 6
579             };
580             break;
581         default:
582             dos.close();
583             throw new Error("unknown RDN-type: " + key);
584         }
585         RDN rdn = new RDN(new AVA(new ObjectIdentifier(oid), new DerValue(dos.toByteArray())));
586         dos.close();
587         return rdn;
588     }
589
590     private static void addExtension(DerOutputStream extensions, ObjectIdentifier oid, byte[] extContent) throws IOException {
591         DerOutputStream SANs = new DerOutputStream();
592         SANs.putOID(oid);
593         SANs.putOctetString(extContent);
594
595         extensions.write(DerValue.tag_Sequence, SANs);
596     }
597
598     private static byte[] generateSAN(List<SubjectAlternateName> altnames) throws IOException {
599         DerOutputStream SANContent = new DerOutputStream();
600         for (SubjectAlternateName san : altnames) {
601             byte type = 0;
602             if (san.getType() == SANType.DNS) {
603                 type = (byte) GeneralNameInterface.NAME_DNS;
604             } else if (san.getType() == SANType.EMAIL) {
605                 type = (byte) GeneralNameInterface.NAME_RFC822;
606             } else {
607                 SANContent.close();
608                 throw new Error("" + san.getType());
609             }
610             SANContent.write(DerValue.createTag(DerValue.TAG_CONTEXT, false, type), san.getName().getBytes("UTF-8"));
611         }
612         DerOutputStream SANSeqContent = new DerOutputStream();
613         SANSeqContent.write(DerValue.tag_Sequence, SANContent);
614         byte[] byteArray = SANSeqContent.toByteArray();
615         SANContent.close();
616         SANSeqContent.close();
617         return byteArray;
618     }
619 }