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;
57 import sun.security.pkcs10.PKCS10;
58 import sun.security.util.DerOutputStream;
59 import sun.security.util.DerValue;
60 import sun.security.util.ObjectIdentifier;
61 import sun.security.x509.AVA;
62 import sun.security.x509.AlgorithmId;
63 import sun.security.x509.GeneralNameInterface;
64 import sun.security.x509.RDN;
65 import sun.security.x509.X500Name;
67 public class SimpleSigner {
69 private static GigiPreparedStatement warnMail;
71 private static GigiPreparedStatement updateMail;
73 private static GigiPreparedStatement readyCerts;
75 private static GigiPreparedStatement getSANSs;
77 private static GigiPreparedStatement revoke;
79 private static GigiPreparedStatement revokeCompleted;
81 private static GigiPreparedStatement finishJob;
83 private static volatile boolean running = true;
85 private static Thread runner;
87 private static SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss'Z'");
90 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
91 sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
94 public static void main(String[] args) throws IOException, SQLException, InterruptedException {
97 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
99 KeyPair kp = kpg.generateKeyPair();
100 X500Principal xp = new X500Principal(genX500Name(Certificate.buildDN("CN", "uiae")).getEncoded());
101 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");
102 System.out.println(Base64.getMimeEncoder().encodeToString(i));
103 } catch (GeneralSecurityException e) {
108 Properties p = new Properties();
109 try (Reader reader = new InputStreamReader(new FileInputStream("config/gigi.properties"), "UTF-8")) {
112 DatabaseConnection.init(p);
117 public static void stopSigner() throws InterruptedException {
118 Thread capturedRunner;
119 synchronized (SimpleSigner.class) {
120 if (runner == null) {
121 throw new IllegalStateException("already stopped");
123 capturedRunner = runner;
125 SimpleSigner.class.notifyAll();
127 capturedRunner.join();
130 public synchronized static void runSigner() throws SQLException, IOException, InterruptedException {
131 if (runner != null) {
132 throw new IllegalStateException("already running");
135 readyCerts = DatabaseConnection.getInstance().prepare("SELECT certs.id AS id, certs.csr_name, jobs.id AS jobid, csr_type, md, executeFrom, executeTo, profile FROM jobs " + //
136 "INNER JOIN certs ON certs.id=jobs.targetId " + //
137 "INNER JOIN profiles ON profiles.id=certs.profile " + //
138 "WHERE jobs.state='open' "//
139 + "AND task='sign'");
141 getSANSs = DatabaseConnection.getInstance().prepare("SELECT contents, type FROM subjectAlternativeNames " + //
144 updateMail = DatabaseConnection.getInstance().prepare("UPDATE certs SET crt_name=?," + " created=NOW(), serial=?, caid=1 WHERE id=?");
145 warnMail = DatabaseConnection.getInstance().prepare("UPDATE jobs SET warning=warning+1, state=IF(warning<3, 'open','error') WHERE id=?");
147 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'");
148 revokeCompleted = DatabaseConnection.getInstance().prepare("UPDATE certs SET revoked=NOW() WHERE id=?");
150 finishJob = DatabaseConnection.getInstance().prepare("UPDATE jobs SET state='done' WHERE id=?");
152 runner = new Thread() {
163 private synchronized static void work() {
166 } catch (IOException e2) {
167 e2.printStackTrace();
168 } catch (InterruptedException e2) {
169 e2.printStackTrace();
175 revokeCertificates();
177 SimpleSigner.class.wait(5000);
178 } catch (IOException e) {
180 } catch (SQLException e) {
182 } catch (InterruptedException e1) {
188 private static void revokeCertificates() throws SQLException, IOException, InterruptedException {
189 GigiResultSet rs = revoke.executeQuery();
190 boolean worked = false;
192 int id = rs.getInt(1);
193 File crt = KeyStorage.locateCrt(id);
195 revokeCompleted.setInt(1, id);
196 revokeCompleted.execute();
197 finishJob.setInt(1, rs.getInt(3));
205 private static void gencrl() throws IOException, InterruptedException {
209 String[] call = new String[] {
212 "../unassured.crt",//
214 "../unassured.key",//
219 "../unassured.crl",//
224 Process p1 = Runtime.getRuntime().exec(call, null, new File("keys/unassured.ca"));
225 if (p1.waitFor() != 0) {
226 System.out.println("Error while generating crl.");
230 private static int counter = 0;
232 private static void signCertificates() throws SQLException {
233 GigiResultSet rs = readyCerts.executeQuery();
235 Calendar c = Calendar.getInstance();
236 c.setTimeZone(TimeZone.getTimeZone("UTC"));
238 String csrname = rs.getString("csr_name");
239 int id = rs.getInt("id");
240 System.out.println("sign: " + csrname);
242 String csrType = rs.getString("csr_type");
243 CSRType ct = CSRType.valueOf(csrType);
244 File crt = KeyStorage.locateCrt(id);
246 Timestamp from = rs.getTimestamp("executeFrom");
247 String length = rs.getString("executeTo");
251 fromDate = new Date(System.currentTimeMillis());
253 fromDate = new Date(from.getTime());
255 if (length.endsWith("m") || length.endsWith("y")) {
256 String num = length.substring(0, length.length() - 1);
257 int inter = Integer.parseInt(num);
259 if (length.endsWith("m")) {
260 c.add(Calendar.MONTH, inter);
262 c.add(Calendar.YEAR, inter);
264 toDate = c.getTime();
266 toDate = DateSelector.getDateFormat().parse(length);
269 getSANSs.setInt(1, id);
270 GigiResultSet san = getSANSs.executeQuery();
272 boolean first = true;
273 LinkedList<SubjectAlternateName> altnames = new LinkedList<>();
276 altnames.add(new SubjectAlternateName(SANType.valueOf(san.getString("type").toUpperCase()), san.getString("contents")));
278 // TODO look them up!
279 // cfg.println("keyUsage=critical," +
280 // "digitalSignature, keyEncipherment, keyAgreement");
281 // cfg.println("extendedKeyUsage=critical," + "clientAuth");
284 int profile = rs.getInt("profile");
285 CertificateProfile cp = CertificateProfile.getById(profile);
286 String s = cp.getId() + "";
287 while (s.length() < 4) {
290 s += "-" + cp.getKeyName() + ".cfg";
291 Properties caP = new Properties();
292 caP.load(new FileInputStream("signer/profiles/" + s));
293 String ca = caP.getProperty("ca") + "_2015_1";
295 HashMap<String, String> subj = new HashMap<>();
296 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT name, value FROM certAvas WHERE certId=?");
297 ps.setInt(1, rs.getInt("id"));
298 GigiResultSet rs2 = ps.executeQuery();
300 String name = rs2.getString("name");
301 if (name.equals("EMAIL")) {
302 name = "emailAddress";
304 subj.put(name, rs2.getString("value"));
306 if (subj.size() == 0) {
307 subj.put("CN", "<empty>");
308 System.out.println("WARNING: DN was empty");
310 System.out.println(subj);
313 byte[] data = IOUtils.readURL(new FileInputStream(csrname));
314 if (ct == CSRType.SPKAC) {
315 SPKAC sp = new SPKAC(data);
318 PKCS10 p10 = new PKCS10(PEM.decode("(NEW )?CERTIFICATE REQUEST", new String(data)));
319 pk = p10.getSubjectPublicKeyInfo();
321 PrivateKey i = loadOpensslKey(new File("signer/ca/" + ca + "/ca.key"));
324 X509Certificate root = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new FileInputStream("signer/ca/" + ca + "/ca.crt"));
325 byte[] cert = generateCert(pk, i, subj, root.getSubjectX500Principal(), altnames, fromDate, toDate, Digest.valueOf(rs.getString("md").toUpperCase()), caP.getProperty("eku"));
326 PrintWriter out = new PrintWriter(crt);
327 out.println("-----BEGIN CERTIFICATE-----");
328 out.println(Base64.getMimeEncoder().encodeToString(cert));
329 out.println("-----END CERTIFICATE-----");
333 * call = new String[] { "openssl", "ca",// "-in", "../../"
334 * + csrname,// "-cert", "../" + ca + ".crt",// "-keyfile",
335 * "../" + ca + ".key",// "-out", "../../" +
336 * crt.getPath(),// "-utf8", "-startdate",
337 * sdf.format(fromDate),// "-enddate", sdf.format(toDate),//
338 * "-batch",// "-md", rs.getString("md"),// "-extfile",
339 * "../" + f.getName(),// "-subj",
340 * Certificate.stringifyDN(subj),// "-config",
341 * "../selfsign.config"// };
345 try (InputStream is = new FileInputStream(crt)) {
346 CertificateFactory cf = CertificateFactory.getInstance("X.509");
347 X509Certificate crtp = (X509Certificate) cf.generateCertificate(is);
348 BigInteger serial = crtp.getSerialNumber();
349 updateMail.setString(1, crt.getPath());
350 updateMail.setString(2, serial.toString(16));
351 updateMail.setInt(3, id);
352 updateMail.execute();
354 finishJob.setInt(1, rs.getInt("jobid"));
356 System.out.println("signed: " + id);
360 } catch (GeneralSecurityException e) {
362 } catch (IOException e) {
364 } catch (ParseException e) {
367 System.out.println("Error with: " + id);
368 warnMail.setInt(1, rs.getInt("jobid"));
375 private static PrivateKey loadOpensslKey(File f) throws FileNotFoundException, IOException, InvalidKeySpecException, NoSuchAlgorithmException {
376 byte[] p8b = PEM.decode("RSA PRIVATE KEY", new String(IOUtils.readURL(new FileInputStream(f))));
377 DerOutputStream dos = new DerOutputStream();
379 new AlgorithmId(new ObjectIdentifier(new int[] {
380 1, 2, 840, 113549, 1, 1, 1
382 dos.putOctetString(p8b);
383 byte[] ctx = dos.toByteArray();
385 dos.write(DerValue.tag_Sequence, ctx);
386 PKCS8EncodedKeySpec p8 = new PKCS8EncodedKeySpec(dos.toByteArray());
387 PrivateKey i = KeyFactory.getInstance("RSA").generatePrivate(p8);
391 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 {
392 File f = Paths.get("signer", "serial").toFile();
394 FileOutputStream fos = new FileOutputStream(f);
395 fos.write("1".getBytes());
398 try (FileInputStream fr = new FileInputStream(f)) {
399 byte[] serial = IOUtils.readURL(fr);
400 BigInteger ser = new BigInteger(new String(serial).trim());
401 ser = ser.add(BigInteger.ONE);
403 PrintWriter pw = new PrintWriter(f);
406 if (digest != Digest.SHA256 && digest != Digest.SHA512) {
407 System.err.println("assuming sha256 either way ;-): " + digest);
408 digest = Digest.SHA256;
410 ObjectIdentifier sha512withrsa = new ObjectIdentifier(new int[] {
411 1, 2, 840, 113549, 1, 1, digest == Digest.SHA256 ? 11 : 13
413 AlgorithmId aid = new AlgorithmId(sha512withrsa);
414 Signature s = Signature.getInstance(digest == Digest.SHA256 ? "SHA256withRSA" : "SHA512withRSA");
416 DerOutputStream cert = new DerOutputStream();
417 DerOutputStream content = new DerOutputStream();
419 DerOutputStream version = new DerOutputStream();
420 version.putInteger(2); // v3
421 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 0), version);
423 content.putInteger(ser); // Serial
427 content.write(issuer.getEncoded());
430 DerOutputStream notAround = new DerOutputStream();
431 notAround.putUTCTime(fromDate);
432 notAround.putUTCTime(toDate);
433 content.write(DerValue.tag_Sequence, notAround);
437 X500Name xn = genX500Name(subj);
438 content.write(xn.getEncoded());
441 content.write(pk.getEncoded());
444 DerOutputStream extensions = new DerOutputStream();
446 addExtension(extensions, new ObjectIdentifier(new int[] {
448 }), generateSAN(altnames));
449 addExtension(extensions, new ObjectIdentifier(new int[] {
452 addExtension(extensions, new ObjectIdentifier(new int[] {
454 }), generateEKU(eku));
456 DerOutputStream extensionsSeq = new DerOutputStream();
457 extensionsSeq.write(DerValue.tag_Sequence, extensions);
458 content.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte) 3), extensionsSeq);
461 DerOutputStream contentSeq = new DerOutputStream();
463 contentSeq.write(DerValue.tag_Sequence, content.toByteArray());
466 s.update(contentSeq.toByteArray());
468 aid.encode(contentSeq);
469 contentSeq.putBitString(s.sign());
470 cert.write(DerValue.tag_Sequence, contentSeq);
472 X509Certificate c = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(cert.toByteArray()));
473 // c.verify(pk); only for self-signeds
475 return cert.toByteArray();
480 private static byte[] generateKU() throws IOException {
481 DerOutputStream dos = new DerOutputStream();
482 dos.putBitString(new byte[] {
485 return dos.toByteArray();
488 private static byte[] generateEKU(String eku) throws IOException {
490 DerOutputStream dos = new DerOutputStream();
491 for (String name : eku.split(",")) {
492 ObjectIdentifier oid;
495 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.1");
498 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.2");
501 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.3");
503 case "emailProtection":
504 oid = new ObjectIdentifier("1.3.6.1.5.5.7.3.4");
508 throw new Error(name);
512 byte[] data = dos.toByteArray();
514 dos.write(DerValue.tag_Sequence, data);
515 return dos.toByteArray();
518 private 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
555 throw new Error("unknown RDN-type: " + key);
557 RDN rdn = new RDN(new AVA(new ObjectIdentifier(oid), new DerValue(dos.toByteArray())));
561 private static void addExtension(DerOutputStream extensions, ObjectIdentifier oid, byte[] extContent) throws IOException {
562 DerOutputStream SANs = new DerOutputStream();
564 SANs.putOctetString(extContent);
566 extensions.write(DerValue.tag_Sequence, SANs);
569 private static byte[] generateSAN(List<SubjectAlternateName> altnames) throws IOException {
570 DerOutputStream SANContent = new DerOutputStream();
571 for (SubjectAlternateName san : altnames) {
573 if (san.getType() == SANType.DNS) {
574 type = (byte) GeneralNameInterface.NAME_DNS;
575 } else if (san.getType() == SANType.EMAIL) {
576 type = (byte) GeneralNameInterface.NAME_RFC822;
578 throw new Error("" + san.getType());
580 SANContent.write(DerValue.createTag(DerValue.TAG_CONTEXT, false, type), san.getName().getBytes());
582 DerOutputStream SANSeqContent = new DerOutputStream();
583 SANSeqContent.write(DerValue.tag_Sequence, SANContent);
584 byte[] byteArray = SANSeqContent.toByteArray();