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