1 package club.wpia.gigi.util;
3 import java.io.ByteArrayInputStream;
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.NoSuchAlgorithmException;
18 import java.security.PrivateKey;
19 import java.security.PublicKey;
20 import java.security.Signature;
21 import java.security.cert.CertificateFactory;
22 import java.security.cert.X509Certificate;
23 import java.security.spec.InvalidKeySpecException;
24 import java.security.spec.PKCS8EncodedKeySpec;
25 import java.sql.SQLException;
26 import java.sql.Timestamp;
27 import java.text.ParseException;
28 import java.text.SimpleDateFormat;
29 import java.util.Base64;
30 import java.util.Calendar;
31 import java.util.Date;
32 import java.util.GregorianCalendar;
33 import java.util.HashMap;
34 import java.util.LinkedList;
35 import java.util.List;
37 import java.util.Map.Entry;
38 import java.util.Properties;
39 import java.util.TimeZone;
41 import javax.security.auth.x500.X500Principal;
43 import club.wpia.gigi.GigiApiException;
44 import club.wpia.gigi.crypto.SPKAC;
45 import club.wpia.gigi.database.DatabaseConnection;
46 import club.wpia.gigi.database.DatabaseConnection.Link;
47 import club.wpia.gigi.database.GigiPreparedStatement;
48 import club.wpia.gigi.database.GigiResultSet;
49 import club.wpia.gigi.dbObjects.Certificate;
50 import club.wpia.gigi.dbObjects.Certificate.AttachmentType;
51 import club.wpia.gigi.dbObjects.Certificate.CSRType;
52 import club.wpia.gigi.dbObjects.Certificate.SANType;
53 import club.wpia.gigi.dbObjects.Certificate.SubjectAlternateName;
54 import club.wpia.gigi.dbObjects.CertificateProfile;
55 import club.wpia.gigi.dbObjects.Digest;
56 import club.wpia.gigi.output.DateSelector;
57 import club.wpia.gigi.util.ServerConstants.Host;
58 import sun.security.pkcs10.PKCS10;
59 import sun.security.util.DerOutputStream;
60 import sun.security.util.DerValue;
61 import sun.security.util.ObjectIdentifier;
62 import sun.security.x509.AVA;
63 import sun.security.x509.AlgorithmId;
64 import sun.security.x509.GeneralNameInterface;
65 import sun.security.x509.RDN;
66 import sun.security.x509.X500Name;
68 public class SimpleSigner {
70 private static GigiPreparedStatement warnMail;
72 private static GigiPreparedStatement updateMail;
74 private static GigiPreparedStatement readyCerts;
76 private static GigiPreparedStatement getSANSs;
78 private static GigiPreparedStatement revoke;
80 private static GigiPreparedStatement revokeCompleted;
82 private static GigiPreparedStatement finishJob;
84 private static GigiPreparedStatement locateCA;
86 private static volatile boolean running = true;
88 private static Thread runner;
90 private static SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss'Z'");
93 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
94 sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
97 public static void main(String[] args) throws IOException, SQLException, InterruptedException {
98 Properties p = new Properties();
99 try (Reader reader = new InputStreamReader(new FileInputStream("config/gigi.properties"), "UTF-8")) {
102 ServerConstants.init(p);
103 DatabaseConnection.init(p);
108 public static void stopSigner() throws InterruptedException {
109 Thread capturedRunner;
110 synchronized (SimpleSigner.class) {
111 if (runner == null) {
112 throw new IllegalStateException("already stopped");
114 capturedRunner = runner;
116 SimpleSigner.class.notifyAll();
118 capturedRunner.join();
121 public synchronized static void runSigner() throws SQLException, IOException, InterruptedException {
122 if (runner != null) {
123 throw new IllegalStateException("already running");
127 runner = new Thread() {
131 try (Link l = DatabaseConnection.newLink(false)) {
132 readyCerts = new GigiPreparedStatement("SELECT certs.id AS id, jobs.id AS jobid, csr_type, md, `executeFrom`, `executeTo`, profile FROM jobs " + //
133 "INNER JOIN certs ON certs.id=jobs.`targetId` " + //
134 "INNER JOIN profiles ON profiles.id=certs.profile " + //
135 "WHERE jobs.state='open' " + //
138 getSANSs = new GigiPreparedStatement("SELECT contents, type FROM `subjectAlternativeNames` " + //
141 updateMail = new GigiPreparedStatement("UPDATE certs SET created=NOW(), serial=?, caid=?, expire=? WHERE id=?");
142 warnMail = new GigiPreparedStatement("UPDATE jobs SET attempt=attempt+1, state=CASE WHEN attempt<3 THEN 'open'::`jobState` ELSE 'error'::`jobState` END WHERE id=?");
144 revoke = new GigiPreparedStatement("SELECT certs.id, jobs.id FROM jobs INNER JOIN certs ON jobs.`targetId`=certs.id" + " WHERE jobs.state='open' AND task='revoke'");
145 revokeCompleted = new GigiPreparedStatement("UPDATE `certs` SET revoked=NOW() WHERE id=?");
147 finishJob = new GigiPreparedStatement("UPDATE jobs SET state='done' WHERE id=?");
149 locateCA = new GigiPreparedStatement("SELECT id FROM cacerts WHERE keyname=?");
152 } catch (InterruptedException e) {
161 public static void ping() {
162 synchronized (SimpleSigner.class) {
163 SimpleSigner.class.notifyAll();
165 SimpleSigner.class.wait(2000);
166 } catch (InterruptedException e) {
172 private synchronized static void work() {
175 } catch (IOException e2) {
176 e2.printStackTrace();
177 } catch (InterruptedException e2) {
178 e2.printStackTrace();
184 revokeCertificates();
186 SimpleSigner.class.notifyAll();
187 SimpleSigner.class.wait(5000);
188 } catch (IOException e) {
190 } catch (SQLException e) {
192 } catch (InterruptedException e1) {
198 private static void revokeCertificates() throws SQLException, IOException, InterruptedException {
199 GigiResultSet rs = revoke.executeQuery();
200 boolean worked = false;
202 int id = rs.getInt(1);
204 System.out.println("Revoke faked: " + id);
205 revokeCompleted.setInt(1, id);
206 revokeCompleted.executeUpdate();
207 finishJob.setInt(1, rs.getInt(2));
208 finishJob.executeUpdate();
215 private static void gencrl() throws IOException, InterruptedException {
219 String[] call = new String[] {
223 "../unassured.crt",//
225 "../unassured.key",//
230 "../unassured.crl",//
235 Process p1 = Runtime.getRuntime().exec(call, null, new File("keys/unassured.ca"));
236 if (p1.waitFor() != 0) {
237 System.out.println("Error while generating crl.");
241 private static void signCertificates() throws SQLException {
242 GigiResultSet rs = readyCerts.executeQuery();
244 Calendar c = Calendar.getInstance();
245 c.setTimeZone(TimeZone.getTimeZone("UTC"));
247 int id = rs.getInt("id");
248 System.out.println("sign: " + id);
250 Certificate crt = Certificate.getById(id);
251 String csrType = rs.getString("csr_type");
252 CSRType ct = CSRType.valueOf(csrType);
254 Timestamp from = rs.getTimestamp("executeFrom");
255 String length = rs.getString("executeTo");
259 fromDate = new Date(System.currentTimeMillis());
261 fromDate = new Date(from.getTime());
263 if (length.endsWith("m") || length.endsWith("y")) {
264 String num = length.substring(0, length.length() - 1);
265 int inter = Integer.parseInt(num);
267 if (length.endsWith("m")) {
268 c.add(Calendar.MONTH, inter);
270 c.add(Calendar.YEAR, inter);
272 toDate = c.getTime();
274 toDate = DateSelector.getDateFormat().parse(length);
277 getSANSs.setInt(1, id);
278 GigiResultSet san = getSANSs.executeQuery();
280 LinkedList<SubjectAlternateName> altnames = new LinkedList<>();
282 altnames.add(new SubjectAlternateName(SANType.valueOf(san.getString("type").toUpperCase()), san.getString("contents")));
284 // TODO look them up!
285 // cfg.println("keyUsage=critical," +
286 // "digitalSignature, keyEncipherment, keyAgreement");
287 // cfg.println("extendedKeyUsage=critical," + "clientAuth");
290 int profile = rs.getInt("profile");
291 CertificateProfile cp = CertificateProfile.getById(profile);
292 String s = cp.getId() + "";
293 while (s.length() < 4) {
296 s += "-" + cp.getKeyName() + ".cfg";
297 Properties caP = new Properties();
298 try (FileInputStream inStream = new FileInputStream("signer/profiles/" + s)) {
302 HashMap<String, String> subj = new HashMap<>();
303 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT name, value FROM `certAvas` WHERE `certId`=?")) {
304 ps.setInt(1, rs.getInt("id"));
305 GigiResultSet rs2 = ps.executeQuery();
307 String name = rs2.getString("name");
308 if (name.equals("EMAIL")) {
309 name = "emailAddress";
311 subj.put(name, rs2.getString("value"));
314 if (subj.size() == 0) {
315 subj.put("CN", "<empty>");
316 System.out.println("WARNING: DN was empty");
318 System.out.println(subj);
321 byte[] data = crt.getAttachment(AttachmentType.CSR).getBytes("UTF-8");
322 if (ct == CSRType.SPKAC) {
323 String dt = new String(data, "UTF-8");
324 if (dt.startsWith("SPKAC=")) {
325 dt = dt.substring(6);
326 data = dt.getBytes("UTF-8");
327 System.out.println(dt);
329 SPKAC sp = new SPKAC(Base64.getDecoder().decode(data));
332 PKCS10 p10 = new PKCS10(PEM.decode("(NEW )?CERTIFICATE REQUEST", new String(data, "UTF-8")));
333 pk = p10.getSubjectPublicKeyInfo();
335 Calendar cal = GregorianCalendar.getInstance();
336 String ca = caP.getProperty("ca") + "_" + cal.get(Calendar.YEAR) + (cal.get(Calendar.MONTH) >= 6 ? "_2" : "_1");
337 File parent = new File("signer/ca");
338 File[] caFiles = parent.listFiles();
339 if (null == caFiles) {
340 caFiles = new File[0];
342 if ( !new File(parent, ca).exists()) {
343 System.out.println("CA " + ca + " not found. Searching for anything other remotely fitting.");
344 for (File f : caFiles) {
345 if (f.getName().startsWith(caP.getProperty("ca"))) {
351 File caKey = new File(parent, ca + "/ca.key");
352 PrivateKey i = loadOpensslKey(caKey);
354 X509Certificate root = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new FileInputStream("signer/ca/" + ca + "/ca.crt"));
355 byte[] cert = generateCert(pk, i, subj, root.getSubjectX500Principal(), altnames, fromDate, toDate, Digest.valueOf(rs.getString("md").toUpperCase()), caP.getProperty("eku"));
356 StringBuilder b = new StringBuilder();
357 b.append("-----BEGIN CERTIFICATE-----\r\n");
358 b.append(Base64.getMimeEncoder().encodeToString(cert));
359 b.append("-----END CERTIFICATE-----\r\n");
360 crt.addAttachment(AttachmentType.CRT, b.toString());
362 try (InputStream is = new ByteArrayInputStream(cert)) {
363 locateCA.setString(1, ca);
364 GigiResultSet caRs = locateCA.executeQuery();
366 throw new Error("ca " + ca + " was not found");
369 CertificateFactory cf = CertificateFactory.getInstance("X.509");
370 X509Certificate crtp = (X509Certificate) cf.generateCertificate(is);
371 BigInteger serial = crtp.getSerialNumber();
372 updateMail.setString(1, serial.toString(16));
373 updateMail.setInt(2, caRs.getInt("id"));
374 updateMail.setTimestamp(3, new Timestamp(toDate.getTime()));
375 updateMail.setInt(4, id);
376 updateMail.executeUpdate();
378 finishJob.setInt(1, rs.getInt("jobid"));
379 finishJob.executeUpdate();
380 System.out.println("signed: " + id);
384 } catch (GeneralSecurityException e) {
386 } catch (IOException e) {
388 } catch (ParseException e) {
390 } catch (GigiApiException e) {
393 System.out.println("Error with: " + id);
394 warnMail.setInt(1, rs.getInt("jobid"));
395 warnMail.executeUpdate();
401 private static PrivateKey loadOpensslKey(File f) throws FileNotFoundException, IOException, InvalidKeySpecException, NoSuchAlgorithmException {
402 byte[] p8b = PEM.decode("RSA PRIVATE KEY", new String(IOUtils.readURL(new FileInputStream(f))));
403 DerOutputStream dos = new DerOutputStream();
405 new AlgorithmId(new ObjectIdentifier(new int[] {
406 1, 2, 840, 113549, 1, 1, 1
408 dos.putOctetString(p8b);
409 byte[] ctx = dos.toByteArray();
411 dos.write(DerValue.tag_Sequence, ctx);
412 PKCS8EncodedKeySpec p8 = new PKCS8EncodedKeySpec(dos.toByteArray());
413 PrivateKey i = KeyFactory.getInstance("RSA").generatePrivate(p8);
417 public 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 {
418 File f = Paths.get("signer", "serial").toFile();
420 try (FileOutputStream fos = new FileOutputStream(f)) {
421 fos.write("1".getBytes("UTF-8"));
424 try (FileInputStream fr = new FileInputStream(f)) {
425 byte[] serial = IOUtils.readURL(fr);
426 BigInteger ser = new BigInteger(new String(serial).trim());
427 ser = ser.add(BigInteger.ONE);
429 PrintWriter pw = new PrintWriter(f);
432 if (digest != Digest.SHA256 && digest != Digest.SHA384 && digest != Digest.SHA512) {
433 System.err.println("assuming sha256 either way ;-): " + digest);
434 digest = Digest.SHA256;
436 ObjectIdentifier sha512withrsa = new ObjectIdentifier(new int[] {
437 1, 2, 840, 113549, 1, 1, digest == Digest.SHA256 ? 11 : (digest == Digest.SHA384 ? 12 : 13)
439 AlgorithmId aid = new AlgorithmId(sha512withrsa);
440 Signature s = Signature.getInstance(digest == Digest.SHA256 ? "SHA256withRSA" : (digest == Digest.SHA384 ? "SHA384withRSA" : "SHA512withRSA"));
442 DerOutputStream cert = new DerOutputStream();
443 DerOutputStream content = new DerOutputStream();
445 DerOutputStream version = new DerOutputStream();
446 version.putInteger(2); // v3
447 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0), version);
449 content.putInteger(ser); // Serial
453 content.write(issuer.getEncoded());
456 DerOutputStream notAround = new DerOutputStream();
457 notAround.putUTCTime(fromDate);
458 notAround.putUTCTime(toDate);
459 content.write(DerValue.tag_Sequence, notAround);
463 X500Name xn = genX500Name(subj);
464 content.write(xn.getEncoded());
467 content.write(pk.getEncoded());
470 DerOutputStream extensions = new DerOutputStream();
472 addExtension(extensions, new ObjectIdentifier(new int[] {
474 }), generateSAN(altnames));
475 addExtension(extensions, new ObjectIdentifier(new int[] {
478 addExtension(extensions, new ObjectIdentifier(new int[] {
480 }), generateEKU(eku));
481 addExtension(extensions, new ObjectIdentifier(new int[] {
482 1, 3, 6, 1, 5, 5, 7, 1, 1
485 DerOutputStream extensionsSeq = new DerOutputStream();
486 extensionsSeq.write(DerValue.tag_Sequence, extensions);
487 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3), extensionsSeq);
490 DerOutputStream contentSeq = new DerOutputStream();
492 contentSeq.write(DerValue.tag_Sequence, content.toByteArray());
495 s.update(contentSeq.toByteArray());
497 aid.encode(contentSeq);
498 contentSeq.putBitString(s.sign());
499 cert.write(DerValue.tag_Sequence, contentSeq);
501 // X509Certificate c = (X509Certificate)
502 // CertificateFactory.getInstance("X509").generateCertificate(new
503 // ByteArrayInputStream(cert.toByteArray()));
504 // c.verify(pk); only for self-signeds
506 byte[] res = cert.toByteArray();
513 private static byte[] generateAIA() throws IOException {
514 try (DerOutputStream dos = new DerOutputStream()) {
515 try (DerOutputStream seq = new DerOutputStream()) {
516 seq.putOID(new ObjectIdentifier(new int[] {
517 1, 3, 6, 1, 5, 5, 7, 48, 2
519 seq.write((byte) 0x86, ("http://" + ServerConstants.getHostName(Host.OCSP_RESPONDER)).getBytes("UTF-8"));
520 dos.write(DerValue.tag_Sequence, seq);
522 byte[] data = dos.toByteArray();
524 dos.write(DerValue.tag_Sequence, data);
525 return dos.toByteArray();
529 private static byte[] generateKU() throws IOException {
530 try (DerOutputStream dos = new DerOutputStream()) {
531 dos.putBitString(new byte[] {
534 return dos.toByteArray();
538 private static byte[] generateEKU(String eku) throws IOException {
540 try (DerOutputStream dos = new DerOutputStream()) {
541 for (String name : eku.split(",")) {
543 ObjectIdentifier oid;
546 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.1");
549 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.2");
552 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.3");
554 case "emailProtection":
555 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.4");
558 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.9");
562 throw new Error(name);
566 byte[] data = dos.toByteArray();
568 dos.write(DerValue.tag_Sequence, data);
569 return dos.toByteArray();
573 public static X500Name genX500Name(Map<String, String> subj) throws IOException {
574 LinkedList<RDN> rdns = new LinkedList<>();
575 for (Entry<String, String> i : subj.entrySet()) {
579 return new X500Name(rdns.toArray(new RDN[rdns.size()]));
582 private static RDN genRDN(Entry<String, String> i) throws IOException {
583 DerOutputStream dos = new DerOutputStream();
584 dos.putUTF8String(i.getValue());
586 String key = i.getKey();
596 1, 2, 840, 113549, 1, 9, 1
626 throw new Error("unknown RDN-type: " + key);
628 RDN rdn = new RDN(new AVA(new ObjectIdentifier(oid), new DerValue(dos.toByteArray())));
633 private static void addExtension(DerOutputStream extensions, ObjectIdentifier oid, byte[] extContent) throws IOException {
634 DerOutputStream SANs = new DerOutputStream();
636 SANs.putOctetString(extContent);
638 extensions.write(DerValue.tag_Sequence, SANs);
641 private static byte[] generateSAN(List<SubjectAlternateName> altnames) throws IOException {
642 DerOutputStream SANContent = new DerOutputStream();
643 for (SubjectAlternateName san : altnames) {
645 if (san.getType() == SANType.DNS) {
646 type = (byte) GeneralNameInterface.NAME_DNS;
647 } else if (san.getType() == SANType.EMAIL) {
648 type = (byte) GeneralNameInterface.NAME_RFC822;
651 throw new Error("" + san.getType());
653 SANContent.write(DerValue.createTag(DerValue.TAG_CONTEXT, false, type), san.getName().getBytes("UTF-8"));
655 DerOutputStream SANSeqContent = new DerOutputStream();
656 SANSeqContent.write(DerValue.tag_Sequence, SANContent);
657 byte[] byteArray = SANSeqContent.toByteArray();
659 SANSeqContent.close();