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 SANType implements DBEnum {
51 EMAIL("email"), DNS("DNS");
53 private final String opensslName;
55 private SANType(String opensslName) {
56 this.opensslName = opensslName;
59 public String getOpensslName() {
64 public String getDBName() {
69 public static class SubjectAlternateName implements Comparable<SubjectAlternateName> {
75 public SubjectAlternateName(SANType type, String name) {
80 public String getName() {
84 public SANType getType() {
89 public int compareTo(SubjectAlternateName o) {
90 int i = type.compareTo(o.type);
94 return name.compareTo(o.name);
98 public int hashCode() {
101 result = prime * result + ((name == null) ? 0 : name.hashCode());
102 result = prime * result + ((type == null) ? 0 : type.hashCode());
107 public boolean equals(Object obj) {
114 if (getClass() != obj.getClass()) {
117 SubjectAlternateName other = (SubjectAlternateName) obj;
119 if (other.name != null) {
122 } else if ( !name.equals(other.name)) {
125 if (type != other.type) {
133 public enum CSRType {
139 private CertificateOwner owner;
141 private String serial;
145 private String csrName;
147 private String crtName;
149 private String csr = null;
151 private CSRType csrType;
153 private List<SubjectAlternateName> sans;
155 private CertificateProfile profile;
157 private HashMap<String, String> dn;
159 private String dnString;
161 private CACertificate ca;
164 * Creates a new Certificate. WARNING: this is an internal API. Creating
165 * certificates for users must be done using the {@link CertificateRequest}
169 * the owner for whom the certificate should be created.
171 * the acting user that creates the certificate
173 * the distinguished name of the subject of this certificate (as
174 * Map using OpenSSL-Style keys)
176 * the {@link Digest} to sign the certificate with
178 * the CSR/SPKAC-Request containing the public key in question
180 * the type of the csr parameter
182 * the profile under which this certificate is to be issued
184 * additional subject alternative names
185 * @throws GigiApiException
186 * in case the request is malformed or internal errors occur
187 * @throws IOException
188 * when the request cannot be written.
190 public Certificate(CertificateOwner owner, User actor, HashMap<String, String> dn, Digest md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException, IOException {
191 if ( !profile.canBeIssuedBy(owner, actor)) {
192 throw new GigiApiException("You are not allowed to issue these certificates.");
196 if (dn.size() == 0) {
197 throw new GigiApiException("DN must not be empty.");
199 dnString = stringifyDN(dn);
202 this.csrType = csrType;
203 this.profile = profile;
204 this.sans = Arrays.asList(sans);
205 synchronized (Certificate.class) {
207 try (GigiPreparedStatement inserter = new GigiPreparedStatement("INSERT INTO certs SET md=?::`mdType`, csr_type=?::`csrType`, crt_name='', memid=?, profile=?")) {
208 inserter.setString(1, md.toString().toLowerCase());
209 inserter.setString(2, this.csrType.toString());
210 inserter.setInt(3, owner.getId());
211 inserter.setInt(4, profile.getId());
213 id = inserter.lastInsertId();
216 try (GigiPreparedStatement san = new GigiPreparedStatement("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`")) {
217 for (SubjectAlternateName subjectAlternateName : sans) {
219 san.setString(2, subjectAlternateName.getName());
220 san.setString(3, subjectAlternateName.getType().getOpensslName());
225 try (GigiPreparedStatement insertAVA = new GigiPreparedStatement("INSERT INTO `certAvas` SET `certId`=?, name=?, value=?")) {
226 insertAVA.setInt(1, id);
227 for (Entry<String, String> e : this.dn.entrySet()) {
228 insertAVA.setString(2, e.getKey());
229 insertAVA.setString(3, e.getValue());
233 File csrFile = KeyStorage.locateCsr(id);
234 csrName = csrFile.getPath();
235 try (FileOutputStream fos = new FileOutputStream(csrFile)) {
236 fos.write(this.csr.getBytes("UTF-8"));
238 try (GigiPreparedStatement updater = new GigiPreparedStatement("UPDATE `certs` SET `csr_name`=? WHERE id=?")) {
239 updater.setString(1, csrName);
240 updater.setInt(2, id);
248 private Certificate(GigiResultSet rs) {
249 this.id = rs.getInt("id");
250 dnString = rs.getString("subject");
251 md = Digest.valueOf(rs.getString("md").toUpperCase());
252 csrName = rs.getString("csr_name");
253 crtName = rs.getString("crt_name");
254 owner = CertificateOwner.getById(rs.getInt("memid"));
255 profile = CertificateProfile.getById(rs.getInt("profile"));
256 this.serial = rs.getString("serial");
258 try (GigiPreparedStatement ps2 = new GigiPreparedStatement("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?")) {
260 GigiResultSet rs2 = ps2.executeQuery();
261 sans = new LinkedList<>();
263 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
268 public enum CertificateStatus {
270 * This certificate is not in the database, has no id and only exists as
275 * The certificate has been signed. It is stored in the database.
276 * {@link Certificate#cert()} is valid.
281 * The certificate has been revoked.
286 * If this certificate cannot be updated because an error happened in
291 private final Outputable name;
293 private CertificateStatus(String codename) {
294 this.name = new TranslateCommand(codename);
298 public Outputable getName() {
304 public synchronized CertificateStatus getStatus() {
305 try (GigiPreparedStatement searcher = new GigiPreparedStatement("SELECT crt_name, created, revoked, serial, caid FROM certs WHERE id=?")) {
306 searcher.setInt(1, id);
307 GigiResultSet rs = searcher.executeQuery();
309 throw new IllegalStateException("Certificate not in Database");
312 crtName = rs.getString(1);
313 serial = rs.getString(4);
314 if (rs.getTimestamp(2) == null) {
315 return CertificateStatus.DRAFT;
317 ca = CACertificate.getById(rs.getInt("caid"));
318 if (rs.getTimestamp(2) != null && rs.getTimestamp(3) == null) {
319 return CertificateStatus.ISSUED;
321 return CertificateStatus.REVOKED;
327 * the date from which on the certificate should be valid. (or
328 * null if it should be valid instantly)
330 * the period for which the date should be valid. (a
331 * <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
333 * @return A job which can be used to monitor the progress of this task.
334 * @throws IOException
335 * for problems with writing the CSR/SPKAC
336 * @throws GigiApiException
337 * if the period is bogus
339 public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
340 if (getStatus() != CertificateStatus.DRAFT) {
341 throw new IllegalStateException();
344 return Job.sign(this, start, period);
348 public Job revoke(RevocationType type) {
349 if (getStatus() != CertificateStatus.ISSUED) {
350 throw new IllegalStateException();
352 return Job.revoke(this, type);
355 public Job revoke(String challenge, String signature, String message) {
356 if (getStatus() != CertificateStatus.ISSUED) {
357 throw new IllegalStateException();
359 return Job.revoke(this, challenge, signature, message);
362 public CACertificate getParent() {
363 CertificateStatus status = getStatus();
364 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
365 throw new IllegalStateException(status + " is not wanted here.");
370 public X509Certificate cert() throws IOException, GeneralSecurityException {
371 CertificateStatus status = getStatus();
372 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
373 throw new IllegalStateException(status + " is not wanted here.");
375 InputStream is = null;
376 X509Certificate crt = null;
378 is = new FileInputStream(crtName);
379 CertificateFactory cf = CertificateFactory.getInstance("X.509");
380 crt = (X509Certificate) cf.generateCertificate(is);
389 public Certificate renew() {
397 public String getSerial() {
403 public String getDistinguishedName() {
407 public Digest getMessageDigest() {
411 public CertificateOwner getOwner() {
415 public List<SubjectAlternateName> getSANs() {
416 return Collections.unmodifiableList(sans);
419 public CertificateProfile getProfile() {
423 private static final String CONCAT = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
425 public synchronized static Certificate getBySerial(String serial) {
426 if (serial == null || "".equals(serial)) {
429 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`")) {
430 ps.setString(1, serial);
431 GigiResultSet rs = ps.executeQuery();
435 int id = rs.getInt(1);
436 Certificate c1 = cache.get(id);
440 Certificate certificate = new Certificate(rs);
441 cache.put(certificate);
446 private static ObjectCache<Certificate> cache = new ObjectCache<>();
448 public synchronized static Certificate getById(int id) {
449 Certificate cacheRes = cache.get(id);
450 if (cacheRes != null) {
455 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")) {
457 GigiResultSet rs = ps.executeQuery();
462 Certificate c = new Certificate(rs);
466 } catch (IllegalArgumentException e) {
472 public static String escapeAVA(String value) {
474 return value.replace("\\", "\\\\").replace("/", "\\/");
477 public static String stringifyDN(HashMap<String, String> contents) {
478 StringBuffer res = new StringBuffer();
479 for (Entry<String, String> i : contents.entrySet()) {
480 res.append("/" + i.getKey() + "=");
481 res.append(escapeAVA(i.getValue()));
483 return res.toString();
486 public static HashMap<String, String> buildDN(String... contents) {
487 HashMap<String, String> res = new HashMap<>();
488 for (int i = 0; i + 1 < contents.length; i += 2) {
489 res.put(contents[i], contents[i + 1]);
494 public java.util.Date getRevocationDate() {
495 if (getStatus() == CertificateStatus.REVOKED) {
496 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT revoked FROM certs WHERE id=?")) {
497 prep.setInt(1, getId());
498 GigiResultSet res = prep.executeQuery();
500 return new java.util.Date(res.getTimestamp("revoked").getTime());
507 public void setLoginEnabled(boolean activate) {
509 if ( !isLoginEnabled()) {
510 try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `logincerts` SET `id`=?")) {
516 try (GigiPreparedStatement prep = new GigiPreparedStatement("DELETE FROM `logincerts` WHERE `id`=?")) {
523 public boolean isLoginEnabled() {
524 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT 1 FROM `logincerts` WHERE `id`=?")) {
526 GigiResultSet res = prep.executeQuery();
531 public static Certificate[] findBySerialPattern(String serial) {
532 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `id` FROM `certs` WHERE `serial` LIKE ? GROUP BY `id` LIMIT 100", true)) {
533 prep.setString(1, serial);
534 return fetchCertsToArray(prep);
538 public static Certificate[] findBySANPattern(String request, SANType type) {
539 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `certId` FROM `subjectAlternativeNames` WHERE `contents` LIKE ? and `type`=?::`SANType` GROUP BY `certId` LIMIT 100", true)) {
540 prep.setString(1, request);
541 prep.setEnum(2, type);
542 return fetchCertsToArray(prep);
546 private static Certificate[] fetchCertsToArray(GigiPreparedStatement prep) {
547 GigiResultSet res = prep.executeQuery();
549 Certificate[] certs = new Certificate[res.getRow()];
551 for (int i = 0; res.next(); i++) {
552 certs[i] = Certificate.getById(res.getInt(1));