]> WPIA git - gigi.git/blob - util-testing/org/cacert/gigi/util/SimpleSigner.java
fix: some coverity bugs
[gigi.git] / util-testing / org / cacert / gigi / util / SimpleSigner.java
1 package org.cacert.gigi.util;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileNotFoundException;
6 import java.io.FileOutputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.InputStreamReader;
10 import java.io.PrintWriter;
11 import java.io.Reader;
12 import java.math.BigInteger;
13 import java.nio.file.Paths;
14 import java.security.GeneralSecurityException;
15 import java.security.KeyFactory;
16 import java.security.KeyPair;
17 import java.security.KeyPairGenerator;
18 import java.security.NoSuchAlgorithmException;
19 import java.security.PrivateKey;
20 import java.security.PublicKey;
21 import java.security.Signature;
22 import java.security.cert.CertificateFactory;
23 import java.security.cert.X509Certificate;
24 import java.security.spec.InvalidKeySpecException;
25 import java.security.spec.PKCS8EncodedKeySpec;
26 import java.sql.SQLException;
27 import java.sql.Timestamp;
28 import java.text.ParseException;
29 import java.text.SimpleDateFormat;
30 import java.util.Arrays;
31 import java.util.Base64;
32 import java.util.Calendar;
33 import java.util.Date;
34 import java.util.HashMap;
35 import java.util.LinkedList;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Map.Entry;
39 import java.util.Properties;
40 import java.util.TimeZone;
41
42 import javax.security.auth.x500.X500Principal;
43
44 import org.cacert.gigi.crypto.SPKAC;
45 import org.cacert.gigi.database.DatabaseConnection;
46 import org.cacert.gigi.database.GigiPreparedStatement;
47 import org.cacert.gigi.database.GigiResultSet;
48 import org.cacert.gigi.dbObjects.Certificate;
49 import org.cacert.gigi.dbObjects.Certificate.CSRType;
50 import org.cacert.gigi.dbObjects.Certificate.SANType;
51 import org.cacert.gigi.dbObjects.Certificate.SubjectAlternateName;
52 import org.cacert.gigi.dbObjects.CertificateProfile;
53 import org.cacert.gigi.dbObjects.Digest;
54 import org.cacert.gigi.output.DateSelector;
55
56 import sun.security.pkcs10.PKCS10;
57 import sun.security.util.DerOutputStream;
58 import sun.security.util.DerValue;
59 import sun.security.util.ObjectIdentifier;
60 import sun.security.x509.AVA;
61 import sun.security.x509.AlgorithmId;
62 import sun.security.x509.GeneralNameInterface;
63 import sun.security.x509.RDN;
64 import sun.security.x509.X500Name;
65
66 public class SimpleSigner {
67
68     private static GigiPreparedStatement warnMail;
69
70     private static GigiPreparedStatement updateMail;
71
72     private static GigiPreparedStatement readyCerts;
73
74     private static GigiPreparedStatement getSANSs;
75
76     private static GigiPreparedStatement revoke;
77
78     private static GigiPreparedStatement revokeCompleted;
79
80     private static GigiPreparedStatement finishJob;
81
82     private static GigiPreparedStatement locateCA;
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=? 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         locateCA = DatabaseConnection.getInstance().prepare("SELECT id FROM cacerts WHERE keyname=?");
154
155         runner = new Thread() {
156
157             @Override
158             public void run() {
159                 work();
160             }
161
162         };
163         runner.start();
164     }
165
166     private synchronized static void work() {
167         try {
168             gencrl();
169         } catch (IOException e2) {
170             e2.printStackTrace();
171         } catch (InterruptedException e2) {
172             e2.printStackTrace();
173         }
174
175         while (running) {
176             try {
177                 signCertificates();
178                 revokeCertificates();
179
180                 SimpleSigner.class.wait(5000);
181             } catch (IOException e) {
182                 e.printStackTrace();
183             } catch (SQLException e) {
184                 e.printStackTrace();
185             } catch (InterruptedException e1) {
186             }
187         }
188         runner = null;
189     }
190
191     private static void revokeCertificates() throws SQLException, IOException, InterruptedException {
192         GigiResultSet rs = revoke.executeQuery();
193         boolean worked = false;
194         while (rs.next()) {
195             int id = rs.getInt(1);
196             File crt = KeyStorage.locateCrt(id);
197             worked = true;
198             System.out.println("Revoke faked: " + id);
199             revokeCompleted.setInt(1, id);
200             revokeCompleted.execute();
201             finishJob.setInt(1, rs.getInt(3));
202             finishJob.execute();
203         }
204         if (worked) {
205             gencrl();
206         }
207     }
208
209     private static void gencrl() throws IOException, InterruptedException {
210         if (true) {
211             return;
212         }
213         String[] call = new String[] {
214                 "openssl", "ca",//
215                 "-cert",
216                 "../unassured.crt",//
217                 "-keyfile",
218                 "../unassured.key",//
219                 "-gencrl",//
220                 "-crlhours",//
221                 "12",//
222                 "-out",
223                 "../unassured.crl",//
224                 "-config",
225                 "../selfsign.config"
226
227         };
228         Process p1 = Runtime.getRuntime().exec(call, null, new File("keys/unassured.ca"));
229         if (p1.waitFor() != 0) {
230             System.out.println("Error while generating crl.");
231         }
232     }
233
234     private static int counter = 0;
235
236     private static void signCertificates() throws SQLException {
237         GigiResultSet rs = readyCerts.executeQuery();
238
239         Calendar c = Calendar.getInstance();
240         c.setTimeZone(TimeZone.getTimeZone("UTC"));
241         while (rs.next()) {
242             String csrname = rs.getString("csr_name");
243             int id = rs.getInt("id");
244             System.out.println("sign: " + csrname);
245             try {
246                 String csrType = rs.getString("csr_type");
247                 CSRType ct = CSRType.valueOf(csrType);
248                 File crt = KeyStorage.locateCrt(id);
249
250                 Timestamp from = rs.getTimestamp("executeFrom");
251                 String length = rs.getString("executeTo");
252                 Date fromDate;
253                 Date toDate;
254                 if (from == null) {
255                     fromDate = new Date(System.currentTimeMillis());
256                 } else {
257                     fromDate = new Date(from.getTime());
258                 }
259                 if (length.endsWith("m") || length.endsWith("y")) {
260                     String num = length.substring(0, length.length() - 1);
261                     int inter = Integer.parseInt(num);
262                     c.setTime(fromDate);
263                     if (length.endsWith("m")) {
264                         c.add(Calendar.MONTH, inter);
265                     } else {
266                         c.add(Calendar.YEAR, inter);
267                     }
268                     toDate = c.getTime();
269                 } else {
270                     toDate = DateSelector.getDateFormat().parse(length);
271                 }
272
273                 getSANSs.setInt(1, id);
274                 GigiResultSet san = getSANSs.executeQuery();
275
276                 LinkedList<SubjectAlternateName> altnames = new LinkedList<>();
277                 while (san.next()) {
278                     altnames.add(new SubjectAlternateName(SANType.valueOf(san.getString("type").toUpperCase()), san.getString("contents")));
279                 }
280                 // TODO look them up!
281                 // cfg.println("keyUsage=critical," +
282                 // "digitalSignature, keyEncipherment, keyAgreement");
283                 // cfg.println("extendedKeyUsage=critical," + "clientAuth");
284                 // cfg.close();
285
286                 int profile = rs.getInt("profile");
287                 CertificateProfile cp = CertificateProfile.getById(profile);
288                 String s = cp.getId() + "";
289                 while (s.length() < 4) {
290                     s = "0" + s;
291                 }
292                 s += "-" + cp.getKeyName() + ".cfg";
293                 Properties caP = new Properties();
294                 try (FileInputStream inStream = new FileInputStream("signer/profiles/" + s)) {
295                     caP.load(inStream);
296                 }
297                 String ca = caP.getProperty("ca") + "_2015_1";
298
299                 HashMap<String, String> subj = new HashMap<>();
300                 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT name, value FROM `certAvas` WHERE `certId`=?");
301                 ps.setInt(1, rs.getInt("id"));
302                 GigiResultSet rs2 = ps.executeQuery();
303                 while (rs2.next()) {
304                     String name = rs2.getString("name");
305                     if (name.equals("EMAIL")) {
306                         name = "emailAddress";
307                     }
308                     subj.put(name, rs2.getString("value"));
309                 }
310                 if (subj.size() == 0) {
311                     subj.put("CN", "<empty>");
312                     System.out.println("WARNING: DN was empty");
313                 }
314                 System.out.println(subj);
315
316                 PublicKey pk;
317                 byte[] data = IOUtils.readURL(new FileInputStream(csrname));
318                 if (ct == CSRType.SPKAC) {
319                     String dt = new String(data, "UTF-8");
320                     if (dt.startsWith("SPKAC=")) {
321                         dt = dt.substring(6);
322                         data = dt.getBytes("UTF-8");
323                         System.out.println(dt);
324                     }
325                     SPKAC sp = new SPKAC(Base64.getDecoder().decode(data));
326                     pk = sp.getPubkey();
327                 } else {
328                     PKCS10 p10 = new PKCS10(PEM.decode("(NEW )?CERTIFICATE REQUEST", new String(data, "UTF-8")));
329                     pk = p10.getSubjectPublicKeyInfo();
330                 }
331                 PrivateKey i = loadOpensslKey(new File("signer/ca/" + ca + "/ca.key"));
332
333                 String[] call;
334                 X509Certificate root = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new FileInputStream("signer/ca/" + ca + "/ca.crt"));
335                 byte[] cert = generateCert(pk, i, subj, root.getSubjectX500Principal(), altnames, fromDate, toDate, Digest.valueOf(rs.getString("md").toUpperCase()), caP.getProperty("eku"));
336                 PrintWriter out = new PrintWriter(crt);
337                 out.println("-----BEGIN CERTIFICATE-----");
338                 out.println(Base64.getMimeEncoder().encodeToString(cert));
339                 out.println("-----END CERTIFICATE-----");
340                 out.close();
341                 // synchronized (sdf) {
342                 /*
343                  * call = new String[] { "openssl", "ca",// "-in", "../../" +
344                  * csrname,// "-cert", "../" + ca + ".crt",// "-keyfile", "../"
345                  * + ca + ".key",// "-out", "../../" + crt.getPath(),// "-utf8",
346                  * "-startdate", sdf.format(fromDate),// "-enddate",
347                  * sdf.format(toDate),// "-batch",// "-md",
348                  * rs.getString("md"),// "-extfile", "../" + f.getName(),//
349                  * "-subj", Certificate.stringifyDN(subj),// "-config",
350                  * "../selfsign.config"// };
351                  */
352                 // }
353
354                 try (InputStream is = new FileInputStream(crt)) {
355                     locateCA.setString(1, ca);
356                     GigiResultSet caRs = locateCA.executeQuery();
357                     if ( !caRs.next()) {
358                         throw new Error("ca " + ca + " was not found");
359                     }
360
361                     CertificateFactory cf = CertificateFactory.getInstance("X.509");
362                     X509Certificate crtp = (X509Certificate) cf.generateCertificate(is);
363                     BigInteger serial = crtp.getSerialNumber();
364                     updateMail.setString(1, crt.getPath());
365                     updateMail.setString(2, serial.toString(16));
366                     updateMail.setInt(3, caRs.getInt("id"));
367                     updateMail.setInt(4, id);
368                     updateMail.execute();
369
370                     finishJob.setInt(1, rs.getInt("jobid"));
371                     finishJob.execute();
372                     System.out.println("signed: " + id);
373                     continue;
374                 }
375
376             } catch (GeneralSecurityException e) {
377                 e.printStackTrace();
378             } catch (IOException e) {
379                 e.printStackTrace();
380             } catch (ParseException e) {
381                 e.printStackTrace();
382             }
383             System.out.println("Error with: " + id);
384             warnMail.setInt(1, rs.getInt("jobid"));
385             warnMail.execute();
386
387         }
388         rs.close();
389     }
390
391     private static PrivateKey loadOpensslKey(File f) throws FileNotFoundException, IOException, InvalidKeySpecException, NoSuchAlgorithmException {
392         byte[] p8b = PEM.decode("RSA PRIVATE KEY", new String(IOUtils.readURL(new FileInputStream(f))));
393         DerOutputStream dos = new DerOutputStream();
394         dos.putInteger(0);
395         new AlgorithmId(new ObjectIdentifier(new int[] {
396                 1, 2, 840, 113549, 1, 1, 1
397         })).encode(dos);
398         dos.putOctetString(p8b);
399         byte[] ctx = dos.toByteArray();
400         dos.reset();
401         dos.write(DerValue.tag_Sequence, ctx);
402         PKCS8EncodedKeySpec p8 = new PKCS8EncodedKeySpec(dos.toByteArray());
403         PrivateKey i = KeyFactory.getInstance("RSA").generatePrivate(p8);
404         return i;
405     }
406
407     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 {
408         File f = Paths.get("signer", "serial").toFile();
409         if ( !f.exists()) {
410             try (FileOutputStream fos = new FileOutputStream(f)) {
411                 fos.write("1".getBytes("UTF-8"));
412             }
413         }
414         try (FileInputStream fr = new FileInputStream(f)) {
415             byte[] serial = IOUtils.readURL(fr);
416             BigInteger ser = new BigInteger(new String(serial).trim());
417             ser = ser.add(BigInteger.ONE);
418
419             PrintWriter pw = new PrintWriter(f);
420             pw.println(ser);
421             pw.close();
422             if (digest != Digest.SHA256 && digest != Digest.SHA512) {
423                 System.err.println("assuming sha256 either way ;-): " + digest);
424                 digest = Digest.SHA256;
425             }
426             ObjectIdentifier sha512withrsa = new ObjectIdentifier(new int[] {
427                     1, 2, 840, 113549, 1, 1, digest == Digest.SHA256 ? 11 : 13
428             });
429             AlgorithmId aid = new AlgorithmId(sha512withrsa);
430             Signature s = Signature.getInstance(digest == Digest.SHA256 ? "SHA256withRSA" : "SHA512withRSA");
431
432             DerOutputStream cert = new DerOutputStream();
433             DerOutputStream content = new DerOutputStream();
434             {
435                 DerOutputStream version = new DerOutputStream();
436                 version.putInteger(2); // v3
437                 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0), version);
438             }
439             content.putInteger(ser); // Serial
440             aid.encode(content);
441
442             {
443                 content.write(issuer.getEncoded());
444             }
445             {
446                 DerOutputStream notAround = new DerOutputStream();
447                 notAround.putUTCTime(fromDate);
448                 notAround.putUTCTime(toDate);
449                 content.write(DerValue.tag_Sequence, notAround);
450             }
451             {
452
453                 X500Name xn = genX500Name(subj);
454                 content.write(xn.getEncoded());
455             }
456             {
457                 content.write(pk.getEncoded());
458             }
459             {
460                 DerOutputStream extensions = new DerOutputStream();
461                 {
462                     addExtension(extensions, new ObjectIdentifier(new int[] {
463                             2, 5, 29, 17
464                     }), generateSAN(altnames));
465                     addExtension(extensions, new ObjectIdentifier(new int[] {
466                             2, 5, 29, 15
467                     }), generateKU());
468                     addExtension(extensions, new ObjectIdentifier(new int[] {
469                             2, 5, 29, 37
470                     }), generateEKU(eku));
471                 }
472                 DerOutputStream extensionsSeq = new DerOutputStream();
473                 extensionsSeq.write(DerValue.tag_Sequence, extensions);
474                 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3), extensionsSeq);
475             }
476
477             DerOutputStream contentSeq = new DerOutputStream();
478
479             contentSeq.write(DerValue.tag_Sequence, content.toByteArray());
480
481             s.initSign(prk);
482             s.update(contentSeq.toByteArray());
483
484             aid.encode(contentSeq);
485             contentSeq.putBitString(s.sign());
486             cert.write(DerValue.tag_Sequence, contentSeq);
487
488             // X509Certificate c = (X509Certificate)
489             // CertificateFactory.getInstance("X509").generateCertificate(new
490             // 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("UTF-8"));
614         }
615         DerOutputStream SANSeqContent = new DerOutputStream();
616         SANSeqContent.write(DerValue.tag_Sequence, SANContent);
617         byte[] byteArray = SANSeqContent.toByteArray();
618         return byteArray;
619     }
620 }