1 package club.wpia.gigi.dbObjects;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
8 import java.security.GeneralSecurityException;
9 import java.security.cert.CertificateFactory;
10 import java.security.cert.X509Certificate;
12 import java.util.Arrays;
13 import java.util.Collections;
14 import java.util.HashMap;
15 import java.util.LinkedList;
16 import java.util.List;
17 import java.util.Locale;
18 import java.util.Map.Entry;
20 import club.wpia.gigi.GigiApiException;
21 import club.wpia.gigi.database.DBEnum;
22 import club.wpia.gigi.database.GigiPreparedStatement;
23 import club.wpia.gigi.database.GigiResultSet;
24 import club.wpia.gigi.output.template.Outputable;
25 import club.wpia.gigi.output.template.TranslateCommand;
26 import club.wpia.gigi.pages.account.certs.CertificateRequest;
27 import club.wpia.gigi.util.KeyStorage;
29 public class Certificate implements IdCachable {
31 public enum RevocationType implements DBEnum {
32 USER("user"), SUPPORT("support"), PING_TIMEOUT("ping_timeout"), KEY_COMPROMISE("key_compromise");
34 private final String dbName;
36 private RevocationType(String dbName) {
41 public String getDBName() {
45 public static RevocationType fromString(String s) {
46 return valueOf(s.toUpperCase(Locale.ENGLISH));
50 public enum AttachmentType implements DBEnum {
54 public String getDBName() {
59 public enum SANType implements DBEnum {
60 EMAIL("email"), DNS("DNS");
62 private final String opensslName;
64 private SANType(String opensslName) {
65 this.opensslName = opensslName;
68 public String getOpensslName() {
73 public String getDBName() {
78 public static class SubjectAlternateName implements Comparable<SubjectAlternateName> {
84 public SubjectAlternateName(SANType type, String name) {
89 public String getName() {
93 public SANType getType() {
98 public int compareTo(SubjectAlternateName o) {
99 int i = type.compareTo(o.type);
103 return name.compareTo(o.name);
107 public int hashCode() {
108 final int prime = 31;
110 result = prime * result + ((name == null) ? 0 : name.hashCode());
111 result = prime * result + ((type == null) ? 0 : type.hashCode());
116 public boolean equals(Object obj) {
123 if (getClass() != obj.getClass()) {
126 SubjectAlternateName other = (SubjectAlternateName) obj;
128 if (other.name != null) {
131 } else if ( !name.equals(other.name)) {
134 if (type != other.type) {
142 public enum CSRType {
148 private CertificateOwner owner;
150 private String serial;
154 private String csrName;
156 private String crtName;
158 private String csr = null;
160 private CSRType csrType;
162 private List<SubjectAlternateName> sans;
164 private CertificateProfile profile;
166 private HashMap<String, String> dn;
168 private String dnString;
170 private CACertificate ca;
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`, crt_name='', 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 File csrFile = KeyStorage.locateCsr(id);
243 csrName = csrFile.getPath();
244 try (FileOutputStream fos = new FileOutputStream(csrFile)) {
245 fos.write(this.csr.getBytes("UTF-8"));
247 try (GigiPreparedStatement updater = new GigiPreparedStatement("UPDATE `certs` SET `csr_name`=? WHERE id=?")) {
248 updater.setString(1, csrName);
249 updater.setInt(2, id);
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 csrName = rs.getString("csr_name");
262 crtName = rs.getString("crt_name");
263 owner = CertificateOwner.getById(rs.getInt("memid"));
264 profile = CertificateProfile.getById(rs.getInt("profile"));
265 this.serial = rs.getString("serial");
267 try (GigiPreparedStatement ps2 = new GigiPreparedStatement("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?")) {
269 GigiResultSet rs2 = ps2.executeQuery();
270 sans = new LinkedList<>();
272 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
277 public enum CertificateStatus {
279 * This certificate is not in the database, has no id and only exists as
284 * The certificate has been signed. It is stored in the database.
285 * {@link Certificate#cert()} is valid.
290 * The certificate has been revoked.
295 * If this certificate cannot be updated because an error happened in
300 private final Outputable name;
302 private CertificateStatus(String codename) {
303 this.name = new TranslateCommand(codename);
307 public Outputable getName() {
313 public synchronized CertificateStatus getStatus() {
314 try (GigiPreparedStatement searcher = new GigiPreparedStatement("SELECT crt_name, created, revoked, serial, caid FROM certs WHERE id=?")) {
315 searcher.setInt(1, id);
316 GigiResultSet rs = searcher.executeQuery();
318 throw new IllegalStateException("Certificate not in Database");
321 crtName = rs.getString(1);
322 serial = rs.getString(4);
323 if (rs.getTimestamp(2) == null) {
324 return CertificateStatus.DRAFT;
326 ca = CACertificate.getById(rs.getInt("caid"));
327 if (rs.getTimestamp(2) != null && rs.getTimestamp(3) == null) {
328 return CertificateStatus.ISSUED;
330 return CertificateStatus.REVOKED;
336 * the date from which on the certificate should be valid. (or
337 * null if it should be valid instantly)
339 * the period for which the date should be valid. (a
340 * <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
342 * @return A job which can be used to monitor the progress of this task.
343 * @throws IOException
344 * for problems with writing the CSR/SPKAC
345 * @throws GigiApiException
346 * if the period is bogus
348 public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
349 if (getStatus() != CertificateStatus.DRAFT) {
350 throw new IllegalStateException();
353 return Job.sign(this, start, period);
357 public Job revoke(RevocationType type) {
358 if (getStatus() != CertificateStatus.ISSUED) {
359 throw new IllegalStateException();
361 return Job.revoke(this, type);
364 public Job revoke(String challenge, String signature, String message) {
365 if (getStatus() != CertificateStatus.ISSUED) {
366 throw new IllegalStateException();
368 return Job.revoke(this, challenge, signature, message);
371 public CACertificate getParent() {
372 CertificateStatus status = getStatus();
373 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
374 throw new IllegalStateException(status + " is not wanted here.");
379 public X509Certificate cert() throws IOException, GeneralSecurityException {
380 CertificateStatus status = getStatus();
381 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
382 throw new IllegalStateException(status + " is not wanted here.");
384 InputStream is = null;
385 X509Certificate crt = null;
387 is = new FileInputStream(crtName);
388 CertificateFactory cf = CertificateFactory.getInstance("X.509");
389 crt = (X509Certificate) cf.generateCertificate(is);
398 public Certificate renew() {
406 public String getSerial() {
412 public String getDistinguishedName() {
416 public Digest getMessageDigest() {
420 public CertificateOwner getOwner() {
424 public List<SubjectAlternateName> getSANs() {
425 return Collections.unmodifiableList(sans);
428 public CertificateProfile getProfile() {
432 private static final String CONCAT = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
434 public synchronized static Certificate getBySerial(String serial) {
435 if (serial == null || "".equals(serial)) {
438 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT certs.id, " + CONCAT + " as `subject`, `md`, `csr_name`, `crt_name`,`memid`, `profile`, `certs`.`serial` FROM `certs` LEFT JOIN `certAvas` ON `certAvas`.`certId`=`certs`.`id` WHERE `serial`=? GROUP BY `certs`.`id`")) {
439 ps.setString(1, serial);
440 GigiResultSet rs = ps.executeQuery();
444 int id = rs.getInt(1);
445 Certificate c1 = cache.get(id);
449 Certificate certificate = new Certificate(rs);
450 cache.put(certificate);
455 private static ObjectCache<Certificate> cache = new ObjectCache<>();
457 public synchronized static Certificate getById(int id) {
458 Certificate cacheRes = cache.get(id);
459 if (cacheRes != null) {
464 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT certs.id, " + CONCAT + " as subject, md, csr_name, crt_name,memid, profile, certs.serial FROM `certs` LEFT JOIN `certAvas` ON `certAvas`.`certId`=certs.id WHERE certs.id=? GROUP BY certs.id")) {
466 GigiResultSet rs = ps.executeQuery();
471 Certificate c = new Certificate(rs);
475 } catch (IllegalArgumentException e) {
481 public static String escapeAVA(String value) {
483 return value.replace("\\", "\\\\").replace("/", "\\/");
486 public static String stringifyDN(HashMap<String, String> contents) {
487 StringBuffer res = new StringBuffer();
488 for (Entry<String, String> i : contents.entrySet()) {
489 res.append("/" + i.getKey() + "=");
490 res.append(escapeAVA(i.getValue()));
492 return res.toString();
495 public static HashMap<String, String> buildDN(String... contents) {
496 HashMap<String, String> res = new HashMap<>();
497 for (int i = 0; i + 1 < contents.length; i += 2) {
498 res.put(contents[i], contents[i + 1]);
503 public java.util.Date getRevocationDate() {
504 if (getStatus() == CertificateStatus.REVOKED) {
505 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT revoked FROM certs WHERE id=?")) {
506 prep.setInt(1, getId());
507 GigiResultSet res = prep.executeQuery();
509 return new java.util.Date(res.getTimestamp("revoked").getTime());
516 public void setLoginEnabled(boolean activate) {
518 if ( !isLoginEnabled()) {
519 try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `logincerts` SET `id`=?")) {
525 try (GigiPreparedStatement prep = new GigiPreparedStatement("DELETE FROM `logincerts` WHERE `id`=?")) {
532 public boolean isLoginEnabled() {
533 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT 1 FROM `logincerts` WHERE `id`=?")) {
535 GigiResultSet res = prep.executeQuery();
540 public static Certificate[] findBySerialPattern(String serial) {
541 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `id` FROM `certs` WHERE `serial` LIKE ? GROUP BY `id` LIMIT 100", true)) {
542 prep.setString(1, serial);
543 return fetchCertsToArray(prep);
547 public static Certificate[] findBySANPattern(String request, SANType type) {
548 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `certId` FROM `subjectAlternativeNames` WHERE `contents` LIKE ? and `type`=?::`SANType` GROUP BY `certId` LIMIT 100", true)) {
549 prep.setString(1, request);
550 prep.setEnum(2, type);
551 return fetchCertsToArray(prep);
555 private static Certificate[] fetchCertsToArray(GigiPreparedStatement prep) {
556 GigiResultSet res = prep.executeQuery();
558 Certificate[] certs = new Certificate[res.getRow()];
560 for (int i = 0; res.next(); i++) {
561 certs[i] = Certificate.getById(res.getInt(1));
566 public void addAttachment(AttachmentType tp, String data) throws GigiApiException {
567 if (getAttachment(tp) != null) {
568 throw new GigiApiException("Cannot override attachment");
571 throw new GigiApiException("Attachment must not be null");
573 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `certificateAttachment` SET `certid`=?, `type`=?::`certificateAttachmentType`, `content`=?")) {
574 ps.setInt(1, getId());
576 ps.setString(3, data);
581 public String getAttachment(AttachmentType tp) throws GigiApiException {
582 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `content` FROM `certificateAttachment` WHERE `certid`=? AND `type`=?::`certificateAttachmentType`")) {
583 ps.setInt(1, getId());
585 GigiResultSet rs = ps.executeQuery();
589 String s = rs.getString(1);
591 throw new GigiApiException("Invalid database state");