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