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