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.CertificateFactory;
7 import java.security.cert.X509Certificate;
9 import java.util.Arrays;
10 import java.util.Collections;
11 import java.util.HashMap;
12 import java.util.LinkedList;
13 import java.util.List;
14 import java.util.Locale;
15 import java.util.Map.Entry;
17 import club.wpia.gigi.GigiApiException;
18 import club.wpia.gigi.database.DBEnum;
19 import club.wpia.gigi.database.GigiPreparedStatement;
20 import club.wpia.gigi.database.GigiResultSet;
21 import club.wpia.gigi.output.template.Outputable;
22 import club.wpia.gigi.output.template.TranslateCommand;
23 import club.wpia.gigi.pages.account.certs.CertificateRequest;
24 import club.wpia.gigi.util.PEM;
26 public class Certificate implements IdCachable {
28 public enum RevocationType implements DBEnum {
29 USER("user"), SUPPORT("support"), PING_TIMEOUT("ping_timeout"), KEY_COMPROMISE("key_compromise");
31 private final String dbName;
33 private RevocationType(String dbName) {
38 public String getDBName() {
42 public static RevocationType fromString(String s) {
43 return valueOf(s.toUpperCase(Locale.ENGLISH));
47 public enum AttachmentType implements DBEnum {
51 public String getDBName() {
56 public enum SANType implements DBEnum {
57 EMAIL("email"), DNS("DNS");
59 private final String opensslName;
61 private SANType(String opensslName) {
62 this.opensslName = opensslName;
65 public String getOpensslName() {
70 public String getDBName() {
75 public static class SubjectAlternateName implements Comparable<SubjectAlternateName> {
81 public SubjectAlternateName(SANType type, String name) {
86 public String getName() {
90 public SANType getType() {
95 public int compareTo(SubjectAlternateName o) {
96 int i = type.compareTo(o.type);
100 return name.compareTo(o.name);
104 public int hashCode() {
105 final int prime = 31;
107 result = prime * result + ((name == null) ? 0 : name.hashCode());
108 result = prime * result + ((type == null) ? 0 : type.hashCode());
113 public boolean equals(Object obj) {
120 if (getClass() != obj.getClass()) {
123 SubjectAlternateName other = (SubjectAlternateName) obj;
125 if (other.name != null) {
128 } else if ( !name.equals(other.name)) {
131 if (type != other.type) {
139 public enum CSRType {
145 private CertificateOwner owner;
147 private String serial;
151 private String csr = null;
153 private CSRType csrType;
155 private List<SubjectAlternateName> sans;
157 private CertificateProfile profile;
159 private HashMap<String, String> dn;
161 private String dnString;
163 private CACertificate ca;
165 private String description = "";
168 * Creates a new Certificate. WARNING: this is an internal API. Creating
169 * certificates for users must be done using the {@link CertificateRequest}
173 * the owner for whom the certificate should be created.
175 * the acting user that creates the certificate
177 * the distinguished name of the subject of this certificate (as
178 * Map using OpenSSL-Style keys)
180 * the {@link Digest} to sign the certificate with
182 * the CSR/SPKAC-Request containing the public key in question
184 * the type of the csr parameter
186 * the profile under which this certificate is to be issued
188 * additional subject alternative names
189 * @throws GigiApiException
190 * in case the request is malformed or internal errors occur
191 * @throws IOException
192 * when the request cannot be written.
194 public Certificate(CertificateOwner owner, User actor, HashMap<String, String> dn, Digest md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException, IOException {
195 if ( !profile.canBeIssuedBy(owner, actor)) {
196 throw new GigiApiException("You are not allowed to issue these certificates.");
200 if (dn.size() == 0) {
201 throw new GigiApiException("DN must not be empty.");
203 dnString = stringifyDN(dn);
206 this.csrType = csrType;
207 this.profile = profile;
208 this.sans = Arrays.asList(sans);
209 synchronized (Certificate.class) {
211 try (GigiPreparedStatement inserter = new GigiPreparedStatement("INSERT INTO certs SET md=?::`mdType`, csr_type=?::`csrType`, memid=?, profile=?")) {
212 inserter.setString(1, md.toString().toLowerCase());
213 inserter.setString(2, this.csrType.toString());
214 inserter.setInt(3, owner.getId());
215 inserter.setInt(4, profile.getId());
217 id = inserter.lastInsertId();
220 try (GigiPreparedStatement san = new GigiPreparedStatement("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`")) {
221 for (SubjectAlternateName subjectAlternateName : sans) {
223 san.setString(2, subjectAlternateName.getName());
224 san.setString(3, subjectAlternateName.getType().getOpensslName());
229 try (GigiPreparedStatement insertAVA = new GigiPreparedStatement("INSERT INTO `certAvas` SET `certId`=?, name=?, value=?")) {
230 insertAVA.setInt(1, id);
231 for (Entry<String, String> e : this.dn.entrySet()) {
232 insertAVA.setString(2, e.getKey());
233 insertAVA.setString(3, e.getValue());
237 addAttachment(AttachmentType.CSR, csr);
242 private Certificate(GigiResultSet rs) {
243 this.id = rs.getInt("id");
244 dnString = rs.getString("subject");
245 md = Digest.valueOf(rs.getString("md").toUpperCase());
246 owner = CertificateOwner.getById(rs.getInt("memid"));
247 profile = CertificateProfile.getById(rs.getInt("profile"));
248 this.serial = rs.getString("serial");
249 this.description = rs.getString("description");
251 try (GigiPreparedStatement ps2 = new GigiPreparedStatement("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?")) {
253 GigiResultSet rs2 = ps2.executeQuery();
254 sans = new LinkedList<>();
256 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
261 public enum CertificateStatus {
263 * This certificate is not in the database, has no id and only exists as
268 * The certificate has been signed. It is stored in the database.
269 * {@link Certificate#cert()} is valid.
274 * The certificate has been revoked.
279 * If this certificate cannot be updated because an error happened in
284 private final Outputable name;
286 private CertificateStatus(String codename) {
287 this.name = new TranslateCommand(codename);
291 public Outputable getName() {
297 public synchronized CertificateStatus getStatus() {
298 try (GigiPreparedStatement searcher = new GigiPreparedStatement("SELECT created, revoked, serial, caid FROM certs WHERE id=?")) {
299 searcher.setInt(1, id);
300 GigiResultSet rs = searcher.executeQuery();
302 throw new IllegalStateException("Certificate not in Database");
305 serial = rs.getString(3);
306 if (rs.getTimestamp(1) == null) {
307 return CertificateStatus.DRAFT;
309 ca = CACertificate.getById(rs.getInt("caid"));
310 if (rs.getTimestamp(1) != null && rs.getTimestamp(2) == null) {
311 return CertificateStatus.ISSUED;
313 return CertificateStatus.REVOKED;
319 * the date from which on the certificate should be valid. (or
320 * null if it should be valid instantly)
322 * the period for which the date should be valid. (a
323 * <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
325 * @return A job which can be used to monitor the progress of this task.
326 * @throws IOException
327 * for problems with writing the CSR/SPKAC
328 * @throws GigiApiException
329 * if the period is bogus
331 public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
332 if (getStatus() != CertificateStatus.DRAFT) {
333 throw new IllegalStateException();
336 return Job.sign(this, start, period);
340 public Job revoke(RevocationType type) {
341 if (getStatus() != CertificateStatus.ISSUED) {
342 throw new IllegalStateException();
344 return Job.revoke(this, type);
347 public Job revoke(String challenge, String signature, String message) {
348 if (getStatus() != CertificateStatus.ISSUED) {
349 throw new IllegalStateException();
351 return Job.revoke(this, challenge, signature, message);
354 public CACertificate getParent() {
355 CertificateStatus status = getStatus();
356 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
357 throw new IllegalStateException(status + " is not wanted here.");
362 public X509Certificate cert() throws IOException, GeneralSecurityException, GigiApiException {
363 CertificateStatus status = getStatus();
364 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
365 throw new IllegalStateException(status + " is not wanted here.");
367 String crtS = getAttachment(AttachmentType.CRT);
368 try (ByteArrayInputStream bais = new ByteArrayInputStream(PEM.decode("CERTIFICATE", crtS))) {
369 CertificateFactory cf = CertificateFactory.getInstance("X.509");
370 return (X509Certificate) cf.generateCertificate(bais);
374 public Certificate renew() {
382 public String getSerial() {
388 public String getDistinguishedName() {
392 public Digest getMessageDigest() {
396 public CertificateOwner getOwner() {
400 public List<SubjectAlternateName> getSANs() {
401 return Collections.unmodifiableList(sans);
404 public CertificateProfile getProfile() {
408 private static final String CONCAT = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
410 public synchronized static Certificate getBySerial(String serial) {
411 if (serial == null || "".equals(serial)) {
414 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`")) {
415 ps.setString(1, serial);
416 GigiResultSet rs = ps.executeQuery();
420 int id = rs.getInt(1);
421 Certificate c1 = cache.get(id);
425 Certificate certificate = new Certificate(rs);
426 cache.put(certificate);
431 private static ObjectCache<Certificate> cache = new ObjectCache<>();
433 public synchronized static Certificate getById(int id) {
434 Certificate cacheRes = cache.get(id);
435 if (cacheRes != null) {
440 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")) {
442 GigiResultSet rs = ps.executeQuery();
447 Certificate c = new Certificate(rs);
451 } catch (IllegalArgumentException e) {
457 public static String escapeAVA(String value) {
459 return value.replace("\\", "\\\\").replace("/", "\\/");
462 public static String stringifyDN(HashMap<String, String> contents) {
463 StringBuffer res = new StringBuffer();
464 for (Entry<String, String> i : contents.entrySet()) {
465 res.append("/" + i.getKey() + "=");
466 res.append(escapeAVA(i.getValue()));
468 return res.toString();
471 public static HashMap<String, String> buildDN(String... contents) {
472 HashMap<String, String> res = new HashMap<>();
473 for (int i = 0; i + 1 < contents.length; i += 2) {
474 res.put(contents[i], contents[i + 1]);
479 public java.util.Date getRevocationDate() {
480 if (getStatus() == CertificateStatus.REVOKED) {
481 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT revoked FROM certs WHERE id=?")) {
482 prep.setInt(1, getId());
483 GigiResultSet res = prep.executeQuery();
485 return new java.util.Date(res.getTimestamp("revoked").getTime());
492 public void setLoginEnabled(boolean activate) {
494 if ( !isLoginEnabled()) {
495 try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `logincerts` SET `id`=?")) {
501 try (GigiPreparedStatement prep = new GigiPreparedStatement("DELETE FROM `logincerts` WHERE `id`=?")) {
508 public boolean isLoginEnabled() {
509 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT 1 FROM `logincerts` WHERE `id`=?")) {
511 GigiResultSet res = prep.executeQuery();
516 public static Certificate[] findBySerialPattern(String serial) {
517 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `id` FROM `certs` WHERE `serial` LIKE ? GROUP BY `id` LIMIT 100", true)) {
518 prep.setString(1, serial);
519 return fetchCertsToArray(prep);
523 public static Certificate[] findBySANPattern(String request, SANType type) {
524 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `certId` FROM `subjectAlternativeNames` WHERE `contents` LIKE ? and `type`=?::`SANType` GROUP BY `certId` LIMIT 100", true)) {
525 prep.setString(1, request);
526 prep.setEnum(2, type);
527 return fetchCertsToArray(prep);
531 private static Certificate[] fetchCertsToArray(GigiPreparedStatement prep) {
532 GigiResultSet res = prep.executeQuery();
534 Certificate[] certs = new Certificate[res.getRow()];
536 for (int i = 0; res.next(); i++) {
537 certs[i] = Certificate.getById(res.getInt(1));
542 public void addAttachment(AttachmentType tp, String data) throws GigiApiException {
543 if (getAttachment(tp) != null) {
544 throw new GigiApiException("Cannot override attachment");
547 throw new GigiApiException("Attachment must not be null");
549 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `certificateAttachment` SET `certid`=?, `type`=?::`certificateAttachmentType`, `content`=?")) {
550 ps.setInt(1, getId());
552 ps.setString(3, data);
557 public String getAttachment(AttachmentType tp) throws GigiApiException {
558 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `content` FROM `certificateAttachment` WHERE `certid`=? AND `type`=?::`certificateAttachmentType`")) {
559 ps.setInt(1, getId());
561 GigiResultSet rs = ps.executeQuery();
565 String s = rs.getString(1);
567 throw new GigiApiException("Invalid database state");
573 public void setDescription(String description) {
574 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `certs` SET `description`=? WHERE `id`=?")) {
575 ps.setString(1, description);
579 this.description = description;
582 public String getDescription() {