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