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