1 package org.cacert.gigi.util;
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.NoSuchAlgorithmException;
17 import java.security.PrivateKey;
18 import java.security.PublicKey;
19 import java.security.Signature;
20 import java.security.cert.CertificateFactory;
21 import java.security.cert.X509Certificate;
22 import java.security.spec.InvalidKeySpecException;
23 import java.security.spec.PKCS8EncodedKeySpec;
24 import java.sql.SQLException;
25 import java.sql.Timestamp;
26 import java.text.ParseException;
27 import java.text.SimpleDateFormat;
28 import java.util.Base64;
29 import java.util.Calendar;
30 import java.util.Date;
31 import java.util.GregorianCalendar;
32 import java.util.HashMap;
33 import java.util.LinkedList;
34 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Properties;
38 import java.util.TimeZone;
40 import javax.security.auth.x500.X500Principal;
42 import org.cacert.gigi.crypto.SPKAC;
43 import org.cacert.gigi.database.DatabaseConnection;
44 import org.cacert.gigi.database.DatabaseConnection.Link;
45 import org.cacert.gigi.database.GigiPreparedStatement;
46 import org.cacert.gigi.database.GigiResultSet;
47 import org.cacert.gigi.dbObjects.Certificate.CSRType;
48 import org.cacert.gigi.dbObjects.Certificate.SANType;
49 import org.cacert.gigi.dbObjects.Certificate.SubjectAlternateName;
50 import org.cacert.gigi.dbObjects.CertificateProfile;
51 import org.cacert.gigi.dbObjects.Digest;
52 import org.cacert.gigi.output.DateSelector;
54 import sun.security.pkcs10.PKCS10;
55 import sun.security.util.DerOutputStream;
56 import sun.security.util.DerValue;
57 import sun.security.util.ObjectIdentifier;
58 import sun.security.x509.AVA;
59 import sun.security.x509.AlgorithmId;
60 import sun.security.x509.GeneralNameInterface;
61 import sun.security.x509.RDN;
62 import sun.security.x509.X500Name;
64 public class SimpleSigner {
66 private static GigiPreparedStatement warnMail;
68 private static GigiPreparedStatement updateMail;
70 private static GigiPreparedStatement readyCerts;
72 private static GigiPreparedStatement getSANSs;
74 private static GigiPreparedStatement revoke;
76 private static GigiPreparedStatement revokeCompleted;
78 private static GigiPreparedStatement finishJob;
80 private static GigiPreparedStatement locateCA;
82 private static volatile boolean running = true;
84 private static Thread runner;
86 private static SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss'Z'");
89 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
90 sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
93 public static void main(String[] args) throws IOException, SQLException, InterruptedException {
94 Properties p = new Properties();
95 try (Reader reader = new InputStreamReader(new FileInputStream("config/gigi.properties"), "UTF-8")) {
98 DatabaseConnection.init(p);
103 public static void stopSigner() throws InterruptedException {
104 Thread capturedRunner;
105 synchronized (SimpleSigner.class) {
106 if (runner == null) {
107 throw new IllegalStateException("already stopped");
109 capturedRunner = runner;
111 SimpleSigner.class.notifyAll();
113 capturedRunner.join();
116 public synchronized static void runSigner() throws SQLException, IOException, InterruptedException {
117 if (runner != null) {
118 throw new IllegalStateException("already running");
122 runner = new Thread() {
126 try (Link l = DatabaseConnection.newLink(false)) {
127 readyCerts = new GigiPreparedStatement("SELECT certs.id AS id, certs.csr_name, jobs.id AS jobid, csr_type, md, `executeFrom`, `executeTo`, profile FROM jobs " + //
128 "INNER JOIN certs ON certs.id=jobs.`targetId` " + //
129 "INNER JOIN profiles ON profiles.id=certs.profile " + //
130 "WHERE jobs.state='open' " + //
133 getSANSs = new GigiPreparedStatement("SELECT contents, type FROM `subjectAlternativeNames` " + //
136 updateMail = new GigiPreparedStatement("UPDATE certs SET crt_name=?," + " created=NOW(), serial=?, caid=? WHERE id=?");
137 warnMail = new GigiPreparedStatement("UPDATE jobs SET warning=warning+1, state=IF(warning<3, 'open','error') WHERE id=?");
139 revoke = new GigiPreparedStatement("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'");
140 revokeCompleted = new GigiPreparedStatement("UPDATE certs SET revoked=NOW() WHERE id=?");
142 finishJob = new GigiPreparedStatement("UPDATE jobs SET state='done' WHERE id=?");
144 locateCA = new GigiPreparedStatement("SELECT id FROM cacerts WHERE keyname=?");
147 } catch (InterruptedException e) {
156 public static void ping() {
157 synchronized (SimpleSigner.class) {
158 SimpleSigner.class.notifyAll();
160 SimpleSigner.class.wait(2000);
161 } catch (InterruptedException e) {
167 private synchronized static void work() {
170 } catch (IOException e2) {
171 e2.printStackTrace();
172 } catch (InterruptedException e2) {
173 e2.printStackTrace();
179 revokeCertificates();
181 SimpleSigner.class.notifyAll();
182 SimpleSigner.class.wait(5000);
183 } catch (IOException e) {
185 } catch (SQLException e) {
187 } catch (InterruptedException e1) {
193 private static void revokeCertificates() throws SQLException, IOException, InterruptedException {
194 GigiResultSet rs = revoke.executeQuery();
195 boolean worked = false;
197 int id = rs.getInt(1);
199 System.out.println("Revoke faked: " + id);
200 revokeCompleted.setInt(1, id);
201 revokeCompleted.execute();
202 finishJob.setInt(1, rs.getInt(3));
210 private static void gencrl() throws IOException, InterruptedException {
214 String[] call = new String[] {
218 "../unassured.crt",//
220 "../unassured.key",//
225 "../unassured.crl",//
230 Process p1 = Runtime.getRuntime().exec(call, null, new File("keys/unassured.ca"));
231 if (p1.waitFor() != 0) {
232 System.out.println("Error while generating crl.");
236 private static void signCertificates() throws SQLException {
237 GigiResultSet rs = readyCerts.executeQuery();
239 Calendar c = Calendar.getInstance();
240 c.setTimeZone(TimeZone.getTimeZone("UTC"));
242 String csrname = rs.getString("csr_name");
243 int id = rs.getInt("id");
244 System.out.println("sign: " + csrname);
246 String csrType = rs.getString("csr_type");
247 CSRType ct = CSRType.valueOf(csrType);
248 File crt = KeyStorage.locateCrt(id);
250 Timestamp from = rs.getTimestamp("executeFrom");
251 String length = rs.getString("executeTo");
255 fromDate = new Date(System.currentTimeMillis());
257 fromDate = new Date(from.getTime());
259 if (length.endsWith("m") || length.endsWith("y")) {
260 String num = length.substring(0, length.length() - 1);
261 int inter = Integer.parseInt(num);
263 if (length.endsWith("m")) {
264 c.add(Calendar.MONTH, inter);
266 c.add(Calendar.YEAR, inter);
268 toDate = c.getTime();
270 toDate = DateSelector.getDateFormat().parse(length);
273 getSANSs.setInt(1, id);
274 GigiResultSet san = getSANSs.executeQuery();
276 LinkedList<SubjectAlternateName> altnames = new LinkedList<>();
278 altnames.add(new SubjectAlternateName(SANType.valueOf(san.getString("type").toUpperCase()), san.getString("contents")));
280 // TODO look them up!
281 // cfg.println("keyUsage=critical," +
282 // "digitalSignature, keyEncipherment, keyAgreement");
283 // cfg.println("extendedKeyUsage=critical," + "clientAuth");
286 int profile = rs.getInt("profile");
287 CertificateProfile cp = CertificateProfile.getById(profile);
288 String s = cp.getId() + "";
289 while (s.length() < 4) {
292 s += "-" + cp.getKeyName() + ".cfg";
293 Properties caP = new Properties();
294 try (FileInputStream inStream = new FileInputStream("signer/profiles/" + s)) {
298 HashMap<String, String> subj = new HashMap<>();
299 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT name, value FROM `certAvas` WHERE `certId`=?")) {
300 ps.setInt(1, rs.getInt("id"));
301 GigiResultSet rs2 = ps.executeQuery();
303 String name = rs2.getString("name");
304 if (name.equals("EMAIL")) {
305 name = "emailAddress";
307 subj.put(name, rs2.getString("value"));
310 if (subj.size() == 0) {
311 subj.put("CN", "<empty>");
312 System.out.println("WARNING: DN was empty");
314 System.out.println(subj);
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);
325 SPKAC sp = new SPKAC(Base64.getDecoder().decode(data));
328 PKCS10 p10 = new PKCS10(PEM.decode("(NEW )?CERTIFICATE REQUEST", new String(data, "UTF-8")));
329 pk = p10.getSubjectPublicKeyInfo();
331 Calendar cal = GregorianCalendar.getInstance();
332 String ca = caP.getProperty("ca") + "_" + cal.get(Calendar.YEAR) + (cal.get(Calendar.MONTH) >= 6 ? "_2" : "_1");
333 File parent = new File("signer/ca");
334 File[] caFiles = parent.listFiles();
335 if (null == caFiles) {
336 caFiles = new File[0];
338 if ( !new File(parent, ca).exists()) {
339 System.out.println("CA " + ca + " not found. Searching for anything other remotely fitting.");
340 for (File f : caFiles) {
341 if (f.getName().startsWith(caP.getProperty("ca"))) {
347 File caKey = new File(parent, ca + "/ca.key");
348 PrivateKey i = loadOpensslKey(caKey);
350 X509Certificate root = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new FileInputStream("signer/ca/" + ca + "/ca.crt"));
351 byte[] cert = generateCert(pk, i, subj, root.getSubjectX500Principal(), altnames, fromDate, toDate, Digest.valueOf(rs.getString("md").toUpperCase()), caP.getProperty("eku"));
352 PrintWriter out = new PrintWriter(crt);
353 out.println("-----BEGIN CERTIFICATE-----");
354 out.println(Base64.getMimeEncoder().encodeToString(cert));
355 out.println("-----END CERTIFICATE-----");
358 try (InputStream is = new FileInputStream(crt)) {
359 locateCA.setString(1, ca);
360 GigiResultSet caRs = locateCA.executeQuery();
362 throw new Error("ca " + ca + " was not found");
365 CertificateFactory cf = CertificateFactory.getInstance("X.509");
366 X509Certificate crtp = (X509Certificate) cf.generateCertificate(is);
367 BigInteger serial = crtp.getSerialNumber();
368 updateMail.setString(1, crt.getPath());
369 updateMail.setString(2, serial.toString(16));
370 updateMail.setInt(3, caRs.getInt("id"));
371 updateMail.setInt(4, id);
372 updateMail.execute();
374 finishJob.setInt(1, rs.getInt("jobid"));
376 System.out.println("signed: " + id);
380 } catch (GeneralSecurityException e) {
382 } catch (IOException e) {
384 } catch (ParseException e) {
387 System.out.println("Error with: " + id);
388 warnMail.setInt(1, rs.getInt("jobid"));
395 private static PrivateKey loadOpensslKey(File f) throws FileNotFoundException, IOException, InvalidKeySpecException, NoSuchAlgorithmException {
396 byte[] p8b = PEM.decode("RSA PRIVATE KEY", new String(IOUtils.readURL(new FileInputStream(f))));
397 DerOutputStream dos = new DerOutputStream();
399 new AlgorithmId(new ObjectIdentifier(new int[] {
400 1, 2, 840, 113549, 1, 1, 1
402 dos.putOctetString(p8b);
403 byte[] ctx = dos.toByteArray();
405 dos.write(DerValue.tag_Sequence, ctx);
406 PKCS8EncodedKeySpec p8 = new PKCS8EncodedKeySpec(dos.toByteArray());
407 PrivateKey i = KeyFactory.getInstance("RSA").generatePrivate(p8);
411 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 {
412 File f = Paths.get("signer", "serial").toFile();
414 try (FileOutputStream fos = new FileOutputStream(f)) {
415 fos.write("1".getBytes("UTF-8"));
418 try (FileInputStream fr = new FileInputStream(f)) {
419 byte[] serial = IOUtils.readURL(fr);
420 BigInteger ser = new BigInteger(new String(serial).trim());
421 ser = ser.add(BigInteger.ONE);
423 PrintWriter pw = new PrintWriter(f);
426 if (digest != Digest.SHA256 && digest != Digest.SHA512) {
427 System.err.println("assuming sha256 either way ;-): " + digest);
428 digest = Digest.SHA256;
430 ObjectIdentifier sha512withrsa = new ObjectIdentifier(new int[] {
431 1, 2, 840, 113549, 1, 1, digest == Digest.SHA256 ? 11 : 13
433 AlgorithmId aid = new AlgorithmId(sha512withrsa);
434 Signature s = Signature.getInstance(digest == Digest.SHA256 ? "SHA256withRSA" : "SHA512withRSA");
436 DerOutputStream cert = new DerOutputStream();
437 DerOutputStream content = new DerOutputStream();
439 DerOutputStream version = new DerOutputStream();
440 version.putInteger(2); // v3
441 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0), version);
443 content.putInteger(ser); // Serial
447 content.write(issuer.getEncoded());
450 DerOutputStream notAround = new DerOutputStream();
451 notAround.putUTCTime(fromDate);
452 notAround.putUTCTime(toDate);
453 content.write(DerValue.tag_Sequence, notAround);
457 X500Name xn = genX500Name(subj);
458 content.write(xn.getEncoded());
461 content.write(pk.getEncoded());
464 DerOutputStream extensions = new DerOutputStream();
466 addExtension(extensions, new ObjectIdentifier(new int[] {
468 }), generateSAN(altnames));
469 addExtension(extensions, new ObjectIdentifier(new int[] {
472 addExtension(extensions, new ObjectIdentifier(new int[] {
474 }), generateEKU(eku));
476 DerOutputStream extensionsSeq = new DerOutputStream();
477 extensionsSeq.write(DerValue.tag_Sequence, extensions);
478 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3), extensionsSeq);
481 DerOutputStream contentSeq = new DerOutputStream();
483 contentSeq.write(DerValue.tag_Sequence, content.toByteArray());
486 s.update(contentSeq.toByteArray());
488 aid.encode(contentSeq);
489 contentSeq.putBitString(s.sign());
490 cert.write(DerValue.tag_Sequence, contentSeq);
492 // X509Certificate c = (X509Certificate)
493 // CertificateFactory.getInstance("X509").generateCertificate(new
494 // ByteArrayInputStream(cert.toByteArray()));
495 // c.verify(pk); only for self-signeds
497 byte[] res = cert.toByteArray();
504 private static byte[] generateKU() throws IOException {
505 try (DerOutputStream dos = new DerOutputStream()) {
506 dos.putBitString(new byte[] {
509 return dos.toByteArray();
513 private static byte[] generateEKU(String eku) throws IOException {
515 try (DerOutputStream dos = new DerOutputStream()) {
516 for (String name : eku.split(",")) {
517 ObjectIdentifier oid;
520 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.1");
523 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.2");
526 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.3");
528 case "emailProtection":
529 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.4");
532 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.9");
536 throw new Error(name);
540 byte[] data = dos.toByteArray();
542 dos.write(DerValue.tag_Sequence, data);
543 return dos.toByteArray();
547 public static X500Name genX500Name(Map<String, String> subj) throws IOException {
548 LinkedList<RDN> rdns = new LinkedList<>();
549 for (Entry<String, String> i : subj.entrySet()) {
553 return new X500Name(rdns.toArray(new RDN[rdns.size()]));
556 private static RDN genRDN(Entry<String, String> i) throws IOException {
557 DerOutputStream dos = new DerOutputStream();
558 dos.putUTF8String(i.getValue());
560 String key = i.getKey();
570 1, 2, 840, 113549, 1, 9, 1
600 throw new Error("unknown RDN-type: " + key);
602 RDN rdn = new RDN(new AVA(new ObjectIdentifier(oid), new DerValue(dos.toByteArray())));
607 private static void addExtension(DerOutputStream extensions, ObjectIdentifier oid, byte[] extContent) throws IOException {
608 DerOutputStream SANs = new DerOutputStream();
610 SANs.putOctetString(extContent);
612 extensions.write(DerValue.tag_Sequence, SANs);
615 private static byte[] generateSAN(List<SubjectAlternateName> altnames) throws IOException {
616 DerOutputStream SANContent = new DerOutputStream();
617 for (SubjectAlternateName san : altnames) {
619 if (san.getType() == SANType.DNS) {
620 type = (byte) GeneralNameInterface.NAME_DNS;
621 } else if (san.getType() == SANType.EMAIL) {
622 type = (byte) GeneralNameInterface.NAME_RFC822;
625 throw new Error("" + san.getType());
627 SANContent.write(DerValue.createTag(DerValue.TAG_CONTEXT, false, type), san.getName().getBytes("UTF-8"));
629 DerOutputStream SANSeqContent = new DerOutputStream();
630 SANSeqContent.write(DerValue.tag_Sequence, SANContent);
631 byte[] byteArray = SANSeqContent.toByteArray();
633 SANSeqContent.close();