]> WPIA git - gigi.git/blob - util-testing/org/cacert/gigi/util/SimpleSigner.java
upd: copy IOUtils, because "tests" is not visible here
[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                     SPKAC sp = new SPKAC(data);
316                     pk = sp.getPubkey();
317                 } else {
318                     PKCS10 p10 = new PKCS10(PEM.decode("(NEW )?CERTIFICATE REQUEST", new String(data)));
319                     pk = p10.getSubjectPublicKeyInfo();
320                 }
321                 PrivateKey i = loadOpensslKey(new File("signer/ca/" + ca + "/ca.key"));
322
323                 String[] call;
324                 X509Certificate root = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new FileInputStream("signer/ca/" + ca + "/ca.crt"));
325                 byte[] cert = generateCert(pk, i, subj, root.getSubjectX500Principal(), altnames, fromDate, toDate, Digest.valueOf(rs.getString("md").toUpperCase()), caP.getProperty("eku"));
326                 PrintWriter out = new PrintWriter(crt);
327                 out.println("-----BEGIN CERTIFICATE-----");
328                 out.println(Base64.getMimeEncoder().encodeToString(cert));
329                 out.println("-----END CERTIFICATE-----");
330                 out.close();
331                 synchronized (sdf) {
332                     /*
333                      * call = new String[] { "openssl", "ca",// "-in", "../../"
334                      * + csrname,// "-cert", "../" + ca + ".crt",// "-keyfile",
335                      * "../" + ca + ".key",// "-out", "../../" +
336                      * crt.getPath(),// "-utf8", "-startdate",
337                      * sdf.format(fromDate),// "-enddate", sdf.format(toDate),//
338                      * "-batch",// "-md", rs.getString("md"),// "-extfile",
339                      * "../" + f.getName(),// "-subj",
340                      * Certificate.stringifyDN(subj),// "-config",
341                      * "../selfsign.config"// };
342                      */
343                 }
344
345                 try (InputStream is = new FileInputStream(crt)) {
346                     CertificateFactory cf = CertificateFactory.getInstance("X.509");
347                     X509Certificate crtp = (X509Certificate) cf.generateCertificate(is);
348                     BigInteger serial = crtp.getSerialNumber();
349                     updateMail.setString(1, crt.getPath());
350                     updateMail.setString(2, serial.toString(16));
351                     updateMail.setInt(3, id);
352                     updateMail.execute();
353
354                     finishJob.setInt(1, rs.getInt("jobid"));
355                     finishJob.execute();
356                     System.out.println("signed: " + id);
357                     continue;
358                 }
359
360             } catch (GeneralSecurityException e) {
361                 e.printStackTrace();
362             } catch (IOException e) {
363                 e.printStackTrace();
364             } catch (ParseException e) {
365                 e.printStackTrace();
366             }
367             System.out.println("Error with: " + id);
368             warnMail.setInt(1, rs.getInt("jobid"));
369             warnMail.execute();
370
371         }
372         rs.close();
373     }
374
375     private static PrivateKey loadOpensslKey(File f) throws FileNotFoundException, IOException, InvalidKeySpecException, NoSuchAlgorithmException {
376         byte[] p8b = PEM.decode("RSA PRIVATE KEY", new String(IOUtils.readURL(new FileInputStream(f))));
377         DerOutputStream dos = new DerOutputStream();
378         dos.putInteger(0);
379         new AlgorithmId(new ObjectIdentifier(new int[] {
380                 1, 2, 840, 113549, 1, 1, 1
381         })).encode(dos);
382         dos.putOctetString(p8b);
383         byte[] ctx = dos.toByteArray();
384         dos.reset();
385         dos.write(DerValue.tag_Sequence, ctx);
386         PKCS8EncodedKeySpec p8 = new PKCS8EncodedKeySpec(dos.toByteArray());
387         PrivateKey i = KeyFactory.getInstance("RSA").generatePrivate(p8);
388         return i;
389     }
390
391     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 {
392         File f = Paths.get("signer", "serial").toFile();
393         if ( !f.exists()) {
394             FileOutputStream fos = new FileOutputStream(f);
395             fos.write("1".getBytes());
396             fos.close();
397         }
398         try (FileInputStream fr = new FileInputStream(f)) {
399             byte[] serial = IOUtils.readURL(fr);
400             BigInteger ser = new BigInteger(new String(serial).trim());
401             ser = ser.add(BigInteger.ONE);
402
403             PrintWriter pw = new PrintWriter(f);
404             pw.println(ser);
405             pw.close();
406             if (digest != Digest.SHA256 && digest != Digest.SHA512) {
407                 System.err.println("assuming sha256 either way ;-): " + digest);
408                 digest = Digest.SHA256;
409             }
410             ObjectIdentifier sha512withrsa = new ObjectIdentifier(new int[] {
411                     1, 2, 840, 113549, 1, 1, digest == Digest.SHA256 ? 11 : 13
412             });
413             AlgorithmId aid = new AlgorithmId(sha512withrsa);
414             Signature s = Signature.getInstance(digest == Digest.SHA256 ? "SHA256withRSA" : "SHA512withRSA");
415
416             DerOutputStream cert = new DerOutputStream();
417             DerOutputStream content = new DerOutputStream();
418             {
419                 DerOutputStream version = new DerOutputStream();
420                 version.putInteger(2); // v3
421                 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0), version);
422             }
423             content.putInteger(ser); // Serial
424             aid.encode(content);
425
426             {
427                 content.write(issuer.getEncoded());
428             }
429             {
430                 DerOutputStream notAround = new DerOutputStream();
431                 notAround.putUTCTime(fromDate);
432                 notAround.putUTCTime(toDate);
433                 content.write(DerValue.tag_Sequence, notAround);
434             }
435             {
436
437                 X500Name xn = genX500Name(subj);
438                 content.write(xn.getEncoded());
439             }
440             {
441                 content.write(pk.getEncoded());
442             }
443             {
444                 DerOutputStream extensions = new DerOutputStream();
445                 {
446                     addExtension(extensions, new ObjectIdentifier(new int[] {
447                             2, 5, 29, 17
448                     }), generateSAN(altnames));
449                     addExtension(extensions, new ObjectIdentifier(new int[] {
450                             2, 5, 29, 15
451                     }), generateKU());
452                     addExtension(extensions, new ObjectIdentifier(new int[] {
453                             2, 5, 29, 37
454                     }), generateEKU(eku));
455                 }
456                 DerOutputStream extensionsSeq = new DerOutputStream();
457                 extensionsSeq.write(DerValue.tag_Sequence, extensions);
458                 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3), extensionsSeq);
459             }
460
461             DerOutputStream contentSeq = new DerOutputStream();
462
463             contentSeq.write(DerValue.tag_Sequence, content.toByteArray());
464
465             s.initSign(prk);
466             s.update(contentSeq.toByteArray());
467
468             aid.encode(contentSeq);
469             contentSeq.putBitString(s.sign());
470             cert.write(DerValue.tag_Sequence, contentSeq);
471
472             X509Certificate c = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(cert.toByteArray()));
473             // c.verify(pk); only for self-signeds
474
475             return cert.toByteArray();
476         }
477
478     }
479
480     private static byte[] generateKU() throws IOException {
481         DerOutputStream dos = new DerOutputStream();
482         dos.putBitString(new byte[] {
483             (byte) 0b10101000
484         });
485         return dos.toByteArray();
486     }
487
488     private static byte[] generateEKU(String eku) throws IOException {
489
490         DerOutputStream dos = new DerOutputStream();
491         for (String name : eku.split(",")) {
492             ObjectIdentifier oid;
493             switch (name) {
494             case "serverAuth":
495                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.1");
496                 break;
497             case "clientAuth":
498                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.2");
499                 break;
500             case "codeSigning":
501                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.3");
502                 break;
503             case "emailProtection":
504                 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.4");
505                 break;
506
507             default:
508                 throw new Error(name);
509             }
510             dos.putOID(oid);
511         }
512         byte[] data = dos.toByteArray();
513         dos.reset();
514         dos.write(DerValue.tag_Sequence, data);
515         return dos.toByteArray();
516     }
517
518     private static X500Name genX500Name(Map<String, String> subj) throws IOException {
519         LinkedList<RDN> rdns = new LinkedList<>();
520         for (Entry<String, String> i : subj.entrySet()) {
521             RDN rdn = genRDN(i);
522             rdns.add(rdn);
523         }
524         return new X500Name(rdns.toArray(new RDN[rdns.size()]));
525     }
526
527     private static RDN genRDN(Entry<String, String> i) throws IOException {
528         DerOutputStream dos = new DerOutputStream();
529         dos.putUTF8String(i.getValue());
530         int[] oid;
531         String key = i.getKey();
532         switch (key) {
533         case "CN":
534             oid = new int[] {
535                     2, 5, 4, 3
536             };
537             break;
538         case "EMAIL":
539         case "emailAddress":
540             oid = new int[] {
541                     1, 2, 840, 113549, 1, 9, 1
542             };
543             break;
544         case "O":
545             oid = new int[] {
546                     2, 5, 4, 10
547             };
548             break;
549         case "OU":
550             oid = new int[] {
551                     2, 5, 4, 11
552             };
553             break;
554         default:
555             throw new Error("unknown RDN-type: " + key);
556         }
557         RDN rdn = new RDN(new AVA(new ObjectIdentifier(oid), new DerValue(dos.toByteArray())));
558         return rdn;
559     }
560
561     private static void addExtension(DerOutputStream extensions, ObjectIdentifier oid, byte[] extContent) throws IOException {
562         DerOutputStream SANs = new DerOutputStream();
563         SANs.putOID(oid);
564         SANs.putOctetString(extContent);
565
566         extensions.write(DerValue.tag_Sequence, SANs);
567     }
568
569     private static byte[] generateSAN(List<SubjectAlternateName> altnames) throws IOException {
570         DerOutputStream SANContent = new DerOutputStream();
571         for (SubjectAlternateName san : altnames) {
572             byte type = 0;
573             if (san.getType() == SANType.DNS) {
574                 type = (byte) GeneralNameInterface.NAME_DNS;
575             } else if (san.getType() == SANType.EMAIL) {
576                 type = (byte) GeneralNameInterface.NAME_RFC822;
577             } else {
578                 throw new Error("" + san.getType());
579             }
580             SANContent.write(DerValue.createTag(DerValue.TAG_CONTEXT, false, type), san.getName().getBytes());
581         }
582         DerOutputStream SANSeqContent = new DerOutputStream();
583         SANSeqContent.write(DerValue.tag_Sequence, SANContent);
584         byte[] byteArray = SANSeqContent.toByteArray();
585         return byteArray;
586     }
587 }