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