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.HashMap;
32 import java.util.LinkedList;
33 import java.util.List;
35 import java.util.Map.Entry;
36 import java.util.Properties;
37 import java.util.TimeZone;
39 import javax.security.auth.x500.X500Principal;
41 import org.cacert.gigi.crypto.SPKAC;
42 import org.cacert.gigi.database.DatabaseConnection;
43 import org.cacert.gigi.database.DatabaseConnection.Link;
44 import org.cacert.gigi.database.GigiPreparedStatement;
45 import org.cacert.gigi.database.GigiResultSet;
46 import org.cacert.gigi.dbObjects.Certificate.CSRType;
47 import org.cacert.gigi.dbObjects.Certificate.SANType;
48 import org.cacert.gigi.dbObjects.Certificate.SubjectAlternateName;
49 import org.cacert.gigi.dbObjects.CertificateProfile;
50 import org.cacert.gigi.dbObjects.Digest;
51 import org.cacert.gigi.output.DateSelector;
53 import sun.security.pkcs10.PKCS10;
54 import sun.security.util.DerOutputStream;
55 import sun.security.util.DerValue;
56 import sun.security.util.ObjectIdentifier;
57 import sun.security.x509.AVA;
58 import sun.security.x509.AlgorithmId;
59 import sun.security.x509.GeneralNameInterface;
60 import sun.security.x509.RDN;
61 import sun.security.x509.X500Name;
63 public class SimpleSigner {
65 private static GigiPreparedStatement warnMail;
67 private static GigiPreparedStatement updateMail;
69 private static GigiPreparedStatement readyCerts;
71 private static GigiPreparedStatement getSANSs;
73 private static GigiPreparedStatement revoke;
75 private static GigiPreparedStatement revokeCompleted;
77 private static GigiPreparedStatement finishJob;
79 private static GigiPreparedStatement locateCA;
81 private static volatile boolean running = true;
83 private static Thread runner;
85 private static SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss'Z'");
88 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
89 sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
92 public static void main(String[] args) throws IOException, SQLException, InterruptedException {
93 Properties p = new Properties();
94 try (Reader reader = new InputStreamReader(new FileInputStream("config/gigi.properties"), "UTF-8")) {
97 DatabaseConnection.init(p);
102 public static void stopSigner() throws InterruptedException {
103 Thread capturedRunner;
104 synchronized (SimpleSigner.class) {
105 if (runner == null) {
106 throw new IllegalStateException("already stopped");
108 capturedRunner = runner;
110 SimpleSigner.class.notifyAll();
112 capturedRunner.join();
115 public synchronized static void runSigner() throws SQLException, IOException, InterruptedException {
116 if (runner != null) {
117 throw new IllegalStateException("already running");
121 runner = new Thread() {
125 try (Link l = DatabaseConnection.newLink(false)) {
126 readyCerts = new GigiPreparedStatement("SELECT certs.id AS id, certs.csr_name, jobs.id AS jobid, csr_type, md, `executeFrom`, `executeTo`, profile FROM jobs " + //
127 "INNER JOIN certs ON certs.id=jobs.`targetId` " + //
128 "INNER JOIN profiles ON profiles.id=certs.profile " + //
129 "WHERE jobs.state='open' "//
130 + "AND task='sign'");
132 getSANSs = new GigiPreparedStatement("SELECT contents, type FROM `subjectAlternativeNames` " + //
135 updateMail = new GigiPreparedStatement("UPDATE certs SET crt_name=?," + " created=NOW(), serial=?, caid=? WHERE id=?");
136 warnMail = new GigiPreparedStatement("UPDATE jobs SET warning=warning+1, state=IF(warning<3, 'open','error') WHERE id=?");
138 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'");
139 revokeCompleted = new GigiPreparedStatement("UPDATE certs SET revoked=NOW() WHERE id=?");
141 finishJob = new GigiPreparedStatement("UPDATE jobs SET state='done' WHERE id=?");
143 locateCA = new GigiPreparedStatement("SELECT id FROM cacerts WHERE keyname=?");
146 } catch (InterruptedException e) {
155 private synchronized static void work() {
158 } catch (IOException e2) {
159 e2.printStackTrace();
160 } catch (InterruptedException e2) {
161 e2.printStackTrace();
167 revokeCertificates();
169 SimpleSigner.class.wait(5000);
170 } catch (IOException e) {
172 } catch (SQLException e) {
174 } catch (InterruptedException e1) {
180 private static void revokeCertificates() throws SQLException, IOException, InterruptedException {
181 GigiResultSet rs = revoke.executeQuery();
182 boolean worked = false;
184 int id = rs.getInt(1);
186 System.out.println("Revoke faked: " + id);
187 revokeCompleted.setInt(1, id);
188 revokeCompleted.execute();
189 finishJob.setInt(1, rs.getInt(3));
197 private static void gencrl() throws IOException, InterruptedException {
201 String[] call = new String[] {
204 "../unassured.crt",//
206 "../unassured.key",//
211 "../unassured.crl",//
216 Process p1 = Runtime.getRuntime().exec(call, null, new File("keys/unassured.ca"));
217 if (p1.waitFor() != 0) {
218 System.out.println("Error while generating crl.");
222 private static int counter = 0;
224 private static void signCertificates() throws SQLException {
225 GigiResultSet rs = readyCerts.executeQuery();
227 Calendar c = Calendar.getInstance();
228 c.setTimeZone(TimeZone.getTimeZone("UTC"));
230 String csrname = rs.getString("csr_name");
231 int id = rs.getInt("id");
232 System.out.println("sign: " + csrname);
234 String csrType = rs.getString("csr_type");
235 CSRType ct = CSRType.valueOf(csrType);
236 File crt = KeyStorage.locateCrt(id);
238 Timestamp from = rs.getTimestamp("executeFrom");
239 String length = rs.getString("executeTo");
243 fromDate = new Date(System.currentTimeMillis());
245 fromDate = new Date(from.getTime());
247 if (length.endsWith("m") || length.endsWith("y")) {
248 String num = length.substring(0, length.length() - 1);
249 int inter = Integer.parseInt(num);
251 if (length.endsWith("m")) {
252 c.add(Calendar.MONTH, inter);
254 c.add(Calendar.YEAR, inter);
256 toDate = c.getTime();
258 toDate = DateSelector.getDateFormat().parse(length);
261 getSANSs.setInt(1, id);
262 GigiResultSet san = getSANSs.executeQuery();
264 LinkedList<SubjectAlternateName> altnames = new LinkedList<>();
266 altnames.add(new SubjectAlternateName(SANType.valueOf(san.getString("type").toUpperCase()), san.getString("contents")));
268 // TODO look them up!
269 // cfg.println("keyUsage=critical," +
270 // "digitalSignature, keyEncipherment, keyAgreement");
271 // cfg.println("extendedKeyUsage=critical," + "clientAuth");
274 int profile = rs.getInt("profile");
275 CertificateProfile cp = CertificateProfile.getById(profile);
276 String s = cp.getId() + "";
277 while (s.length() < 4) {
280 s += "-" + cp.getKeyName() + ".cfg";
281 Properties caP = new Properties();
282 try (FileInputStream inStream = new FileInputStream("signer/profiles/" + s)) {
285 String ca = caP.getProperty("ca") + "_2015_1";
287 HashMap<String, String> subj = new HashMap<>();
288 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT name, value FROM `certAvas` WHERE `certId`=?")) {
289 ps.setInt(1, rs.getInt("id"));
290 GigiResultSet rs2 = ps.executeQuery();
292 String name = rs2.getString("name");
293 if (name.equals("EMAIL")) {
294 name = "emailAddress";
296 subj.put(name, rs2.getString("value"));
299 if (subj.size() == 0) {
300 subj.put("CN", "<empty>");
301 System.out.println("WARNING: DN was empty");
303 System.out.println(subj);
306 byte[] data = IOUtils.readURL(new FileInputStream(csrname));
307 if (ct == CSRType.SPKAC) {
308 String dt = new String(data, "UTF-8");
309 if (dt.startsWith("SPKAC=")) {
310 dt = dt.substring(6);
311 data = dt.getBytes("UTF-8");
312 System.out.println(dt);
314 SPKAC sp = new SPKAC(Base64.getDecoder().decode(data));
317 PKCS10 p10 = new PKCS10(PEM.decode("(NEW )?CERTIFICATE REQUEST", new String(data, "UTF-8")));
318 pk = p10.getSubjectPublicKeyInfo();
320 PrivateKey i = loadOpensslKey(new File("signer/ca/" + ca + "/ca.key"));
322 X509Certificate root = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new FileInputStream("signer/ca/" + ca + "/ca.crt"));
323 byte[] cert = generateCert(pk, i, subj, root.getSubjectX500Principal(), altnames, fromDate, toDate, Digest.valueOf(rs.getString("md").toUpperCase()), caP.getProperty("eku"));
324 PrintWriter out = new PrintWriter(crt);
325 out.println("-----BEGIN CERTIFICATE-----");
326 out.println(Base64.getMimeEncoder().encodeToString(cert));
327 out.println("-----END CERTIFICATE-----");
330 try (InputStream is = new FileInputStream(crt)) {
331 locateCA.setString(1, ca);
332 GigiResultSet caRs = locateCA.executeQuery();
334 throw new Error("ca " + ca + " was not found");
337 CertificateFactory cf = CertificateFactory.getInstance("X.509");
338 X509Certificate crtp = (X509Certificate) cf.generateCertificate(is);
339 BigInteger serial = crtp.getSerialNumber();
340 updateMail.setString(1, crt.getPath());
341 updateMail.setString(2, serial.toString(16));
342 updateMail.setInt(3, caRs.getInt("id"));
343 updateMail.setInt(4, id);
344 updateMail.execute();
346 finishJob.setInt(1, rs.getInt("jobid"));
348 System.out.println("signed: " + id);
352 } catch (GeneralSecurityException e) {
354 } catch (IOException e) {
356 } catch (ParseException e) {
359 System.out.println("Error with: " + id);
360 warnMail.setInt(1, rs.getInt("jobid"));
367 private static PrivateKey loadOpensslKey(File f) throws FileNotFoundException, IOException, InvalidKeySpecException, NoSuchAlgorithmException {
368 byte[] p8b = PEM.decode("RSA PRIVATE KEY", new String(IOUtils.readURL(new FileInputStream(f))));
369 DerOutputStream dos = new DerOutputStream();
371 new AlgorithmId(new ObjectIdentifier(new int[] {
372 1, 2, 840, 113549, 1, 1, 1
374 dos.putOctetString(p8b);
375 byte[] ctx = dos.toByteArray();
377 dos.write(DerValue.tag_Sequence, ctx);
378 PKCS8EncodedKeySpec p8 = new PKCS8EncodedKeySpec(dos.toByteArray());
379 PrivateKey i = KeyFactory.getInstance("RSA").generatePrivate(p8);
383 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 {
384 File f = Paths.get("signer", "serial").toFile();
386 try (FileOutputStream fos = new FileOutputStream(f)) {
387 fos.write("1".getBytes("UTF-8"));
390 try (FileInputStream fr = new FileInputStream(f)) {
391 byte[] serial = IOUtils.readURL(fr);
392 BigInteger ser = new BigInteger(new String(serial).trim());
393 ser = ser.add(BigInteger.ONE);
395 PrintWriter pw = new PrintWriter(f);
398 if (digest != Digest.SHA256 && digest != Digest.SHA512) {
399 System.err.println("assuming sha256 either way ;-): " + digest);
400 digest = Digest.SHA256;
402 ObjectIdentifier sha512withrsa = new ObjectIdentifier(new int[] {
403 1, 2, 840, 113549, 1, 1, digest == Digest.SHA256 ? 11 : 13
405 AlgorithmId aid = new AlgorithmId(sha512withrsa);
406 Signature s = Signature.getInstance(digest == Digest.SHA256 ? "SHA256withRSA" : "SHA512withRSA");
408 DerOutputStream cert = new DerOutputStream();
409 DerOutputStream content = new DerOutputStream();
411 DerOutputStream version = new DerOutputStream();
412 version.putInteger(2); // v3
413 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0), version);
415 content.putInteger(ser); // Serial
419 content.write(issuer.getEncoded());
422 DerOutputStream notAround = new DerOutputStream();
423 notAround.putUTCTime(fromDate);
424 notAround.putUTCTime(toDate);
425 content.write(DerValue.tag_Sequence, notAround);
429 X500Name xn = genX500Name(subj);
430 content.write(xn.getEncoded());
433 content.write(pk.getEncoded());
436 DerOutputStream extensions = new DerOutputStream();
438 addExtension(extensions, new ObjectIdentifier(new int[] {
440 }), generateSAN(altnames));
441 addExtension(extensions, new ObjectIdentifier(new int[] {
444 addExtension(extensions, new ObjectIdentifier(new int[] {
446 }), generateEKU(eku));
448 DerOutputStream extensionsSeq = new DerOutputStream();
449 extensionsSeq.write(DerValue.tag_Sequence, extensions);
450 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3), extensionsSeq);
453 DerOutputStream contentSeq = new DerOutputStream();
455 contentSeq.write(DerValue.tag_Sequence, content.toByteArray());
458 s.update(contentSeq.toByteArray());
460 aid.encode(contentSeq);
461 contentSeq.putBitString(s.sign());
462 cert.write(DerValue.tag_Sequence, contentSeq);
464 // X509Certificate c = (X509Certificate)
465 // CertificateFactory.getInstance("X509").generateCertificate(new
466 // ByteArrayInputStream(cert.toByteArray()));
467 // c.verify(pk); only for self-signeds
469 byte[] res = cert.toByteArray();
476 private static byte[] generateKU() throws IOException {
477 try (DerOutputStream dos = new DerOutputStream()) {
478 dos.putBitString(new byte[] {
481 return dos.toByteArray();
485 private static byte[] generateEKU(String eku) throws IOException {
487 DerOutputStream dos = new DerOutputStream();
488 for (String name : eku.split(",")) {
489 ObjectIdentifier oid;
492 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.1");
495 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.2");
498 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.3");
500 case "emailProtection":
501 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.4");
504 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.9");
508 throw new Error(name);
512 byte[] data = dos.toByteArray();
514 dos.write(DerValue.tag_Sequence, data);
515 return dos.toByteArray();
518 public static X500Name genX500Name(Map<String, String> subj) throws IOException {
519 LinkedList<RDN> rdns = new LinkedList<>();
520 for (Entry<String, String> i : subj.entrySet()) {
524 return new X500Name(rdns.toArray(new RDN[rdns.size()]));
527 private static RDN genRDN(Entry<String, String> i) throws IOException {
528 DerOutputStream dos = new DerOutputStream();
529 dos.putUTF8String(i.getValue());
531 String key = i.getKey();
541 1, 2, 840, 113549, 1, 9, 1
571 throw new Error("unknown RDN-type: " + key);
573 RDN rdn = new RDN(new AVA(new ObjectIdentifier(oid), new DerValue(dos.toByteArray())));
578 private static void addExtension(DerOutputStream extensions, ObjectIdentifier oid, byte[] extContent) throws IOException {
579 DerOutputStream SANs = new DerOutputStream();
581 SANs.putOctetString(extContent);
583 extensions.write(DerValue.tag_Sequence, SANs);
586 private static byte[] generateSAN(List<SubjectAlternateName> altnames) throws IOException {
587 DerOutputStream SANContent = new DerOutputStream();
588 for (SubjectAlternateName san : altnames) {
590 if (san.getType() == SANType.DNS) {
591 type = (byte) GeneralNameInterface.NAME_DNS;
592 } else if (san.getType() == SANType.EMAIL) {
593 type = (byte) GeneralNameInterface.NAME_RFC822;
596 throw new Error("" + san.getType());
598 SANContent.write(DerValue.createTag(DerValue.TAG_CONTEXT, false, type), san.getName().getBytes("UTF-8"));
600 DerOutputStream SANSeqContent = new DerOutputStream();
601 SANSeqContent.write(DerValue.tag_Sequence, SANContent);
602 byte[] byteArray = SANSeqContent.toByteArray();
604 SANSeqContent.close();