1 package club.wpia.gigi.dbObjects;
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;
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;
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;
27 public class Certificate implements IdCachable {
29 public enum RevocationType implements DBEnum {
30 USER("user"), SUPPORT("support"), PING_TIMEOUT("ping_timeout"), KEY_COMPROMISE("key_compromise");
32 private final String dbName;
34 private RevocationType(String dbName) {
39 public String getDBName() {
43 public static RevocationType fromString(String s) {
44 return valueOf(s.toUpperCase(Locale.ENGLISH));
48 public enum AttachmentType implements DBEnum {
52 public String getDBName() {
57 public enum SANType implements DBEnum {
58 EMAIL("email"), DNS("DNS");
60 private final String opensslName;
62 private SANType(String opensslName) {
63 this.opensslName = opensslName;
66 public String getOpensslName() {
71 public String getDBName() {
76 public static class SubjectAlternateName implements Comparable<SubjectAlternateName> {
82 public SubjectAlternateName(SANType type, String name) {
87 public String getName() {
91 public SANType getType() {
96 public int compareTo(SubjectAlternateName o) {
97 int i = type.compareTo(o.type);
101 return name.compareTo(o.name);
105 public int hashCode() {
106 final int prime = 31;
108 result = prime * result + ((name == null) ? 0 : name.hashCode());
109 result = prime * result + ((type == null) ? 0 : type.hashCode());
114 public boolean equals(Object obj) {
121 if (getClass() != obj.getClass()) {
124 SubjectAlternateName other = (SubjectAlternateName) obj;
126 if (other.name != null) {
129 } else if ( !name.equals(other.name)) {
132 if (type != other.type) {
140 public enum CSRType {
146 private CertificateOwner owner;
148 private String serial;
152 private String csr = null;
154 private CSRType csrType;
156 private List<SubjectAlternateName> sans;
158 private CertificateProfile profile;
160 private HashMap<String, String> dn;
162 private String dnString;
164 private CACertificate ca;
166 private String description = "";
168 public static final TranslateCommand NOT_LOADED = new TranslateCommand("Certificate could not be loaded");
170 public static final TranslateCommand NOT_PARSED = new TranslateCommand("Certificate could not be parsed");
173 * Creates a new Certificate. WARNING: this is an internal API. Creating
174 * certificates for users must be done using the {@link CertificateRequest}
178 * the owner for whom the certificate should be created.
180 * the acting user that creates the certificate
182 * the distinguished name of the subject of this certificate (as
183 * Map using OpenSSL-Style keys)
185 * the {@link Digest} to sign the certificate with
187 * the CSR/SPKAC-Request containing the public key in question
189 * the type of the csr parameter
191 * the profile under which this certificate is to be issued
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.
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.");
205 if (dn.size() == 0) {
206 throw new GigiApiException("DN must not be empty.");
208 dnString = stringifyDN(dn);
211 this.csrType = csrType;
212 this.profile = profile;
213 this.sans = Arrays.asList(sans);
214 synchronized (Certificate.class) {
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());
222 id = inserter.lastInsertId();
225 try (GigiPreparedStatement san = new GigiPreparedStatement("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`")) {
226 for (SubjectAlternateName subjectAlternateName : sans) {
228 san.setString(2, subjectAlternateName.getName());
229 san.setString(3, subjectAlternateName.getType().getOpensslName());
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());
242 addAttachment(AttachmentType.CSR, csr);
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");
256 try (GigiPreparedStatement ps2 = new GigiPreparedStatement("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?")) {
258 GigiResultSet rs2 = ps2.executeQuery();
259 sans = new LinkedList<>();
261 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
266 public enum CertificateStatus {
268 * This certificate is not in the database, has no id and only exists as
273 * The certificate has been signed. It is stored in the database.
274 * {@link Certificate#cert()} is valid.
279 * The certificate has been revoked.
284 * If this certificate cannot be updated because an error happened in
289 private final Outputable name;
291 private CertificateStatus(String codename) {
292 this.name = new TranslateCommand(codename);
296 public Outputable getName() {
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();
307 throw new IllegalStateException("Certificate not in Database");
310 serial = rs.getString(3);
311 if (rs.getTimestamp(1) == null) {
312 return CertificateStatus.DRAFT;
314 ca = CACertificate.getById(rs.getInt("caid"));
315 if (rs.getTimestamp(1) != null && rs.getTimestamp(2) == null) {
316 return CertificateStatus.ISSUED;
318 return CertificateStatus.REVOKED;
324 * the date from which on the certificate should be valid. (or
325 * null if it should be valid instantly)
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
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
336 public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
337 if (getStatus() != CertificateStatus.DRAFT) {
338 throw new IllegalStateException();
341 return Job.sign(this, start, period);
345 public Job revoke(RevocationType type) {
346 if (getStatus() != CertificateStatus.ISSUED) {
347 throw new IllegalStateException();
349 return Job.revoke(this, type);
352 public Job revoke(String challenge, String signature, String message) {
353 if (getStatus() != CertificateStatus.ISSUED) {
354 throw new IllegalStateException();
356 return Job.revoke(this, challenge, signature, message);
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.");
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.");
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);
379 public Certificate renew() {
387 public String getSerial() {
393 public String getDistinguishedName() {
397 public Digest getMessageDigest() {
401 public CertificateOwner getOwner() {
405 public List<SubjectAlternateName> getSANs() {
406 return Collections.unmodifiableList(sans);
409 public CertificateProfile getProfile() {
413 private static final String CONCAT = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
415 public synchronized static Certificate getBySerial(String serial) {
416 if (serial == null || "".equals(serial)) {
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();
425 int id = rs.getInt(1);
426 Certificate c1 = cache.get(id);
430 Certificate certificate = new Certificate(rs);
431 cache.put(certificate);
436 private static ObjectCache<Certificate> cache = new ObjectCache<>();
438 public synchronized static Certificate getById(int id) {
439 Certificate cacheRes = cache.get(id);
440 if (cacheRes != null) {
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")) {
447 GigiResultSet rs = ps.executeQuery();
452 Certificate c = new Certificate(rs);
456 } catch (IllegalArgumentException e) {
462 public static String escapeAVA(String value) {
464 return value.replace("\\", "\\\\").replace("/", "\\/");
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()));
473 return res.toString();
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]);
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();
490 return new java.util.Date(res.getTimestamp("revoked").getTime());
497 public void setLoginEnabled(boolean activate) {
499 if ( !isLoginEnabled()) {
500 try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `logincerts` SET `id`=?")) {
506 try (GigiPreparedStatement prep = new GigiPreparedStatement("DELETE FROM `logincerts` WHERE `id`=?")) {
513 public boolean isLoginEnabled() {
514 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT 1 FROM `logincerts` WHERE `id`=?")) {
516 GigiResultSet res = prep.executeQuery();
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);
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);
536 private static Certificate[] fetchCertsToArray(GigiPreparedStatement prep) {
537 GigiResultSet res = prep.executeQuery();
539 Certificate[] certs = new Certificate[res.getRow()];
541 for (int i = 0; res.next(); i++) {
542 certs[i] = Certificate.getById(res.getInt(1));
547 public void addAttachment(AttachmentType tp, String data) throws GigiApiException {
548 if (getAttachment(tp) != null) {
549 throw new GigiApiException("Cannot override attachment");
552 throw new GigiApiException("Attachment must not be null");
554 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `certificateAttachment` SET `certid`=?, `type`=?::`certificateAttachmentType`, `content`=?")) {
555 ps.setInt(1, getId());
557 ps.setString(3, data);
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());
566 GigiResultSet rs = ps.executeQuery();
570 String s = rs.getString(1);
572 throw new GigiApiException("Invalid database state");
578 public void setDescription(String description) {
579 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `certs` SET `description`=? WHERE `id`=?")) {
580 ps.setString(1, description);
584 this.description = description;
587 public String getDescription() {
591 public static Certificate locateCertificate(String serial, String certData) throws GigiApiException {
592 Certificate c = null;
594 if (serial != null && !serial.isEmpty()) {
595 c = getBySerial(normalizeSerial(serial));
600 if (certData != null && !certData.isEmpty()) {
602 X509Certificate cert = null;
603 final byte[] supplied;
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);
613 c = getBySerial(c0.getSerialNumber().toString(16));
618 if ( !Arrays.equals(supplied, cert.getEncoded())) {
621 } catch (IOException e) {
622 throw new GigiApiException(NOT_LOADED);
623 } catch (GeneralSecurityException e) {
624 throw new GigiApiException(NOT_LOADED);
628 throw new GigiApiException("No information to identify the correct certificate was provided.");
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(":", "");
640 while (idx < serial.length() && serial.charAt(idx) == '0') {
643 serial = serial.substring(idx);
644 if ( !serial.matches("[0-9a-f]+")) {
645 throw new GigiApiException("Malformed serial");