]> WPIA git - gigi.git/blob - util-testing/org/cacert/gigi/util/SimpleSigner.java
fix: simple signer will now better select a CA
[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",
215                 "ca",//
216                 "-cert",
217                 "../unassured.crt",//
218                 "-keyfile",
219                 "../unassured.key",//
220                 "-gencrl",//
221                 "-crlhours",//
222                 "12",//
223                 "-out",
224                 "../unassured.crl",//
225                 "-config",
226                 "../selfsign.config"
227
228         };
229         Process p1 = Runtime.getRuntime().exec(call, null, new File("keys/unassured.ca"));
230         if (p1.waitFor() != 0) {
231             System.out.println("Error while generating crl.");
232         }
233     }
234
235     private static int counter = 0;
236
237     private static void signCertificates() throws SQLException {
238         GigiResultSet rs = readyCerts.executeQuery();
239
240         Calendar c = Calendar.getInstance();
241         c.setTimeZone(TimeZone.getTimeZone("UTC"));
242         while (rs.next()) {
243             String csrname = rs.getString("csr_name");
244             int id = rs.getInt("id");
245             System.out.println("sign: " + csrname);
246             try {
247                 String csrType = rs.getString("csr_type");
248                 CSRType ct = CSRType.valueOf(csrType);
249                 File crt = KeyStorage.locateCrt(id);
250
251                 Timestamp from = rs.getTimestamp("executeFrom");
252                 String length = rs.getString("executeTo");
253                 Date fromDate;
254                 Date toDate;
255                 if (from == null) {
256                     fromDate = new Date(System.currentTimeMillis());
257                 } else {
258                     fromDate = new Date(from.getTime());
259                 }
260                 if (length.endsWith("m") || length.endsWith("y")) {
261                     String num = length.substring(0, length.length() - 1);
262                     int inter = Integer.parseInt(num);
263                     c.setTime(fromDate);
264                     if (length.endsWith("m")) {
265                         c.add(Calendar.MONTH, inter);
266                     } else {
267                         c.add(Calendar.YEAR, inter);
268                     }
269                     toDate = c.getTime();
270                 } else {
271                     toDate = DateSelector.getDateFormat().parse(length);
272                 }
273
274                 getSANSs.setInt(1, id);
275                 GigiResultSet san = getSANSs.executeQuery();
276
277                 LinkedList<SubjectAlternateName> altnames = new LinkedList<>();
278                 while (san.next()) {
279                     altnames.add(new SubjectAlternateName(SANType.valueOf(san.getString("type").toUpperCase()), san.getString("contents")));
280                 }
281                 // TODO look them up!
282                 // cfg.println("keyUsage=critical," +
283                 // "digitalSignature, keyEncipherment, keyAgreement");
284                 // cfg.println("extendedKeyUsage=critical," + "clientAuth");
285                 // cfg.close();
286
287                 int profile = rs.getInt("profile");
288                 CertificateProfile cp = CertificateProfile.getById(profile);
289                 String s = cp.getId() + "";
290                 while (s.length() < 4) {
291                     s = "0" + s;
292                 }
293                 s += "-" + cp.getKeyName() + ".cfg";
294                 Properties caP = new Properties();
295                 try (FileInputStream inStream = new FileInputStream("signer/profiles/" + s)) {
296                     caP.load(inStream);
297                 }
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                 String ca = caP.getProperty("ca") + "_2015_1";
333                 File parent = new File("signer/ca");
334                 for (File f : parent.listFiles()) {
335                     if (f.getName().startsWith(caP.getProperty("ca"))) {
336                         ca = f.getName();
337                         break;
338                     }
339                 }
340                 File caKey = new File(parent, ca + "/ca.key");
341                 PrivateKey i = loadOpensslKey(caKey);
342
343                 X509Certificate root = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new FileInputStream("signer/ca/" + ca + "/ca.crt"));
344                 byte[] cert = generateCert(pk, i, subj, root.getSubjectX500Principal(), altnames, fromDate, toDate, Digest.valueOf(rs.getString("md").toUpperCase()), caP.getProperty("eku"));
345                 PrintWriter out = new PrintWriter(crt);
346                 out.println("-----BEGIN CERTIFICATE-----");
347                 out.println(Base64.getMimeEncoder().encodeToString(cert));
348                 out.println("-----END CERTIFICATE-----");
349                 out.close();
350
351                 try (InputStream is = new FileInputStream(crt)) {
352                     locateCA.setString(1, ca);
353                     GigiResultSet caRs = locateCA.executeQuery();
354                     if ( !caRs.next()) {
355                         throw new Error("ca " + ca + " was not found");
356                     }
357
358                     CertificateFactory cf = CertificateFactory.getInstance("X.509");
359                     X509Certificate crtp = (X509Certificate) cf.generateCertificate(is);
360                     BigInteger serial = crtp.getSerialNumber();
361                     updateMail.setString(1, crt.getPath());
362                     updateMail.setString(2, serial.toString(16));
363                     updateMail.setInt(3, caRs.getInt("id"));
364                     updateMail.setInt(4, id);
365                     updateMail.execute();
366
367                     finishJob.setInt(1, rs.getInt("jobid"));
368                     finishJob.execute();
369                     System.out.println("signed: " + id);
370                     continue;
371                 }
372
373             } catch (GeneralSecurityException e) {
374                 e.printStackTrace();
375             } catch (IOException e) {
376                 e.printStackTrace();
377             } catch (ParseException e) {
378                 e.printStackTrace();
379             }
380             System.out.println("Error with: " + id);
381             warnMail.setInt(1, rs.getInt("jobid"));
382             warnMail.execute();
383
384         }
385         rs.close();
386     }
387
388     private static PrivateKey loadOpensslKey(File f) throws FileNotFoundException, IOException, InvalidKeySpecException, NoSuchAlgorithmException {
389         byte[] p8b = PEM.decode("RSA PRIVATE KEY", new String(IOUtils.readURL(new FileInputStream(f))));
390         DerOutputStream dos = new DerOutputStream();
391         dos.putInteger(0);
392         new AlgorithmId(new ObjectIdentifier(new int[] {
393                 1, 2, 840, 113549, 1, 1, 1
394         })).encode(dos);
395         dos.putOctetString(p8b);
396         byte[] ctx = dos.toByteArray();
397         dos.reset();
398         dos.write(DerValue.tag_Sequence, ctx);
399         PKCS8EncodedKeySpec p8 = new PKCS8EncodedKeySpec(dos.toByteArray());
400         PrivateKey i = KeyFactory.getInstance("RSA").generatePrivate(p8);
401         return i;
402     }
403
404     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 {
405         File f = Paths.get("signer", "serial").toFile();
406         if ( !f.exists()) {
407             try (FileOutputStream fos = new FileOutputStream(f)) {
408                 fos.write("1".getBytes("UTF-8"));
409             }
410         }
411         try (FileInputStream fr = new FileInputStream(f)) {
412             byte[] serial = IOUtils.readURL(fr);
413             BigInteger ser = new BigInteger(new String(serial).trim());
414             ser = ser.add(BigInteger.ONE);
415
416             PrintWriter pw = new PrintWriter(f);
417             pw.println(ser);
418             pw.close();
419             if (digest != Digest.SHA256 && digest != Digest.SHA512) {
420                 System.err.println("assuming sha256 either way ;-): " + digest);
421                 digest = Digest.SHA256;
422             }
423             ObjectIdentifier sha512withrsa = new ObjectIdentifier(new int[] {
424                     1, 2, 840, 113549, 1, 1, digest == Digest.SHA256 ? 11 : 13
425             });
426             AlgorithmId aid = new AlgorithmId(sha512withrsa);
427             Signature s = Signature.getInstance(digest == Digest.SHA256 ? "SHA256withRSA" : "SHA512withRSA");
428
429             DerOutputStream cert = new DerOutputStream();
430             DerOutputStream content = new DerOutputStream();
431             {
432                 DerOutputStream version = new DerOutputStream();
433                 version.putInteger(2); // v3
434                 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0), version);
435             }
436             content.putInteger(ser); // Serial
437             aid.encode(content);
438
439             {
440                 content.write(issuer.getEncoded());
441             }
442             {
443                 DerOutputStream notAround = new DerOutputStream();
444                 notAround.putUTCTime(fromDate);
445                 notAround.putUTCTime(toDate);
446                 content.write(DerValue.tag_Sequence, notAround);
447             }
448             {
449
450                 X500Name xn = genX500Name(subj);
451                 content.write(xn.getEncoded());
452             }
453             {
454                 content.write(pk.getEncoded());
455             }
456             {
457                 DerOutputStream extensions = new DerOutputStream();
458                 {
459                     addExtension(extensions, new ObjectIdentifier(new int[] {
460                             2, 5, 29, 17
461                     }), generateSAN(altnames));
462                     addExtension(extensions, new ObjectIdentifier(new int[] {
463                             2, 5, 29, 15
464                     }), generateKU());
465                     addExtension(extensions, new ObjectIdentifier(new int[] {
466                             2, 5, 29, 37
467                     }), generateEKU(eku));
468                 }
469                 DerOutputStream extensionsSeq = new DerOutputStream();
470                 extensionsSeq.write(DerValue.tag_Sequence, extensions);
471                 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3), extensionsSeq);
472             }
473
474             DerOutputStream contentSeq = new DerOutputStream();
475
476             contentSeq.write(DerValue.tag_Sequence, content.toByteArray());
477
478             s.initSign(prk);
479             s.update(contentSeq.toByteArray());
480
481             aid.encode(contentSeq);
482             contentSeq.putBitString(s.sign());
483             cert.write(DerValue.tag_Sequence, contentSeq);
484
485             // X509Certificate c = (X509Certificate)
486             // CertificateFactory.getInstance("X509").generateCertificate(new
487             // ByteArrayInputStream(cert.toByteArray()));
488             // c.verify(pk); only for self-signeds
489
490             byte[] res = cert.toByteArray();
491             cert.close();
492             return res;
493         }
494
495     }
496
497     private static byte[] generateKU() throws IOException {
498         try (DerOutputStream dos = new DerOutputStream()) {
499             dos.putBitString(new byte[] {
500                     (byte) 0b10101000
501             });
502             return dos.toByteArray();
503         }
504     }
505
506     private static byte[] generateEKU(String eku) throws IOException {
507
508         DerOutputStream dos = new DerOutputStream();
509         for (String name : eku.split(",")) {
510             ObjectIdentifier oid;
511             switch (name) {
512             case "serverAuth":
513                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.1");
514                 break;
515             case "clientAuth":
516                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.2");
517                 break;
518             case "codeSigning":
519                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.3");
520                 break;
521             case "emailProtection":
522                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.4");
523                 break;
524             case "OCSPSigning":
525                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.9");
526                 break;
527
528             default:
529                 throw new Error(name);
530             }
531             dos.putOID(oid);
532         }
533         byte[] data = dos.toByteArray();
534         dos.reset();
535         dos.write(DerValue.tag_Sequence, data);
536         return dos.toByteArray();
537     }
538
539     public static X500Name genX500Name(Map<String, String> subj) throws IOException {
540         LinkedList<RDN> rdns = new LinkedList<>();
541         for (Entry<String, String> i : subj.entrySet()) {
542             RDN rdn = genRDN(i);
543             rdns.add(rdn);
544         }
545         return new X500Name(rdns.toArray(new RDN[rdns.size()]));
546     }
547
548     private static RDN genRDN(Entry<String, String> i) throws IOException {
549         DerOutputStream dos = new DerOutputStream();
550         dos.putUTF8String(i.getValue());
551         int[] oid;
552         String key = i.getKey();
553         switch (key) {
554         case "CN":
555             oid = new int[] {
556                     2, 5, 4, 3
557             };
558             break;
559         case "EMAIL":
560         case "emailAddress":
561             oid = new int[] {
562                     1, 2, 840, 113549, 1, 9, 1
563             };
564             break;
565         case "O":
566             oid = new int[] {
567                     2, 5, 4, 10
568             };
569             break;
570         case "OU":
571             oid = new int[] {
572                     2, 5, 4, 11
573             };
574             break;
575         case "ST":
576             oid = new int[] {
577                     2, 5, 4, 8
578             };
579             break;
580         case "L":
581             oid = new int[] {
582                     2, 5, 4, 7
583             };
584             break;
585         case "C":
586             oid = new int[] {
587                     2, 5, 4, 6
588             };
589             break;
590         default:
591             dos.close();
592             throw new Error("unknown RDN-type: " + key);
593         }
594         RDN rdn = new RDN(new AVA(new ObjectIdentifier(oid), new DerValue(dos.toByteArray())));
595         dos.close();
596         return rdn;
597     }
598
599     private static void addExtension(DerOutputStream extensions, ObjectIdentifier oid, byte[] extContent) throws IOException {
600         DerOutputStream SANs = new DerOutputStream();
601         SANs.putOID(oid);
602         SANs.putOctetString(extContent);
603
604         extensions.write(DerValue.tag_Sequence, SANs);
605     }
606
607     private static byte[] generateSAN(List<SubjectAlternateName> altnames) throws IOException {
608         DerOutputStream SANContent = new DerOutputStream();
609         for (SubjectAlternateName san : altnames) {
610             byte type = 0;
611             if (san.getType() == SANType.DNS) {
612                 type = (byte) GeneralNameInterface.NAME_DNS;
613             } else if (san.getType() == SANType.EMAIL) {
614                 type = (byte) GeneralNameInterface.NAME_RFC822;
615             } else {
616                 SANContent.close();
617                 throw new Error("" + san.getType());
618             }
619             SANContent.write(DerValue.createTag(DerValue.TAG_CONTEXT, false, type), san.getName().getBytes("UTF-8"));
620         }
621         DerOutputStream SANSeqContent = new DerOutputStream();
622         SANSeqContent.write(DerValue.tag_Sequence, SANContent);
623         byte[] byteArray = SANSeqContent.toByteArray();
624         SANContent.close();
625         SANSeqContent.close();
626         return byteArray;
627     }
628 }