]> WPIA git - gigi.git/blob - util-testing/org/cacert/gigi/util/SimpleSigner.java
upd: move my Listing to WOT pages ( + testCase)
[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 GigiPreparedStatement locateCA;
84
85     private static volatile boolean running = true;
86
87     private static Thread runner;
88
89     private static SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss'Z'");
90
91     static {
92         TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
93         sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
94     }
95
96     public static void main(String[] args) throws IOException, SQLException, InterruptedException {
97         if (false) {
98             try {
99                 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
100                 kpg.initialize(2048);
101                 KeyPair kp = kpg.generateKeyPair();
102                 X500Principal xp = new X500Principal(genX500Name(Certificate.buildDN("CN", "uiae")).getEncoded());
103                 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");
104                 System.out.println(Base64.getMimeEncoder().encodeToString(i));
105             } catch (GeneralSecurityException e) {
106                 e.printStackTrace();
107             }
108             return;
109         }
110         Properties p = new Properties();
111         try (Reader reader = new InputStreamReader(new FileInputStream("config/gigi.properties"), "UTF-8")) {
112             p.load(reader);
113         }
114         DatabaseConnection.init(p);
115
116         runSigner();
117     }
118
119     public static void stopSigner() throws InterruptedException {
120         Thread capturedRunner;
121         synchronized (SimpleSigner.class) {
122             if (runner == null) {
123                 throw new IllegalStateException("already stopped");
124             }
125             capturedRunner = runner;
126             running = false;
127             SimpleSigner.class.notifyAll();
128         }
129         capturedRunner.join();
130     }
131
132     public synchronized static void runSigner() throws SQLException, IOException, InterruptedException {
133         if (runner != null) {
134             throw new IllegalStateException("already running");
135         }
136         running = true;
137         readyCerts = DatabaseConnection.getInstance().prepare("SELECT certs.id AS id, certs.csr_name, jobs.id AS jobid, csr_type, md, `executeFrom`, `executeTo`, profile FROM jobs " + //
138                 "INNER JOIN certs ON certs.id=jobs.`targetId` " + //
139                 "INNER JOIN profiles ON profiles.id=certs.profile " + //
140                 "WHERE jobs.state='open' "//
141                 + "AND task='sign'");
142
143         getSANSs = DatabaseConnection.getInstance().prepare("SELECT contents, type FROM `subjectAlternativeNames` " + //
144                 "WHERE `certId`=?");
145
146         updateMail = DatabaseConnection.getInstance().prepare("UPDATE certs SET crt_name=?," + " created=NOW(), serial=?, caid=? WHERE id=?");
147         warnMail = DatabaseConnection.getInstance().prepare("UPDATE jobs SET warning=warning+1, state=IF(warning<3, 'open','error') WHERE id=?");
148
149         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'");
150         revokeCompleted = DatabaseConnection.getInstance().prepare("UPDATE certs SET revoked=NOW() WHERE id=?");
151
152         finishJob = DatabaseConnection.getInstance().prepare("UPDATE jobs SET state='done' WHERE id=?");
153
154         locateCA = DatabaseConnection.getInstance().prepare("SELECT id FROM cacerts WHERE keyname=?");
155
156         runner = new Thread() {
157
158             @Override
159             public void run() {
160                 work();
161             }
162
163         };
164         runner.start();
165     }
166
167     private synchronized static void work() {
168         try {
169             gencrl();
170         } catch (IOException e2) {
171             e2.printStackTrace();
172         } catch (InterruptedException e2) {
173             e2.printStackTrace();
174         }
175
176         while (running) {
177             try {
178                 signCertificates();
179                 revokeCertificates();
180
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             File crt = KeyStorage.locateCrt(id);
198             worked = true;
199             System.out.println("Revoke faked: " + id);
200             revokeCompleted.setInt(1, id);
201             revokeCompleted.execute();
202             finishJob.setInt(1, rs.getInt(3));
203             finishJob.execute();
204         }
205         if (worked) {
206             gencrl();
207         }
208     }
209
210     private static void gencrl() throws IOException, InterruptedException {
211         if (true) {
212             return;
213         }
214         String[] call = new String[] {
215                 "openssl", "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                 boolean first = true;
278                 LinkedList<SubjectAlternateName> altnames = new LinkedList<>();
279                 while (san.next()) {
280                     first = false;
281                     altnames.add(new SubjectAlternateName(SANType.valueOf(san.getString("type").toUpperCase()), san.getString("contents")));
282                 }
283                 // TODO look them up!
284                 // cfg.println("keyUsage=critical," +
285                 // "digitalSignature, keyEncipherment, keyAgreement");
286                 // cfg.println("extendedKeyUsage=critical," + "clientAuth");
287                 // cfg.close();
288
289                 int profile = rs.getInt("profile");
290                 CertificateProfile cp = CertificateProfile.getById(profile);
291                 String s = cp.getId() + "";
292                 while (s.length() < 4) {
293                     s = "0" + s;
294                 }
295                 s += "-" + cp.getKeyName() + ".cfg";
296                 Properties caP = new Properties();
297                 caP.load(new FileInputStream("signer/profiles/" + s));
298                 String ca = caP.getProperty("ca") + "_2015_1";
299
300                 HashMap<String, String> subj = new HashMap<>();
301                 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT name, value FROM `certAvas` WHERE `certId`=?");
302                 ps.setInt(1, rs.getInt("id"));
303                 GigiResultSet rs2 = ps.executeQuery();
304                 while (rs2.next()) {
305                     String name = rs2.getString("name");
306                     if (name.equals("EMAIL")) {
307                         name = "emailAddress";
308                     }
309                     subj.put(name, rs2.getString("value"));
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);
321                     if (dt.startsWith("SPKAC=")) {
322                         dt = dt.substring(6);
323                         data = dt.getBytes();
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)));
330                     pk = p10.getSubjectPublicKeyInfo();
331                 }
332                 PrivateKey i = loadOpensslKey(new File("signer/ca/" + ca + "/ca.key"));
333
334                 String[] call;
335                 X509Certificate root = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new FileInputStream("signer/ca/" + ca + "/ca.crt"));
336                 byte[] cert = generateCert(pk, i, subj, root.getSubjectX500Principal(), altnames, fromDate, toDate, Digest.valueOf(rs.getString("md").toUpperCase()), caP.getProperty("eku"));
337                 PrintWriter out = new PrintWriter(crt);
338                 out.println("-----BEGIN CERTIFICATE-----");
339                 out.println(Base64.getMimeEncoder().encodeToString(cert));
340                 out.println("-----END CERTIFICATE-----");
341                 out.close();
342                 synchronized (sdf) {
343                     /*
344                      * call = new String[] { "openssl", "ca",// "-in", "../../"
345                      * + csrname,// "-cert", "../" + ca + ".crt",// "-keyfile",
346                      * "../" + ca + ".key",// "-out", "../../" +
347                      * crt.getPath(),// "-utf8", "-startdate",
348                      * sdf.format(fromDate),// "-enddate", sdf.format(toDate),//
349                      * "-batch",// "-md", rs.getString("md"),// "-extfile",
350                      * "../" + f.getName(),// "-subj",
351                      * Certificate.stringifyDN(subj),// "-config",
352                      * "../selfsign.config"// };
353                      */
354                 }
355
356                 try (InputStream is = new FileInputStream(crt)) {
357                     locateCA.setString(1, ca);
358                     GigiResultSet caRs = locateCA.executeQuery();
359                     if ( !caRs.next()) {
360                         throw new Error("ca " + ca + " was not found");
361                     }
362
363                     CertificateFactory cf = CertificateFactory.getInstance("X.509");
364                     X509Certificate crtp = (X509Certificate) cf.generateCertificate(is);
365                     BigInteger serial = crtp.getSerialNumber();
366                     updateMail.setString(1, crt.getPath());
367                     updateMail.setString(2, serial.toString(16));
368                     updateMail.setInt(3, caRs.getInt("id"));
369                     updateMail.setInt(4, id);
370                     updateMail.execute();
371
372                     finishJob.setInt(1, rs.getInt("jobid"));
373                     finishJob.execute();
374                     System.out.println("signed: " + id);
375                     continue;
376                 }
377
378             } catch (GeneralSecurityException e) {
379                 e.printStackTrace();
380             } catch (IOException e) {
381                 e.printStackTrace();
382             } catch (ParseException e) {
383                 e.printStackTrace();
384             }
385             System.out.println("Error with: " + id);
386             warnMail.setInt(1, rs.getInt("jobid"));
387             warnMail.execute();
388
389         }
390         rs.close();
391     }
392
393     private static PrivateKey loadOpensslKey(File f) throws FileNotFoundException, IOException, InvalidKeySpecException, NoSuchAlgorithmException {
394         byte[] p8b = PEM.decode("RSA PRIVATE KEY", new String(IOUtils.readURL(new FileInputStream(f))));
395         DerOutputStream dos = new DerOutputStream();
396         dos.putInteger(0);
397         new AlgorithmId(new ObjectIdentifier(new int[] {
398                 1, 2, 840, 113549, 1, 1, 1
399         })).encode(dos);
400         dos.putOctetString(p8b);
401         byte[] ctx = dos.toByteArray();
402         dos.reset();
403         dos.write(DerValue.tag_Sequence, ctx);
404         PKCS8EncodedKeySpec p8 = new PKCS8EncodedKeySpec(dos.toByteArray());
405         PrivateKey i = KeyFactory.getInstance("RSA").generatePrivate(p8);
406         return i;
407     }
408
409     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 {
410         File f = Paths.get("signer", "serial").toFile();
411         if ( !f.exists()) {
412             FileOutputStream fos = new FileOutputStream(f);
413             fos.write("1".getBytes());
414             fos.close();
415         }
416         try (FileInputStream fr = new FileInputStream(f)) {
417             byte[] serial = IOUtils.readURL(fr);
418             BigInteger ser = new BigInteger(new String(serial).trim());
419             ser = ser.add(BigInteger.ONE);
420
421             PrintWriter pw = new PrintWriter(f);
422             pw.println(ser);
423             pw.close();
424             if (digest != Digest.SHA256 && digest != Digest.SHA512) {
425                 System.err.println("assuming sha256 either way ;-): " + digest);
426                 digest = Digest.SHA256;
427             }
428             ObjectIdentifier sha512withrsa = new ObjectIdentifier(new int[] {
429                     1, 2, 840, 113549, 1, 1, digest == Digest.SHA256 ? 11 : 13
430             });
431             AlgorithmId aid = new AlgorithmId(sha512withrsa);
432             Signature s = Signature.getInstance(digest == Digest.SHA256 ? "SHA256withRSA" : "SHA512withRSA");
433
434             DerOutputStream cert = new DerOutputStream();
435             DerOutputStream content = new DerOutputStream();
436             {
437                 DerOutputStream version = new DerOutputStream();
438                 version.putInteger(2); // v3
439                 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0), version);
440             }
441             content.putInteger(ser); // Serial
442             aid.encode(content);
443
444             {
445                 content.write(issuer.getEncoded());
446             }
447             {
448                 DerOutputStream notAround = new DerOutputStream();
449                 notAround.putUTCTime(fromDate);
450                 notAround.putUTCTime(toDate);
451                 content.write(DerValue.tag_Sequence, notAround);
452             }
453             {
454
455                 X500Name xn = genX500Name(subj);
456                 content.write(xn.getEncoded());
457             }
458             {
459                 content.write(pk.getEncoded());
460             }
461             {
462                 DerOutputStream extensions = new DerOutputStream();
463                 {
464                     addExtension(extensions, new ObjectIdentifier(new int[] {
465                             2, 5, 29, 17
466                     }), generateSAN(altnames));
467                     addExtension(extensions, new ObjectIdentifier(new int[] {
468                             2, 5, 29, 15
469                     }), generateKU());
470                     addExtension(extensions, new ObjectIdentifier(new int[] {
471                             2, 5, 29, 37
472                     }), generateEKU(eku));
473                 }
474                 DerOutputStream extensionsSeq = new DerOutputStream();
475                 extensionsSeq.write(DerValue.tag_Sequence, extensions);
476                 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3), extensionsSeq);
477             }
478
479             DerOutputStream contentSeq = new DerOutputStream();
480
481             contentSeq.write(DerValue.tag_Sequence, content.toByteArray());
482
483             s.initSign(prk);
484             s.update(contentSeq.toByteArray());
485
486             aid.encode(contentSeq);
487             contentSeq.putBitString(s.sign());
488             cert.write(DerValue.tag_Sequence, contentSeq);
489
490             X509Certificate c = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(cert.toByteArray()));
491             // c.verify(pk); only for self-signeds
492
493             return cert.toByteArray();
494         }
495
496     }
497
498     private static byte[] generateKU() throws IOException {
499         DerOutputStream dos = new DerOutputStream();
500         dos.putBitString(new byte[] {
501             (byte) 0b10101000
502         });
503         return dos.toByteArray();
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
525             default:
526                 throw new Error(name);
527             }
528             dos.putOID(oid);
529         }
530         byte[] data = dos.toByteArray();
531         dos.reset();
532         dos.write(DerValue.tag_Sequence, data);
533         return dos.toByteArray();
534     }
535
536     private static X500Name genX500Name(Map<String, String> subj) throws IOException {
537         LinkedList<RDN> rdns = new LinkedList<>();
538         for (Entry<String, String> i : subj.entrySet()) {
539             RDN rdn = genRDN(i);
540             rdns.add(rdn);
541         }
542         return new X500Name(rdns.toArray(new RDN[rdns.size()]));
543     }
544
545     private static RDN genRDN(Entry<String, String> i) throws IOException {
546         DerOutputStream dos = new DerOutputStream();
547         dos.putUTF8String(i.getValue());
548         int[] oid;
549         String key = i.getKey();
550         switch (key) {
551         case "CN":
552             oid = new int[] {
553                     2, 5, 4, 3
554             };
555             break;
556         case "EMAIL":
557         case "emailAddress":
558             oid = new int[] {
559                     1, 2, 840, 113549, 1, 9, 1
560             };
561             break;
562         case "O":
563             oid = new int[] {
564                     2, 5, 4, 10
565             };
566             break;
567         case "OU":
568             oid = new int[] {
569                     2, 5, 4, 11
570             };
571             break;
572         case "ST":
573             oid = new int[] {
574                     2, 5, 4, 8
575             };
576             break;
577         case "L":
578             oid = new int[] {
579                     2, 5, 4, 7
580             };
581             break;
582         case "C":
583             oid = new int[] {
584                     2, 5, 4, 6
585             };
586             break;
587         default:
588             throw new Error("unknown RDN-type: " + key);
589         }
590         RDN rdn = new RDN(new AVA(new ObjectIdentifier(oid), new DerValue(dos.toByteArray())));
591         return rdn;
592     }
593
594     private static void addExtension(DerOutputStream extensions, ObjectIdentifier oid, byte[] extContent) throws IOException {
595         DerOutputStream SANs = new DerOutputStream();
596         SANs.putOID(oid);
597         SANs.putOctetString(extContent);
598
599         extensions.write(DerValue.tag_Sequence, SANs);
600     }
601
602     private static byte[] generateSAN(List<SubjectAlternateName> altnames) throws IOException {
603         DerOutputStream SANContent = new DerOutputStream();
604         for (SubjectAlternateName san : altnames) {
605             byte type = 0;
606             if (san.getType() == SANType.DNS) {
607                 type = (byte) GeneralNameInterface.NAME_DNS;
608             } else if (san.getType() == SANType.EMAIL) {
609                 type = (byte) GeneralNameInterface.NAME_RFC822;
610             } else {
611                 throw new Error("" + san.getType());
612             }
613             SANContent.write(DerValue.createTag(DerValue.TAG_CONTEXT, false, type), san.getName().getBytes());
614         }
615         DerOutputStream SANSeqContent = new DerOutputStream();
616         SANSeqContent.write(DerValue.tag_Sequence, SANContent);
617         byte[] byteArray = SANSeqContent.toByteArray();
618         return byteArray;
619     }
620 }