1 package org.cacert.gigi.util;
3 import java.io.BufferedReader;
5 import java.io.FileInputStream;
6 import java.io.FileReader;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.InputStreamReader;
10 import java.io.PrintWriter;
11 import java.math.BigInteger;
12 import java.security.GeneralSecurityException;
13 import java.security.cert.CertificateFactory;
14 import java.security.cert.X509Certificate;
15 import java.sql.SQLException;
16 import java.sql.Timestamp;
17 import java.text.ParseException;
18 import java.text.SimpleDateFormat;
19 import java.util.Calendar;
20 import java.util.Date;
21 import java.util.HashMap;
22 import java.util.Properties;
23 import java.util.TimeZone;
25 import org.cacert.gigi.database.DatabaseConnection;
26 import org.cacert.gigi.database.GigiPreparedStatement;
27 import org.cacert.gigi.database.GigiResultSet;
28 import org.cacert.gigi.dbObjects.Certificate;
29 import org.cacert.gigi.dbObjects.Certificate.CSRType;
30 import org.cacert.gigi.output.DateSelector;
32 public class SimpleSigner {
34 private static GigiPreparedStatement warnMail;
36 private static GigiPreparedStatement updateMail;
38 private static GigiPreparedStatement readyCerts;
40 private static GigiPreparedStatement getSANSs;
42 private static GigiPreparedStatement revoke;
44 private static GigiPreparedStatement revokeCompleted;
46 private static GigiPreparedStatement finishJob;
48 private static boolean running = true;
50 private static Thread runner;
52 private static SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss'Z'");
55 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
56 sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
59 public static void main(String[] args) throws IOException, SQLException, InterruptedException {
60 Properties p = new Properties();
61 p.load(new FileReader("config/gigi.properties"));
62 DatabaseConnection.init(p);
67 public synchronized static void stopSigner() throws InterruptedException {
69 throw new IllegalStateException("already stopped");
77 public synchronized static void runSigner() throws SQLException, IOException, InterruptedException {
79 throw new IllegalStateException("already running");
82 readyCerts = DatabaseConnection.getInstance().prepare("SELECT certs.id AS id, certs.csr_name, jobs.id AS jobid, csr_type, md, keyUsage, extendedKeyUsage, executeFrom, executeTo, rootcert FROM jobs " + //
83 "INNER JOIN certs ON certs.id=jobs.targetId " + //
84 "INNER JOIN profiles ON profiles.id=certs.profile " + //
85 "WHERE jobs.state='open' "//
88 getSANSs = DatabaseConnection.getInstance().prepare("SELECT contents, type FROM subjectAlternativeNames " + //
91 updateMail = DatabaseConnection.getInstance().prepare("UPDATE certs SET crt_name=?," + " created=NOW(), serial=? WHERE id=?");
92 warnMail = DatabaseConnection.getInstance().prepare("UPDATE jobs SET warning=warning+1, state=IF(warning<3, 'open','error') WHERE id=?");
94 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'");
95 revokeCompleted = DatabaseConnection.getInstance().prepare("UPDATE certs SET revoked=NOW() WHERE id=?");
97 finishJob = DatabaseConnection.getInstance().prepare("UPDATE jobs SET state='done' WHERE id=?");
99 runner = new Thread() {
110 private static void work() {
113 } catch (IOException e2) {
114 e2.printStackTrace();
115 } catch (InterruptedException e2) {
116 e2.printStackTrace();
121 revokeCertificates();
123 } catch (IOException e) {
125 } catch (SQLException e) {
127 } catch (InterruptedException e1) {
132 private static void revokeCertificates() throws SQLException, IOException, InterruptedException {
133 GigiResultSet rs = revoke.executeQuery();
134 boolean worked = false;
136 int id = rs.getInt(1);
137 File crt = KeyStorage.locateCrt(id);
138 String[] call = new String[] {
141 "../unassured.crt",//
143 "../unassured.key",//
145 "../../" + crt.getPath(),//
151 Process p1 = Runtime.getRuntime().exec(call, null, new File("keys/unassured.ca"));
152 System.out.println("revoking: " + crt.getPath());
153 if (p1.waitFor() == 0) {
155 revokeCompleted.setInt(1, id);
156 revokeCompleted.execute();
157 finishJob.setInt(1, rs.getInt(3));
160 System.out.println("Failed");
168 private static void gencrl() throws IOException, InterruptedException {
169 String[] call = new String[] {
172 "../unassured.crt",//
174 "../unassured.key",//
179 "../unassured.crl",//
184 Process p1 = Runtime.getRuntime().exec(call, null, new File("keys/unassured.ca"));
185 if (p1.waitFor() != 0) {
186 System.out.println("Error while generating crl.");
190 private static int counter = 0;
192 private static void signCertificates() throws SQLException {
193 GigiResultSet rs = readyCerts.executeQuery();
195 Calendar c = Calendar.getInstance();
196 c.setTimeZone(TimeZone.getTimeZone("UTC"));
199 String csrname = rs.getString("csr_name");
200 int id = rs.getInt("id");
201 System.out.println("sign: " + csrname);
203 String csrType = rs.getString("csr_type");
204 CSRType ct = CSRType.valueOf(csrType);
205 File crt = KeyStorage.locateCrt(id);
207 String keyUsage = rs.getString("keyUsage");
208 String ekeyUsage = rs.getString("extendedKeyUsage");
210 Timestamp from = rs.getTimestamp("executeFrom");
211 String length = rs.getString("executeTo");
215 fromDate = new Date(System.currentTimeMillis());
217 fromDate = new Date(from.getTime());
219 if (length.endsWith("m") || length.endsWith("y")) {
220 String num = length.substring(0, length.length() - 1);
221 int inter = Integer.parseInt(num);
223 if (length.endsWith("m")) {
224 c.add(Calendar.MONTH, inter);
226 c.add(Calendar.YEAR, inter);
228 toDate = c.getTime();
230 toDate = DateSelector.getDateFormat().parse(length);
233 getSANSs.setInt(1, id);
234 GigiResultSet san = getSANSs.executeQuery();
236 File f = new File("keys", "SANFile" + System.currentTimeMillis() + (counter++) + ".cfg");
237 PrintWriter cfg = new PrintWriter(f);
238 boolean first = true;
243 cfg.print("subjectAltName=");
246 cfg.print(san.getString("type"));
248 cfg.print(san.getString("contents"));
251 cfg.println("keyUsage=critical," + keyUsage);
252 cfg.println("extendedKeyUsage=critical," + ekeyUsage);
255 int rootcert = rs.getInt("rootcert");
256 String ca = "unassured";
259 } else if (rootcert == 1) {
262 HashMap<String, String> subj = new HashMap<>();
263 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT name, value FROM certAvas WHERE certId=?");
264 ps.setInt(1, rs.getInt("id"));
265 GigiResultSet rs2 = ps.executeQuery();
267 subj.put(rs2.getString("name"), rs2.getString("value"));
269 if (subj.size() == 0) {
270 subj.put("CN", "<empty>");
271 System.out.println("WARNING: DN was empty");
273 String[] call = new String[] {
276 "../../" + csrname,//
278 "../" + ca + ".crt",//
280 "../" + ca + ".key",//
282 "../../" + crt.getPath(),//
285 sdf.format(fromDate),//
287 sdf.format(toDate),//
290 rs.getString("md"),//
292 "../" + f.getName(),//
295 Certificate.stringifyDN(subj),//
297 "../selfsign.config"//
300 if (ct == CSRType.SPKAC) {
303 Process p1 = Runtime.getRuntime().exec(call, null, new File("keys/unassured.ca"));
305 int waitFor = p1.waitFor();
308 try (InputStream is = new FileInputStream(crt)) {
309 CertificateFactory cf = CertificateFactory.getInstance("X.509");
310 X509Certificate crtp = (X509Certificate) cf.generateCertificate(is);
311 BigInteger serial = crtp.getSerialNumber();
312 updateMail.setString(1, crt.getPath());
313 updateMail.setString(2, serial.toString(16));
314 updateMail.setInt(3, id);
315 updateMail.execute();
317 finishJob.setInt(1, rs.getInt("jobid"));
319 System.out.println("signed: " + id);
323 BufferedReader br = new BufferedReader(new InputStreamReader(p1.getErrorStream()));
325 while ((s = br.readLine()) != null) {
326 System.out.println(s);
329 } catch (GeneralSecurityException e) {
331 } catch (IOException e) {
333 } catch (ParseException e) {
335 } catch (InterruptedException e1) {
336 e1.printStackTrace();
338 System.out.println("Error with: " + id);
339 warnMail.setInt(1, rs.getInt("jobid"));