]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/Certificate.java
37ba66b743b5737829b7923b375afc65a7a2d375
[gigi.git] / src / org / cacert / gigi / dbObjects / Certificate.java
1 package org.cacert.gigi.dbObjects;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.security.GeneralSecurityException;
9 import java.security.cert.CertificateFactory;
10 import java.security.cert.X509Certificate;
11 import java.sql.Date;
12 import java.util.Arrays;
13 import java.util.Collections;
14 import java.util.HashMap;
15 import java.util.LinkedList;
16 import java.util.List;
17 import java.util.Map.Entry;
18
19 import org.cacert.gigi.GigiApiException;
20 import org.cacert.gigi.database.GigiPreparedStatement;
21 import org.cacert.gigi.database.GigiResultSet;
22 import org.cacert.gigi.output.template.Outputable;
23 import org.cacert.gigi.output.template.TranslateCommand;
24 import org.cacert.gigi.util.KeyStorage;
25
26 public class Certificate implements IdCachable {
27
28     public enum SANType {
29         EMAIL("email"), DNS("DNS");
30
31         private final String opensslName;
32
33         private SANType(String opensslName) {
34             this.opensslName = opensslName;
35         }
36
37         public String getOpensslName() {
38             return opensslName;
39         }
40     }
41
42     public static class SubjectAlternateName implements Comparable<SubjectAlternateName> {
43
44         private SANType type;
45
46         private String name;
47
48         public SubjectAlternateName(SANType type, String name) {
49             this.type = type;
50             this.name = name;
51         }
52
53         public String getName() {
54             return name;
55         }
56
57         public SANType getType() {
58             return type;
59         }
60
61         @Override
62         public int compareTo(SubjectAlternateName o) {
63             int i = type.compareTo(o.type);
64             if (i != 0) {
65                 return i;
66             }
67             return name.compareTo(o.name);
68         }
69
70         @Override
71         public int hashCode() {
72             final int prime = 31;
73             int result = 1;
74             result = prime * result + ((name == null) ? 0 : name.hashCode());
75             result = prime * result + ((type == null) ? 0 : type.hashCode());
76             return result;
77         }
78
79         @Override
80         public boolean equals(Object obj) {
81             if (this == obj) {
82                 return true;
83             }
84             if (obj == null) {
85                 return false;
86             }
87             if (getClass() != obj.getClass()) {
88                 return false;
89             }
90             SubjectAlternateName other = (SubjectAlternateName) obj;
91             if (name == null) {
92                 if (other.name != null) {
93                     return false;
94                 }
95             } else if ( !name.equals(other.name)) {
96                 return false;
97             }
98             if (type != other.type) {
99                 return false;
100             }
101             return true;
102         }
103
104     }
105
106     public enum CSRType {
107         CSR, SPKAC;
108     }
109
110     private int id;
111
112     private CertificateOwner owner;
113
114     private String serial;
115
116     private Digest md;
117
118     private String csrName;
119
120     private String crtName;
121
122     private String csr = null;
123
124     private CSRType csrType;
125
126     private List<SubjectAlternateName> sans;
127
128     private CertificateProfile profile;
129
130     private HashMap<String, String> dn;
131
132     private String dnString;
133
134     private CACertificate ca;
135
136     public Certificate(CertificateOwner owner, User actor, HashMap<String, String> dn, Digest md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException, IOException {
137         if ( !profile.canBeIssuedBy(owner, actor)) {
138             throw new GigiApiException("You are not allowed to issue these certificates.");
139         }
140         this.owner = owner;
141         this.dn = dn;
142         if (dn.size() == 0) {
143             throw new GigiApiException("DN must not be empty.");
144         }
145         dnString = stringifyDN(dn);
146         this.md = md;
147         this.csr = csr;
148         this.csrType = csrType;
149         this.profile = profile;
150         this.sans = Arrays.asList(sans);
151         synchronized (Certificate.class) {
152
153             try (GigiPreparedStatement inserter = new GigiPreparedStatement("INSERT INTO certs SET md=?::`mdType`, csr_type=?::`csrType`, crt_name='', memid=?, profile=?")) {
154                 inserter.setString(1, md.toString().toLowerCase());
155                 inserter.setString(2, this.csrType.toString());
156                 inserter.setInt(3, owner.getId());
157                 inserter.setInt(4, profile.getId());
158                 inserter.execute();
159                 id = inserter.lastInsertId();
160             }
161
162             try (GigiPreparedStatement san = new GigiPreparedStatement("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`")) {
163                 for (SubjectAlternateName subjectAlternateName : sans) {
164                     san.setInt(1, id);
165                     san.setString(2, subjectAlternateName.getName());
166                     san.setString(3, subjectAlternateName.getType().getOpensslName());
167                     san.execute();
168                 }
169             }
170
171             try (GigiPreparedStatement insertAVA = new GigiPreparedStatement("INSERT INTO `certAvas` SET `certId`=?, name=?, value=?")) {
172                 insertAVA.setInt(1, id);
173                 for (Entry<String, String> e : this.dn.entrySet()) {
174                     insertAVA.setString(2, e.getKey());
175                     insertAVA.setString(3, e.getValue());
176                     insertAVA.execute();
177                 }
178             }
179             File csrFile = KeyStorage.locateCsr(id);
180             csrName = csrFile.getPath();
181             try (FileOutputStream fos = new FileOutputStream(csrFile)) {
182                 fos.write(this.csr.getBytes("UTF-8"));
183             }
184             try (GigiPreparedStatement updater = new GigiPreparedStatement("UPDATE `certs` SET `csr_name`=? WHERE id=?")) {
185                 updater.setString(1, csrName);
186                 updater.setInt(2, id);
187                 updater.execute();
188             }
189
190             cache.put(this);
191         }
192     }
193
194     private Certificate(GigiResultSet rs) {
195         this.id = rs.getInt("id");
196         dnString = rs.getString("subject");
197         md = Digest.valueOf(rs.getString("md").toUpperCase());
198         csrName = rs.getString("csr_name");
199         crtName = rs.getString("crt_name");
200         owner = CertificateOwner.getById(rs.getInt("memid"));
201         profile = CertificateProfile.getById(rs.getInt("profile"));
202         this.serial = rs.getString("serial");
203
204         try (GigiPreparedStatement ps2 = new GigiPreparedStatement("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?")) {
205             ps2.setInt(1, id);
206             GigiResultSet rs2 = ps2.executeQuery();
207             sans = new LinkedList<>();
208             while (rs2.next()) {
209                 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
210             }
211         }
212     }
213
214     public enum CertificateStatus {
215         /**
216          * This certificate is not in the database, has no id and only exists as
217          * this java object.
218          */
219         DRAFT("draft"),
220         /**
221          * The certificate has been signed. It is stored in the database.
222          * {@link Certificate#cert()} is valid.
223          */
224         ISSUED("issued"),
225
226         /**
227          * The certificate has been revoked.
228          */
229         REVOKED("revoked"),
230
231         /**
232          * If this certificate cannot be updated because an error happened in
233          * the signer.
234          */
235         ERROR("error");
236
237         private final Outputable name;
238
239         private CertificateStatus(String codename) {
240             this.name = new TranslateCommand(codename);
241
242         }
243
244         public Outputable getName() {
245             return name;
246         }
247
248     }
249
250     public synchronized CertificateStatus getStatus() {
251         try (GigiPreparedStatement searcher = new GigiPreparedStatement("SELECT crt_name, created, revoked, serial, caid FROM certs WHERE id=?")) {
252             searcher.setInt(1, id);
253             GigiResultSet rs = searcher.executeQuery();
254             if ( !rs.next()) {
255                 throw new IllegalStateException("Certificate not in Database");
256             }
257
258             crtName = rs.getString(1);
259             serial = rs.getString(4);
260             if (rs.getTimestamp(2) == null) {
261                 return CertificateStatus.DRAFT;
262             }
263             ca = CACertificate.getById(rs.getInt("caid"));
264             if (rs.getTimestamp(2) != null && rs.getTimestamp(3) == null) {
265                 return CertificateStatus.ISSUED;
266             }
267             return CertificateStatus.REVOKED;
268         }
269     }
270
271     /**
272      * @param start
273      *            the date from which on the certificate should be valid. (or
274      *            null if it should be valid instantly)
275      * @param period
276      *            the period for which the date should be valid. (a
277      *            <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
278      *            months)
279      * @return A job which can be used to monitor the progress of this task.
280      * @throws IOException
281      *             for problems with writing the CSR/SPKAC
282      * @throws GigiApiException
283      *             if the period is bogus
284      */
285     public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
286         if (getStatus() != CertificateStatus.DRAFT) {
287             throw new IllegalStateException();
288         }
289
290         return Job.sign(this, start, period);
291
292     }
293
294     public Job revoke() {
295         if (getStatus() != CertificateStatus.ISSUED) {
296             throw new IllegalStateException();
297         }
298         return Job.revoke(this);
299
300     }
301
302     public CACertificate getParent() {
303         CertificateStatus status = getStatus();
304         if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
305             throw new IllegalStateException(status + " is not wanted here.");
306         }
307         return ca;
308     }
309
310     public X509Certificate cert() throws IOException, GeneralSecurityException {
311         CertificateStatus status = getStatus();
312         if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
313             throw new IllegalStateException(status + " is not wanted here.");
314         }
315         InputStream is = null;
316         X509Certificate crt = null;
317         try {
318             is = new FileInputStream(crtName);
319             CertificateFactory cf = CertificateFactory.getInstance("X.509");
320             crt = (X509Certificate) cf.generateCertificate(is);
321         } finally {
322             if (is != null) {
323                 is.close();
324             }
325         }
326         return crt;
327     }
328
329     public Certificate renew() {
330         return null;
331     }
332
333     public int getId() {
334         return id;
335     }
336
337     public String getSerial() {
338         getStatus();
339         // poll changes
340         return serial;
341     }
342
343     public String getDistinguishedName() {
344         return dnString;
345     }
346
347     public Digest getMessageDigest() {
348         return md;
349     }
350
351     public CertificateOwner getOwner() {
352         return owner;
353     }
354
355     public List<SubjectAlternateName> getSANs() {
356         return Collections.unmodifiableList(sans);
357     }
358
359     public CertificateProfile getProfile() {
360         return profile;
361     }
362
363     public synchronized static Certificate getBySerial(String serial) {
364         if (serial == null || "".equals(serial)) {
365             return null;
366         }
367         String concat = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
368         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT certs.id, " + concat + " as `subject`, `md`, `csr_name`, `crt_name`,`memid`, `profile`, `certs`.`serial` FROM `certs` LEFT JOIN `certAvas` ON `certAvas`.`certId`=`certs`.`id` WHERE `serial`=? GROUP BY `certs`.`id`")) {
369             ps.setString(1, serial);
370             GigiResultSet rs = ps.executeQuery();
371             if ( !rs.next()) {
372                 return null;
373             }
374             int id = rs.getInt(1);
375             Certificate c1 = cache.get(id);
376             if (c1 != null) {
377                 return c1;
378             }
379             Certificate certificate = new Certificate(rs);
380             cache.put(certificate);
381             return certificate;
382         }
383     }
384
385     private static ObjectCache<Certificate> cache = new ObjectCache<>();
386
387     public synchronized static Certificate getById(int id) {
388         Certificate cacheRes = cache.get(id);
389         if (cacheRes != null) {
390             return cacheRes;
391         }
392
393         try {
394             String concat = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
395             try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT certs.id, " + concat + " as subject, md, csr_name, crt_name,memid, profile, certs.serial FROM `certs` LEFT JOIN `certAvas` ON `certAvas`.`certId`=certs.id WHERE certs.id=? GROUP BY certs.id")) {
396                 ps.setInt(1, id);
397                 GigiResultSet rs = ps.executeQuery();
398                 if ( !rs.next()) {
399                     return null;
400                 }
401
402                 Certificate c = new Certificate(rs);
403                 cache.put(c);
404                 return c;
405             }
406         } catch (IllegalArgumentException e) {
407
408         }
409         return null;
410     }
411
412     public static String escapeAVA(String value) {
413
414         return value.replace("\\", "\\\\").replace("/", "\\/");
415     }
416
417     public static String stringifyDN(HashMap<String, String> contents) {
418         StringBuffer res = new StringBuffer();
419         for (Entry<String, String> i : contents.entrySet()) {
420             res.append("/" + i.getKey() + "=");
421             res.append(escapeAVA(i.getValue()));
422         }
423         return res.toString();
424     }
425
426     public static HashMap<String, String> buildDN(String... contents) {
427         HashMap<String, String> res = new HashMap<>();
428         for (int i = 0; i + 1 < contents.length; i += 2) {
429             res.put(contents[i], contents[i + 1]);
430         }
431         return res;
432     }
433
434     public java.util.Date getRevocationDate() {
435         if (getStatus() == CertificateStatus.REVOKED) {
436             try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT revoked FROM certs WHERE id=?")) {
437                 prep.setInt(1, getId());
438                 GigiResultSet res = prep.executeQuery();
439                 if (res.next()) {
440                     return new java.util.Date(res.getDate("revoked").getTime());
441                 }
442             }
443         }
444         return null;
445     }
446
447     public void setLoginEnabled(boolean activate) {
448         if (activate) {
449             if ( !isLoginEnabled()) {
450                 try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `logincerts` SET `id`=?")) {
451                     prep.setInt(1, id);
452                     prep.execute();
453                 }
454             }
455         } else {
456             try (GigiPreparedStatement prep = new GigiPreparedStatement("DELETE FROM `logincerts` WHERE `id`=?")) {
457                 prep.setInt(1, id);
458                 prep.execute();
459             }
460         }
461     }
462
463     public boolean isLoginEnabled() {
464         try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT 1 FROM `logincerts` WHERE `id`=?")) {
465             prep.setInt(1, id);
466             GigiResultSet res = prep.executeQuery();
467             return res.next();
468         }
469     }
470 }