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