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;
166 * Creates a new Certificate. WARNING: this is an internal API. Creating
167 * certificates for users must be done using the {@link CertificateRequest}
171 * the owner for whom the certificate should be created.
173 * the acting user that creates the certificate
175 * the distinguished name of the subject of this certificate (as
176 * Map using OpenSSL-Style keys)
178 * the {@link Digest} to sign the certificate with
180 * the CSR/SPKAC-Request containing the public key in question
182 * the type of the csr parameter
184 * the profile under which this certificate is to be issued
186 * additional subject alternative names
187 * @throws GigiApiException
188 * in case the request is malformed or internal errors occur
189 * @throws IOException
190 * when the request cannot be written.
192 public Certificate(CertificateOwner owner, User actor, HashMap<String, String> dn, Digest md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException, IOException {
193 if ( !profile.canBeIssuedBy(owner, actor)) {
194 throw new GigiApiException("You are not allowed to issue these certificates.");
198 if (dn.size() == 0) {
199 throw new GigiApiException("DN must not be empty.");
201 dnString = stringifyDN(dn);
204 this.csrType = csrType;
205 this.profile = profile;
206 this.sans = Arrays.asList(sans);
207 synchronized (Certificate.class) {
209 try (GigiPreparedStatement inserter = new GigiPreparedStatement("INSERT INTO certs SET md=?::`mdType`, csr_type=?::`csrType`, memid=?, profile=?")) {
210 inserter.setString(1, md.toString().toLowerCase());
211 inserter.setString(2, this.csrType.toString());
212 inserter.setInt(3, owner.getId());
213 inserter.setInt(4, profile.getId());
215 id = inserter.lastInsertId();
218 try (GigiPreparedStatement san = new GigiPreparedStatement("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`")) {
219 for (SubjectAlternateName subjectAlternateName : sans) {
221 san.setString(2, subjectAlternateName.getName());
222 san.setString(3, subjectAlternateName.getType().getOpensslName());
227 try (GigiPreparedStatement insertAVA = new GigiPreparedStatement("INSERT INTO `certAvas` SET `certId`=?, name=?, value=?")) {
228 insertAVA.setInt(1, id);
229 for (Entry<String, String> e : this.dn.entrySet()) {
230 insertAVA.setString(2, e.getKey());
231 insertAVA.setString(3, e.getValue());
235 addAttachment(AttachmentType.CSR, csr);
240 private Certificate(GigiResultSet rs) {
241 this.id = rs.getInt("id");
242 dnString = rs.getString("subject");
243 md = Digest.valueOf(rs.getString("md").toUpperCase());
244 owner = CertificateOwner.getById(rs.getInt("memid"));
245 profile = CertificateProfile.getById(rs.getInt("profile"));
246 this.serial = rs.getString("serial");
248 try (GigiPreparedStatement ps2 = new GigiPreparedStatement("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?")) {
250 GigiResultSet rs2 = ps2.executeQuery();
251 sans = new LinkedList<>();
253 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
258 public enum CertificateStatus {
260 * This certificate is not in the database, has no id and only exists as
265 * The certificate has been signed. It is stored in the database.
266 * {@link Certificate#cert()} is valid.
271 * The certificate has been revoked.
276 * If this certificate cannot be updated because an error happened in
281 private final Outputable name;
283 private CertificateStatus(String codename) {
284 this.name = new TranslateCommand(codename);
288 public Outputable getName() {
294 public synchronized CertificateStatus getStatus() {
295 try (GigiPreparedStatement searcher = new GigiPreparedStatement("SELECT created, revoked, serial, caid FROM certs WHERE id=?")) {
296 searcher.setInt(1, id);
297 GigiResultSet rs = searcher.executeQuery();
299 throw new IllegalStateException("Certificate not in Database");
302 serial = rs.getString(3);
303 if (rs.getTimestamp(1) == null) {
304 return CertificateStatus.DRAFT;
306 ca = CACertificate.getById(rs.getInt("caid"));
307 if (rs.getTimestamp(1) != null && rs.getTimestamp(2) == null) {
308 return CertificateStatus.ISSUED;
310 return CertificateStatus.REVOKED;
316 * the date from which on the certificate should be valid. (or
317 * null if it should be valid instantly)
319 * the period for which the date should be valid. (a
320 * <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
322 * @return A job which can be used to monitor the progress of this task.
323 * @throws IOException
324 * for problems with writing the CSR/SPKAC
325 * @throws GigiApiException
326 * if the period is bogus
328 public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
329 if (getStatus() != CertificateStatus.DRAFT) {
330 throw new IllegalStateException();
333 return Job.sign(this, start, period);
337 public Job revoke(RevocationType type) {
338 if (getStatus() != CertificateStatus.ISSUED) {
339 throw new IllegalStateException();
341 return Job.revoke(this, type);
344 public Job revoke(String challenge, String signature, String message) {
345 if (getStatus() != CertificateStatus.ISSUED) {
346 throw new IllegalStateException();
348 return Job.revoke(this, challenge, signature, message);
351 public CACertificate getParent() {
352 CertificateStatus status = getStatus();
353 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
354 throw new IllegalStateException(status + " is not wanted here.");
359 public X509Certificate cert() throws IOException, GeneralSecurityException, GigiApiException {
360 CertificateStatus status = getStatus();
361 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
362 throw new IllegalStateException(status + " is not wanted here.");
364 String crtS = getAttachment(AttachmentType.CRT);
365 try (ByteArrayInputStream bais = new ByteArrayInputStream(PEM.decode("CERTIFICATE", crtS))) {
366 CertificateFactory cf = CertificateFactory.getInstance("X.509");
367 return (X509Certificate) cf.generateCertificate(bais);
371 public Certificate renew() {
379 public String getSerial() {
385 public String getDistinguishedName() {
389 public Digest getMessageDigest() {
393 public CertificateOwner getOwner() {
397 public List<SubjectAlternateName> getSANs() {
398 return Collections.unmodifiableList(sans);
401 public CertificateProfile getProfile() {
405 private static final String CONCAT = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
407 public synchronized static Certificate getBySerial(String serial) {
408 if (serial == null || "".equals(serial)) {
411 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT certs.id, " + CONCAT + " as `subject`, `md`,`memid`, `profile`, `certs`.`serial` FROM `certs` LEFT JOIN `certAvas` ON `certAvas`.`certId`=`certs`.`id` WHERE `serial`=? GROUP BY `certs`.`id`")) {
412 ps.setString(1, serial);
413 GigiResultSet rs = ps.executeQuery();
417 int id = rs.getInt(1);
418 Certificate c1 = cache.get(id);
422 Certificate certificate = new Certificate(rs);
423 cache.put(certificate);
428 private static ObjectCache<Certificate> cache = new ObjectCache<>();
430 public synchronized static Certificate getById(int id) {
431 Certificate cacheRes = cache.get(id);
432 if (cacheRes != null) {
437 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT certs.id, " + CONCAT + " as subject, md, memid, profile, certs.serial FROM `certs` LEFT JOIN `certAvas` ON `certAvas`.`certId`=certs.id WHERE certs.id=? GROUP BY certs.id")) {
439 GigiResultSet rs = ps.executeQuery();
444 Certificate c = new Certificate(rs);
448 } catch (IllegalArgumentException e) {
454 public static String escapeAVA(String value) {
456 return value.replace("\\", "\\\\").replace("/", "\\/");
459 public static String stringifyDN(HashMap<String, String> contents) {
460 StringBuffer res = new StringBuffer();
461 for (Entry<String, String> i : contents.entrySet()) {
462 res.append("/" + i.getKey() + "=");
463 res.append(escapeAVA(i.getValue()));
465 return res.toString();
468 public static HashMap<String, String> buildDN(String... contents) {
469 HashMap<String, String> res = new HashMap<>();
470 for (int i = 0; i + 1 < contents.length; i += 2) {
471 res.put(contents[i], contents[i + 1]);
476 public java.util.Date getRevocationDate() {
477 if (getStatus() == CertificateStatus.REVOKED) {
478 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT revoked FROM certs WHERE id=?")) {
479 prep.setInt(1, getId());
480 GigiResultSet res = prep.executeQuery();
482 return new java.util.Date(res.getTimestamp("revoked").getTime());
489 public void setLoginEnabled(boolean activate) {
491 if ( !isLoginEnabled()) {
492 try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `logincerts` SET `id`=?")) {
498 try (GigiPreparedStatement prep = new GigiPreparedStatement("DELETE FROM `logincerts` WHERE `id`=?")) {
505 public boolean isLoginEnabled() {
506 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT 1 FROM `logincerts` WHERE `id`=?")) {
508 GigiResultSet res = prep.executeQuery();
513 public static Certificate[] findBySerialPattern(String serial) {
514 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `id` FROM `certs` WHERE `serial` LIKE ? GROUP BY `id` LIMIT 100", true)) {
515 prep.setString(1, serial);
516 return fetchCertsToArray(prep);
520 public static Certificate[] findBySANPattern(String request, SANType type) {
521 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `certId` FROM `subjectAlternativeNames` WHERE `contents` LIKE ? and `type`=?::`SANType` GROUP BY `certId` LIMIT 100", true)) {
522 prep.setString(1, request);
523 prep.setEnum(2, type);
524 return fetchCertsToArray(prep);
528 private static Certificate[] fetchCertsToArray(GigiPreparedStatement prep) {
529 GigiResultSet res = prep.executeQuery();
531 Certificate[] certs = new Certificate[res.getRow()];
533 for (int i = 0; res.next(); i++) {
534 certs[i] = Certificate.getById(res.getInt(1));
539 public void addAttachment(AttachmentType tp, String data) throws GigiApiException {
540 if (getAttachment(tp) != null) {
541 throw new GigiApiException("Cannot override attachment");
544 throw new GigiApiException("Attachment must not be null");
546 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `certificateAttachment` SET `certid`=?, `type`=?::`certificateAttachmentType`, `content`=?")) {
547 ps.setInt(1, getId());
549 ps.setString(3, data);
554 public String getAttachment(AttachmentType tp) throws GigiApiException {
555 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `content` FROM `certificateAttachment` WHERE `certid`=? AND `type`=?::`certificateAttachmentType`")) {
556 ps.setInt(1, getId());
558 GigiResultSet rs = ps.executeQuery();
562 String s = rs.getString(1);
564 throw new GigiApiException("Invalid database state");