1 package org.cacert.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.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;
39 import java.util.Map.Entry;
40 import java.util.Properties;
41 import java.util.TimeZone;
43 import javax.security.auth.x500.X500Principal;
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 import org.cacert.gigi.testUtils.IOUtils;
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 volatile boolean running = true;
86 private static Thread runner;
88 private static SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss'Z'");
91 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
92 sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
95 public static void main(String[] args) throws IOException, SQLException, InterruptedException {
98 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
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) {
109 Properties p = new Properties();
110 try (Reader reader = new InputStreamReader(new FileInputStream("config/gigi.properties"), "UTF-8")) {
113 DatabaseConnection.init(p);
118 public static void stopSigner() throws InterruptedException {
119 Thread capturedRunner;
120 synchronized (SimpleSigner.class) {
121 if (runner == null) {
122 throw new IllegalStateException("already stopped");
124 capturedRunner = runner;
126 SimpleSigner.class.notifyAll();
128 capturedRunner.join();
131 public synchronized static void runSigner() throws SQLException, IOException, InterruptedException {
132 if (runner != null) {
133 throw new IllegalStateException("already running");
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'");
142 getSANSs = DatabaseConnection.getInstance().prepare("SELECT contents, type FROM subjectAlternativeNames " + //
145 updateMail = DatabaseConnection.getInstance().prepare("UPDATE certs SET crt_name=?," + " created=NOW(), serial=?, caid=1 WHERE id=?");
146 warnMail = DatabaseConnection.getInstance().prepare("UPDATE jobs SET warning=warning+1, state=IF(warning<3, 'open','error') WHERE id=?");
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=?");
151 finishJob = DatabaseConnection.getInstance().prepare("UPDATE jobs SET state='done' WHERE id=?");
153 runner = new Thread() {
164 private synchronized static void work() {
167 } catch (IOException e2) {
168 e2.printStackTrace();
169 } catch (InterruptedException e2) {
170 e2.printStackTrace();
176 revokeCertificates();
178 SimpleSigner.class.wait(5000);
179 } catch (IOException e) {
181 } catch (SQLException e) {
183 } catch (InterruptedException e1) {
189 private static void revokeCertificates() throws SQLException, IOException, InterruptedException {
190 GigiResultSet rs = revoke.executeQuery();
191 boolean worked = false;
193 int id = rs.getInt(1);
194 File crt = KeyStorage.locateCrt(id);
196 revokeCompleted.setInt(1, id);
197 revokeCompleted.execute();
198 finishJob.setInt(1, rs.getInt(3));
206 private static void gencrl() throws IOException, InterruptedException {
210 String[] call = new String[] {
213 "../unassured.crt",//
215 "../unassured.key",//
220 "../unassured.crl",//
225 Process p1 = Runtime.getRuntime().exec(call, null, new File("keys/unassured.ca"));
226 if (p1.waitFor() != 0) {
227 System.out.println("Error while generating crl.");
231 private static int counter = 0;
233 private static void signCertificates() throws SQLException {
234 GigiResultSet rs = readyCerts.executeQuery();
236 Calendar c = Calendar.getInstance();
237 c.setTimeZone(TimeZone.getTimeZone("UTC"));
239 String csrname = rs.getString("csr_name");
240 int id = rs.getInt("id");
241 System.out.println("sign: " + csrname);
243 String csrType = rs.getString("csr_type");
244 CSRType ct = CSRType.valueOf(csrType);
245 File crt = KeyStorage.locateCrt(id);
247 Timestamp from = rs.getTimestamp("executeFrom");
248 String length = rs.getString("executeTo");
252 fromDate = new Date(System.currentTimeMillis());
254 fromDate = new Date(from.getTime());
256 if (length.endsWith("m") || length.endsWith("y")) {
257 String num = length.substring(0, length.length() - 1);
258 int inter = Integer.parseInt(num);
260 if (length.endsWith("m")) {
261 c.add(Calendar.MONTH, inter);
263 c.add(Calendar.YEAR, inter);
265 toDate = c.getTime();
267 toDate = DateSelector.getDateFormat().parse(length);
270 getSANSs.setInt(1, id);
271 GigiResultSet san = getSANSs.executeQuery();
273 boolean first = true;
274 LinkedList<SubjectAlternateName> altnames = new LinkedList<>();
277 altnames.add(new SubjectAlternateName(SANType.valueOf(san.getString("type").toUpperCase()), san.getString("contents")));
279 // TODO look them up!
280 // cfg.println("keyUsage=critical," +
281 // "digitalSignature, keyEncipherment, keyAgreement");
282 // cfg.println("extendedKeyUsage=critical," + "clientAuth");
285 int profile = rs.getInt("profile");
286 CertificateProfile cp = CertificateProfile.getById(profile);
287 String s = cp.getId() + "";
288 while (s.length() < 4) {
291 s += "-" + cp.getKeyName() + ".cfg";
292 Properties caP = new Properties();
293 caP.load(new FileInputStream("signer/profiles/" + s));
294 String ca = caP.getProperty("ca") + "_2015_1";
296 HashMap<String, String> subj = new HashMap<>();
297 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT name, value FROM certAvas WHERE certId=?");
298 ps.setInt(1, rs.getInt("id"));
299 GigiResultSet rs2 = ps.executeQuery();
301 String name = rs2.getString("name");
302 if (name.equals("EMAIL")) {
303 name = "emailAddress";
305 subj.put(name, rs2.getString("value"));
307 if (subj.size() == 0) {
308 subj.put("CN", "<empty>");
309 System.out.println("WARNING: DN was empty");
311 System.out.println(subj);
314 byte[] data = IOUtils.readURL(new FileInputStream(csrname));
315 if (ct == CSRType.SPKAC) {
316 SPKAC sp = new SPKAC(data);
319 PKCS10 p10 = new PKCS10(PEM.decode("(NEW )?CERTIFICATE REQUEST", new String(data)));
320 pk = p10.getSubjectPublicKeyInfo();
322 PrivateKey i = loadOpensslKey(new File("signer/ca/" + ca + "/ca.key"));
325 X509Certificate root = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new FileInputStream("signer/ca/" + ca + "/ca.crt"));
326 byte[] cert = generateCert(pk, i, subj, root.getSubjectX500Principal(), altnames, fromDate, toDate, Digest.valueOf(rs.getString("md").toUpperCase()), caP.getProperty("eku"));
327 PrintWriter out = new PrintWriter(crt);
328 out.println("-----BEGIN CERTIFICATE-----");
329 out.println(Base64.getMimeEncoder().encodeToString(cert));
330 out.println("-----END CERTIFICATE-----");
334 * call = new String[] { "openssl", "ca",// "-in", "../../"
335 * + csrname,// "-cert", "../" + ca + ".crt",// "-keyfile",
336 * "../" + ca + ".key",// "-out", "../../" +
337 * crt.getPath(),// "-utf8", "-startdate",
338 * sdf.format(fromDate),// "-enddate", sdf.format(toDate),//
339 * "-batch",// "-md", rs.getString("md"),// "-extfile",
340 * "../" + f.getName(),// "-subj",
341 * Certificate.stringifyDN(subj),// "-config",
342 * "../selfsign.config"// };
346 try (InputStream is = new FileInputStream(crt)) {
347 CertificateFactory cf = CertificateFactory.getInstance("X.509");
348 X509Certificate crtp = (X509Certificate) cf.generateCertificate(is);
349 BigInteger serial = crtp.getSerialNumber();
350 updateMail.setString(1, crt.getPath());
351 updateMail.setString(2, serial.toString(16));
352 updateMail.setInt(3, id);
353 updateMail.execute();
355 finishJob.setInt(1, rs.getInt("jobid"));
357 System.out.println("signed: " + id);
361 } catch (GeneralSecurityException e) {
363 } catch (IOException e) {
365 } catch (ParseException e) {
368 System.out.println("Error with: " + id);
369 warnMail.setInt(1, rs.getInt("jobid"));
376 private static PrivateKey loadOpensslKey(File f) throws FileNotFoundException, IOException, InvalidKeySpecException, NoSuchAlgorithmException {
377 byte[] p8b = PEM.decode("RSA PRIVATE KEY", new String(IOUtils.readURL(new FileInputStream(f))));
378 DerOutputStream dos = new DerOutputStream();
380 new AlgorithmId(new ObjectIdentifier(new int[] {
381 1, 2, 840, 113549, 1, 1, 1
383 dos.putOctetString(p8b);
384 byte[] ctx = dos.toByteArray();
386 dos.write(DerValue.tag_Sequence, ctx);
387 PKCS8EncodedKeySpec p8 = new PKCS8EncodedKeySpec(dos.toByteArray());
388 PrivateKey i = KeyFactory.getInstance("RSA").generatePrivate(p8);
392 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 {
393 File f = Paths.get("signer", "serial").toFile();
395 FileOutputStream fos = new FileOutputStream(f);
396 fos.write("1".getBytes());
399 try (FileInputStream fr = new FileInputStream(f)) {
400 byte[] serial = IOUtils.readURL(fr);
401 BigInteger ser = new BigInteger(new String(serial).trim());
402 ser = ser.add(BigInteger.ONE);
404 PrintWriter pw = new PrintWriter(f);
407 if (digest != Digest.SHA256 && digest != Digest.SHA512) {
408 System.err.println("assuming sha256 either way ;-): " + digest);
409 digest = Digest.SHA256;
411 ObjectIdentifier sha512withrsa = new ObjectIdentifier(new int[] {
412 1, 2, 840, 113549, 1, 1, digest == Digest.SHA256 ? 11 : 13
414 AlgorithmId aid = new AlgorithmId(sha512withrsa);
415 Signature s = Signature.getInstance(digest == Digest.SHA256 ? "SHA256withRSA" : "SHA512withRSA");
417 DerOutputStream cert = new DerOutputStream();
418 DerOutputStream content = new DerOutputStream();
420 DerOutputStream version = new DerOutputStream();
421 version.putInteger(2); // v3
422 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0), version);
424 content.putInteger(ser); // Serial
428 content.write(issuer.getEncoded());
431 DerOutputStream notAround = new DerOutputStream();
432 notAround.putUTCTime(fromDate);
433 notAround.putUTCTime(toDate);
434 content.write(DerValue.tag_Sequence, notAround);
438 X500Name xn = genX500Name(subj);
439 content.write(xn.getEncoded());
442 content.write(pk.getEncoded());
445 DerOutputStream extensions = new DerOutputStream();
447 addExtension(extensions, new ObjectIdentifier(new int[] {
449 }), generateSAN(altnames));
450 addExtension(extensions, new ObjectIdentifier(new int[] {
453 addExtension(extensions, new ObjectIdentifier(new int[] {
455 }), generateEKU(eku));
457 DerOutputStream extensionsSeq = new DerOutputStream();
458 extensionsSeq.write(DerValue.tag_Sequence, extensions);
459 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3), extensionsSeq);
462 DerOutputStream contentSeq = new DerOutputStream();
464 contentSeq.write(DerValue.tag_Sequence, content.toByteArray());
467 s.update(contentSeq.toByteArray());
469 aid.encode(contentSeq);
470 contentSeq.putBitString(s.sign());
471 cert.write(DerValue.tag_Sequence, contentSeq);
473 X509Certificate c = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(cert.toByteArray()));
474 // c.verify(pk); only for self-signeds
476 return cert.toByteArray();
481 private static byte[] generateKU() throws IOException {
482 DerOutputStream dos = new DerOutputStream();
483 dos.putBitString(new byte[] {
486 return dos.toByteArray();
489 private static byte[] generateEKU(String eku) throws IOException {
491 DerOutputStream dos = new DerOutputStream();
492 for (String name : eku.split(",")) {
493 ObjectIdentifier oid;
496 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.1");
499 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.2");
502 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.3");
504 case "emailProtection":
505 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.4");
509 throw new Error(name);
513 byte[] data = dos.toByteArray();
515 dos.write(DerValue.tag_Sequence, data);
516 return dos.toByteArray();
519 private static X500Name genX500Name(Map<String, String> subj) throws IOException {
520 LinkedList<RDN> rdns = new LinkedList<>();
521 for (Entry<String, String> i : subj.entrySet()) {
525 return new X500Name(rdns.toArray(new RDN[rdns.size()]));
528 private static RDN genRDN(Entry<String, String> i) throws IOException {
529 DerOutputStream dos = new DerOutputStream();
530 dos.putUTF8String(i.getValue());
532 String key = i.getKey();
542 1, 2, 840, 113549, 1, 9, 1
556 throw new Error("unknown RDN-type: " + key);
558 RDN rdn = new RDN(new AVA(new ObjectIdentifier(oid), new DerValue(dos.toByteArray())));
562 private static void addExtension(DerOutputStream extensions, ObjectIdentifier oid, byte[] extContent) throws IOException {
563 DerOutputStream SANs = new DerOutputStream();
565 SANs.putOctetString(extContent);
567 extensions.write(DerValue.tag_Sequence, SANs);
570 private static byte[] generateSAN(List<SubjectAlternateName> altnames) throws IOException {
571 DerOutputStream SANContent = new DerOutputStream();
572 for (SubjectAlternateName san : altnames) {
574 if (san.getType() == SANType.DNS) {
575 type = (byte) GeneralNameInterface.NAME_DNS;
576 } else if (san.getType() == SANType.EMAIL) {
577 type = (byte) GeneralNameInterface.NAME_RFC822;
579 throw new Error("" + san.getType());
581 SANContent.write(DerValue.createTag(DerValue.TAG_CONTEXT, false, type), san.getName().getBytes());
583 DerOutputStream SANSeqContent = new DerOutputStream();
584 SANSeqContent.write(DerValue.tag_Sequence, SANContent);
585 byte[] byteArray = SANSeqContent.toByteArray();