]> WPIA git - gigi.git/blob - src/club/wpia/gigi/dbObjects/Certificate.java
Merge "fix: spelling"
[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     public static final TranslateCommand NOT_LOADED = new TranslateCommand("Certificate could not be loaded");
170
171     public static final TranslateCommand NOT_PARSED = new TranslateCommand("Certificate could not be parsed");
172
173     /**
174      * Creates a new Certificate. WARNING: this is an internal API. Creating
175      * certificates for users must be done using the {@link CertificateRequest}
176      * -API.
177      * 
178      * @param owner
179      *            the owner for whom the certificate should be created.
180      * @param actor
181      *            the acting user that creates the certificate
182      * @param dn
183      *            the distinguished name of the subject of this certificate (as
184      *            Map using OpenSSL-Style keys)
185      * @param md
186      *            the {@link Digest} to sign the certificate with
187      * @param csr
188      *            the CSR/SPKAC-Request containing the public key in question
189      * @param csrType
190      *            the type of the csr parameter
191      * @param profile
192      *            the profile under which this certificate is to be issued
193      * @param sans
194      *            additional subject alternative names
195      * @throws GigiApiException
196      *             in case the request is malformed or internal errors occur
197      * @throws IOException
198      *             when the request cannot be written.
199      */
200     public Certificate(CertificateOwner owner, User actor, HashMap<String, String> dn, Digest md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException, IOException {
201         if ( !profile.canBeIssuedBy(owner, actor)) {
202             throw new GigiApiException("You are not allowed to issue these certificates.");
203         }
204         this.owner = owner;
205         this.dn = dn;
206         if (dn.size() == 0) {
207             throw new GigiApiException("DN must not be empty.");
208         }
209         dnString = stringifyDN(dn);
210         this.md = md;
211         this.csr = csr;
212         this.csrType = csrType;
213         this.profile = profile;
214         this.sans = Arrays.asList(sans);
215         synchronized (Certificate.class) {
216
217             try (GigiPreparedStatement inserter = new GigiPreparedStatement("INSERT INTO certs SET md=?::`mdType`, csr_type=?::`csrType`, memid=?, profile=?")) {
218                 inserter.setString(1, md.toString().toLowerCase());
219                 inserter.setString(2, this.csrType.toString());
220                 inserter.setInt(3, owner.getId());
221                 inserter.setInt(4, profile.getId());
222                 inserter.execute();
223                 id = inserter.lastInsertId();
224             }
225
226             try (GigiPreparedStatement san = new GigiPreparedStatement("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`")) {
227                 for (SubjectAlternateName subjectAlternateName : sans) {
228                     san.setInt(1, id);
229                     san.setString(2, subjectAlternateName.getName());
230                     san.setString(3, subjectAlternateName.getType().getOpensslName());
231                     san.execute();
232                 }
233             }
234
235             try (GigiPreparedStatement insertAVA = new GigiPreparedStatement("INSERT INTO `certAvas` SET `certId`=?, name=?, value=?")) {
236                 insertAVA.setInt(1, id);
237                 for (Entry<String, String> e : this.dn.entrySet()) {
238                     insertAVA.setString(2, e.getKey());
239                     insertAVA.setString(3, e.getValue());
240                     insertAVA.execute();
241                 }
242             }
243             addAttachment(AttachmentType.CSR, csr);
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         owner = CertificateOwner.getById(rs.getInt("memid"));
253         profile = CertificateProfile.getById(rs.getInt("profile"));
254         this.serial = rs.getString("serial");
255         this.description = rs.getString("description");
256
257         try (GigiPreparedStatement ps2 = new GigiPreparedStatement("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?")) {
258             ps2.setInt(1, id);
259             GigiResultSet rs2 = ps2.executeQuery();
260             sans = new LinkedList<>();
261             while (rs2.next()) {
262                 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
263             }
264         }
265     }
266
267     public enum CertificateStatus {
268         /**
269          * This certificate is not in the database, has no id and only exists as
270          * this java object.
271          */
272         DRAFT("draft"),
273         /**
274          * The certificate has been signed. It is stored in the database.
275          * {@link Certificate#cert()} is valid.
276          */
277         ISSUED("issued"),
278
279         /**
280          * The certificate has been revoked.
281          */
282         REVOKED("revoked"),
283
284         /**
285          * If this certificate cannot be updated because an error happened in
286          * the signer.
287          */
288         ERROR("error");
289
290         private final Outputable name;
291
292         private CertificateStatus(String codename) {
293             this.name = new TranslateCommand(codename);
294
295         }
296
297         public Outputable getName() {
298             return name;
299         }
300
301     }
302
303     public synchronized CertificateStatus getStatus() {
304         try (GigiPreparedStatement searcher = new GigiPreparedStatement("SELECT created, revoked, serial, caid FROM certs WHERE id=?")) {
305             searcher.setInt(1, id);
306             GigiResultSet rs = searcher.executeQuery();
307             if ( !rs.next()) {
308                 throw new IllegalStateException("Certificate not in Database");
309             }
310
311             serial = rs.getString(3);
312             if (rs.getTimestamp(1) == null) {
313                 return CertificateStatus.DRAFT;
314             }
315             ca = CACertificate.getById(rs.getInt("caid"));
316             if (rs.getTimestamp(1) != null && rs.getTimestamp(2) == null) {
317                 return CertificateStatus.ISSUED;
318             }
319             return CertificateStatus.REVOKED;
320         }
321     }
322
323     /**
324      * @param start
325      *            the date from which on the certificate should be valid. (or
326      *            null if it should be valid instantly)
327      * @param period
328      *            the period for which the date should be valid. (a
329      *            <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
330      *            months)
331      * @return A job which can be used to monitor the progress of this task.
332      * @throws IOException
333      *             for problems with writing the CSR/SPKAC
334      * @throws GigiApiException
335      *             if the period is bogus
336      */
337     public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
338         if (getStatus() != CertificateStatus.DRAFT) {
339             throw new IllegalStateException();
340         }
341
342         return Job.sign(this, start, period);
343
344     }
345
346     public Job revoke(RevocationType type) {
347         if (getStatus() != CertificateStatus.ISSUED) {
348             throw new IllegalStateException();
349         }
350         return Job.revoke(this, type);
351     }
352
353     public Job revoke(String challenge, String signature, String message) {
354         if (getStatus() != CertificateStatus.ISSUED) {
355             throw new IllegalStateException();
356         }
357         return Job.revoke(this, challenge, signature, message);
358     }
359
360     public CACertificate getParent() {
361         CertificateStatus status = getStatus();
362         if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
363             throw new IllegalStateException(status + " is not wanted here.");
364         }
365         return ca;
366     }
367
368     public X509Certificate cert() throws IOException, GeneralSecurityException, GigiApiException {
369         CertificateStatus status = getStatus();
370         if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
371             throw new IllegalStateException(status + " is not wanted here.");
372         }
373         String crtS = getAttachment(AttachmentType.CRT);
374         try (ByteArrayInputStream bais = new ByteArrayInputStream(PEM.decode("CERTIFICATE", crtS))) {
375             CertificateFactory cf = CertificateFactory.getInstance("X.509");
376             return (X509Certificate) cf.generateCertificate(bais);
377         }
378     }
379
380     public Certificate renew() {
381         return null;
382     }
383
384     public int getId() {
385         return id;
386     }
387
388     public String getSerial() {
389         getStatus();
390         // poll changes
391         return serial;
392     }
393
394     public String getDistinguishedName() {
395         return dnString;
396     }
397
398     public Digest getMessageDigest() {
399         return md;
400     }
401
402     public CertificateOwner getOwner() {
403         return owner;
404     }
405
406     public List<SubjectAlternateName> getSANs() {
407         return Collections.unmodifiableList(sans);
408     }
409
410     public CertificateProfile getProfile() {
411         return profile;
412     }
413
414     private static final String CONCAT = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
415
416     public synchronized static Certificate getBySerial(BigInteger serial) {
417         if (serial == null) {
418             return null;
419         }
420         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT certs.id, " + CONCAT + " as `subject`, `md`,`memid`, `profile`, `certs`.`serial`, `certs`.`description` FROM `certs` LEFT JOIN `certAvas` ON `certAvas`.`certId`=`certs`.`id` WHERE `serial`=? GROUP BY `certs`.`id`")) {
421             ps.setString(1, serial.toString(16));
422             GigiResultSet rs = ps.executeQuery();
423             if ( !rs.next()) {
424                 return null;
425             }
426             int id = rs.getInt(1);
427             Certificate c1 = cache.get(id);
428             if (c1 != null) {
429                 return c1;
430             }
431             Certificate certificate = new Certificate(rs);
432             cache.put(certificate);
433             return certificate;
434         }
435     }
436
437     private static ObjectCache<Certificate> cache = new ObjectCache<>();
438
439     public synchronized static Certificate getById(int id) {
440         Certificate cacheRes = cache.get(id);
441         if (cacheRes != null) {
442             return cacheRes;
443         }
444
445         try {
446             try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT certs.id, " + CONCAT + " as subject, md, memid, profile, certs.serial, description FROM `certs` LEFT JOIN `certAvas` ON `certAvas`.`certId`=certs.id WHERE certs.id=? GROUP BY certs.id")) {
447                 ps.setInt(1, id);
448                 GigiResultSet rs = ps.executeQuery();
449                 if ( !rs.next()) {
450                     return null;
451                 }
452
453                 Certificate c = new Certificate(rs);
454                 cache.put(c);
455                 return c;
456             }
457         } catch (IllegalArgumentException e) {
458
459         }
460         return null;
461     }
462
463     public static String escapeAVA(String value) {
464
465         return value.replace("\\", "\\\\").replace("/", "\\/");
466     }
467
468     public static String stringifyDN(HashMap<String, String> contents) {
469         StringBuffer res = new StringBuffer();
470         for (Entry<String, String> i : contents.entrySet()) {
471             res.append("/" + i.getKey() + "=");
472             res.append(escapeAVA(i.getValue()));
473         }
474         return res.toString();
475     }
476
477     public static HashMap<String, String> buildDN(String... contents) {
478         HashMap<String, String> res = new HashMap<>();
479         for (int i = 0; i + 1 < contents.length; i += 2) {
480             res.put(contents[i], contents[i + 1]);
481         }
482         return res;
483     }
484
485     public java.util.Date getRevocationDate() {
486         if (getStatus() == CertificateStatus.REVOKED) {
487             try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT revoked FROM certs WHERE id=?")) {
488                 prep.setInt(1, getId());
489                 GigiResultSet res = prep.executeQuery();
490                 if (res.next()) {
491                     return new java.util.Date(res.getTimestamp("revoked").getTime());
492                 }
493             }
494         }
495         return null;
496     }
497
498     public void setLoginEnabled(boolean activate) {
499         if (activate) {
500             if ( !isLoginEnabled()) {
501                 try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `logincerts` SET `id`=?")) {
502                     prep.setInt(1, id);
503                     prep.execute();
504                 }
505             }
506         } else {
507             try (GigiPreparedStatement prep = new GigiPreparedStatement("DELETE FROM `logincerts` WHERE `id`=?")) {
508                 prep.setInt(1, id);
509                 prep.execute();
510             }
511         }
512     }
513
514     public boolean isLoginEnabled() {
515         try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT 1 FROM `logincerts` WHERE `id`=?")) {
516             prep.setInt(1, id);
517             GigiResultSet res = prep.executeQuery();
518             return res.next();
519         }
520     }
521
522     public static Certificate[] findBySerialPattern(String serial) {
523         try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `id` FROM `certs` WHERE `serial` LIKE ? GROUP BY `id`  LIMIT 100", true)) {
524             prep.setString(1, serial);
525             return fetchCertsToArray(prep);
526         }
527     }
528
529     public static Certificate[] findBySANPattern(String request, SANType type) {
530         try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `certId` FROM `subjectAlternativeNames` WHERE `contents` LIKE ? and `type`=?::`SANType` GROUP BY `certId` LIMIT 100", true)) {
531             prep.setString(1, request);
532             prep.setEnum(2, type);
533             return fetchCertsToArray(prep);
534         }
535     }
536
537     private static Certificate[] fetchCertsToArray(GigiPreparedStatement prep) {
538         GigiResultSet res = prep.executeQuery();
539         res.last();
540         Certificate[] certs = new Certificate[res.getRow()];
541         res.beforeFirst();
542         for (int i = 0; res.next(); i++) {
543             certs[i] = Certificate.getById(res.getInt(1));
544         }
545         return certs;
546     }
547
548     public void addAttachment(AttachmentType tp, String data) throws GigiApiException {
549         if (getAttachment(tp) != null) {
550             throw new GigiApiException("Cannot override attachment");
551         }
552         if (data == null) {
553             throw new GigiApiException("Attachment must not be null");
554         }
555         try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `certificateAttachment` SET `certid`=?, `type`=?::`certificateAttachmentType`, `content`=?")) {
556             ps.setInt(1, getId());
557             ps.setEnum(2, tp);
558             ps.setString(3, data);
559             ps.execute();
560         }
561     }
562
563     public String getAttachment(AttachmentType tp) throws GigiApiException {
564         try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `content` FROM `certificateAttachment` WHERE `certid`=? AND `type`=?::`certificateAttachmentType`")) {
565             ps.setInt(1, getId());
566             ps.setEnum(2, tp);
567             GigiResultSet rs = ps.executeQuery();
568             if ( !rs.next()) {
569                 return null;
570             }
571             String s = rs.getString(1);
572             if (rs.next()) {
573                 throw new GigiApiException("Invalid database state");
574             }
575             return s;
576         }
577     }
578
579     public void setDescription(String description) {
580         try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `certs` SET `description`=? WHERE `id`=?")) {
581             ps.setString(1, description);
582             ps.setInt(2, id);
583             ps.execute();
584         }
585         this.description = description;
586     }
587
588     public String getDescription() {
589         return description;
590     }
591
592     public static Certificate locateCertificate(String serial, String certData) throws GigiApiException {
593         if (serial != null && !serial.isEmpty()) {
594             return getBySerial(normalizeSerial(serial));
595         }
596
597         if (certData != null && !certData.isEmpty()) {
598             final byte[] supplied;
599             final X509Certificate c0;
600             try {
601                 supplied = PEM.decode("CERTIFICATE", certData);
602                 c0 = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(supplied));
603             } catch (IllegalArgumentException e1) {
604                 throw new GigiApiException(NOT_PARSED);
605             } catch (CertificateException e1) {
606                 throw new GigiApiException(NOT_PARSED);
607             }
608             try {
609                 Certificate c = getBySerial(c0.getSerialNumber());
610                 if (c == null) {
611                     return null;
612                 }
613                 X509Certificate cert = c.cert();
614                 if ( !Arrays.equals(supplied, cert.getEncoded())) {
615                     return null;
616                 }
617                 return c;
618             } catch (IOException e) {
619                 throw new GigiApiException(NOT_LOADED);
620             } catch (GeneralSecurityException e) {
621                 throw new GigiApiException(NOT_LOADED);
622             }
623         }
624         throw new GigiApiException("No information to identify the correct certificate was provided.");
625     }
626
627     public static BigInteger normalizeSerial(String serial) throws GigiApiException {
628         serial = serial.replace(" ", "");
629         serial = serial.toLowerCase();
630         if (serial.matches("[0-9a-f]{2}(:[0-9a-f]{2})*")) {
631             serial = serial.replace(":", "");
632         }
633         int idx = 0;
634         while (idx < serial.length() && serial.charAt(idx) == '0') {
635             idx++;
636         }
637         serial = serial.substring(idx);
638         if ( !serial.matches("[0-9a-f]+")) {
639             throw new GigiApiException("Malformed serial");
640         }
641         return new BigInteger(serial, 16);
642     }
643 }