1 package club.wpia.gigi.dbObjects;
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;
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;
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;
28 public class Certificate implements IdCachable {
30 public enum RevocationType implements DBEnum {
31 USER("user"), SUPPORT("support"), PING_TIMEOUT("ping_timeout"), KEY_COMPROMISE("key_compromise");
33 private final String dbName;
35 private RevocationType(String dbName) {
40 public String getDBName() {
44 public static RevocationType fromString(String s) {
45 return valueOf(s.toUpperCase(Locale.ENGLISH));
49 public enum AttachmentType implements DBEnum {
53 public String getDBName() {
58 public enum SANType implements DBEnum {
59 EMAIL("email"), DNS("DNS");
61 private final String opensslName;
63 private SANType(String opensslName) {
64 this.opensslName = opensslName;
67 public String getOpensslName() {
72 public String getDBName() {
77 public static class SubjectAlternateName implements Comparable<SubjectAlternateName> {
83 public SubjectAlternateName(SANType type, String name) {
88 public String getName() {
92 public SANType getType() {
97 public int compareTo(SubjectAlternateName o) {
98 int i = type.compareTo(o.type);
102 return name.compareTo(o.name);
106 public int hashCode() {
107 final int prime = 31;
109 result = prime * result + ((name == null) ? 0 : name.hashCode());
110 result = prime * result + ((type == null) ? 0 : type.hashCode());
115 public boolean equals(Object obj) {
122 if (getClass() != obj.getClass()) {
125 SubjectAlternateName other = (SubjectAlternateName) obj;
127 if (other.name != null) {
130 } else if ( !name.equals(other.name)) {
133 if (type != other.type) {
141 public enum CSRType {
147 private CertificateOwner owner;
149 private String serial;
153 private String csr = null;
155 private CSRType csrType;
157 private List<SubjectAlternateName> sans;
159 private CertificateProfile profile;
161 private HashMap<String, String> dn;
163 private String dnString;
165 private CACertificate ca;
167 private String description = "";
171 public static final TranslateCommand NOT_LOADED = new TranslateCommand("Certificate could not be loaded");
173 public static final TranslateCommand NOT_PARSED = new TranslateCommand("Certificate could not be parsed");
176 * Creates a new Certificate. WARNING: this is an internal API. Creating
177 * certificates for users must be done using the {@link CertificateRequest}
181 * the owner for whom the certificate should be created.
183 * the acting user that creates the certificate
185 * the distinguished name of the subject of this certificate (as
186 * Map using OpenSSL-Style keys)
188 * the {@link Digest} to sign the certificate with
190 * the CSR/SPKAC-Request containing the public key in question
192 * the type of the csr parameter
194 * the profile under which this certificate is to be issued
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.
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.");
208 if (dn.size() == 0) {
209 throw new GigiApiException("DN must not be empty.");
211 dnString = stringifyDN(dn);
214 this.csrType = csrType;
215 this.profile = profile;
216 this.sans = Arrays.asList(sans);
218 synchronized (Certificate.class) {
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());
227 id = inserter.lastInsertId();
230 try (GigiPreparedStatement san = new GigiPreparedStatement("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`")) {
231 for (SubjectAlternateName subjectAlternateName : sans) {
233 san.setString(2, subjectAlternateName.getName());
234 san.setString(3, subjectAlternateName.getType().getOpensslName());
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());
247 addAttachment(AttachmentType.CSR, csr);
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"));
262 try (GigiPreparedStatement ps2 = new GigiPreparedStatement("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?")) {
264 GigiResultSet rs2 = ps2.executeQuery();
265 sans = new LinkedList<>();
267 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
272 public enum CertificateStatus {
274 * This certificate is not in the database, has no id and only exists as
279 * The certificate has been signed. It is stored in the database.
280 * {@link Certificate#cert()} is valid.
285 * The certificate has been revoked.
290 * If this certificate cannot be updated because an error happened in
295 private final Outputable name;
297 private CertificateStatus(String codename) {
298 this.name = new TranslateCommand(codename);
302 public Outputable getName() {
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();
313 throw new IllegalStateException("Certificate not in Database");
316 serial = rs.getString(3);
317 if (rs.getTimestamp(1) == null) {
318 return CertificateStatus.DRAFT;
320 ca = CACertificate.getById(rs.getInt("caid"));
321 if (rs.getTimestamp(1) != null && rs.getTimestamp(2) == null) {
322 return CertificateStatus.ISSUED;
324 return CertificateStatus.REVOKED;
330 * the date from which on the certificate should be valid. (or
331 * null if it should be valid instantly)
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
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
342 public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
343 if (getStatus() != CertificateStatus.DRAFT) {
344 throw new IllegalStateException();
347 return Job.sign(this, start, period);
351 public Job revoke(RevocationType type) {
352 if (getStatus() != CertificateStatus.ISSUED) {
353 throw new IllegalStateException();
355 return Job.revoke(this, type);
358 public Job revoke(String challenge, String signature, String message) {
359 if (getStatus() != CertificateStatus.ISSUED) {
360 throw new IllegalStateException();
362 return Job.revoke(this, challenge, signature, message);
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.");
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.");
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);
385 public Certificate renew() {
393 public String getSerial() {
399 public String getDistinguishedName() {
403 public Digest getMessageDigest() {
407 public CertificateOwner getOwner() {
411 public List<SubjectAlternateName> getSANs() {
412 return Collections.unmodifiableList(sans);
415 public CertificateProfile getProfile() {
419 private static final String CONCAT = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
421 public synchronized static Certificate getBySerial(BigInteger serial) {
422 if (serial == null) {
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();
431 int id = rs.getInt(1);
432 Certificate c1 = cache.get(id);
436 Certificate certificate = new Certificate(rs);
437 cache.put(certificate);
442 private static ObjectCache<Certificate> cache = new ObjectCache<>();
444 public synchronized static Certificate getById(int id) {
445 Certificate cacheRes = cache.get(id);
446 if (cacheRes != null) {
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")) {
453 GigiResultSet rs = ps.executeQuery();
458 Certificate c = new Certificate(rs);
462 } catch (IllegalArgumentException e) {
468 public static String escapeAVA(String value) {
470 return value.replace("\\", "\\\\").replace("/", "\\/");
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()));
479 return res.toString();
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]);
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();
496 return new java.util.Date(res.getTimestamp("revoked").getTime());
503 public void setLoginEnabled(boolean activate) {
505 if ( !isLoginEnabled()) {
506 try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `logincerts` SET `id`=?")) {
512 try (GigiPreparedStatement prep = new GigiPreparedStatement("DELETE FROM `logincerts` WHERE `id`=?")) {
519 public boolean isLoginEnabled() {
520 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT 1 FROM `logincerts` WHERE `id`=?")) {
522 GigiResultSet res = prep.executeQuery();
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);
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);
542 private static Certificate[] fetchCertsToArray(GigiPreparedStatement prep) {
543 GigiResultSet res = prep.executeQuery();
545 Certificate[] certs = new Certificate[res.getRow()];
547 for (int i = 0; res.next(); i++) {
548 certs[i] = Certificate.getById(res.getInt(1));
553 public void addAttachment(AttachmentType tp, String data) throws GigiApiException {
554 if (getAttachment(tp) != null) {
555 throw new GigiApiException("Cannot override attachment");
558 throw new GigiApiException("Attachment must not be null");
560 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `certificateAttachment` SET `certid`=?, `type`=?::`certificateAttachmentType`, `content`=?")) {
561 ps.setInt(1, getId());
563 ps.setString(3, data);
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());
572 GigiResultSet rs = ps.executeQuery();
576 String s = rs.getString(1);
578 throw new GigiApiException("Invalid database state");
584 public void setDescription(String description) {
585 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `certs` SET `description`=? WHERE `id`=?")) {
586 ps.setString(1, description);
590 this.description = description;
593 public String getDescription() {
597 public User getActor() {
601 public static Certificate locateCertificate(String serial, String certData) throws GigiApiException {
602 if (serial != null && !serial.isEmpty()) {
603 return getBySerial(normalizeSerial(serial));
606 if (certData != null && !certData.isEmpty()) {
607 final byte[] supplied;
608 final X509Certificate c0;
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);
618 Certificate c = getBySerial(c0.getSerialNumber());
622 X509Certificate cert = c.cert();
623 if ( !Arrays.equals(supplied, cert.getEncoded())) {
627 } catch (IOException e) {
628 throw new GigiApiException(NOT_LOADED);
629 } catch (GeneralSecurityException e) {
630 throw new GigiApiException(NOT_LOADED);
633 throw new GigiApiException("No information to identify the correct certificate was provided.");
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(":", "");
643 while (idx < serial.length() && serial.charAt(idx) == '0') {
646 serial = serial.substring(idx);
647 if ( !serial.matches("[0-9a-f]+")) {
648 throw new GigiApiException("Malformed serial");
650 return new BigInteger(serial, 16);