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