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 = "";
169 public static final TranslateCommand NOT_LOADED = new TranslateCommand("Certificate could not be loaded");
171 public static final TranslateCommand NOT_PARSED = new TranslateCommand("Certificate could not be parsed");
174 * Creates a new Certificate. WARNING: this is an internal API. Creating
175 * certificates for users must be done using the {@link CertificateRequest}
179 * the owner for whom the certificate should be created.
181 * the acting user that creates the certificate
183 * the distinguished name of the subject of this certificate (as
184 * Map using OpenSSL-Style keys)
186 * the {@link Digest} to sign the certificate with
188 * the CSR/SPKAC-Request containing the public key in question
190 * the type of the csr parameter
192 * the profile under which this certificate is to be issued
194 * additional subject alternative names
195 * @throws GigiApiException
196 * in case the request is malformed or internal errors occur
197 * @throws IOException
198 * when the request cannot be written.
200 public Certificate(CertificateOwner owner, User actor, HashMap<String, String> dn, Digest md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException, IOException {
201 if ( !profile.canBeIssuedBy(owner, actor)) {
202 throw new GigiApiException("You are not allowed to issue these certificates.");
206 if (dn.size() == 0) {
207 throw new GigiApiException("DN must not be empty.");
209 dnString = stringifyDN(dn);
212 this.csrType = csrType;
213 this.profile = profile;
214 this.sans = Arrays.asList(sans);
215 synchronized (Certificate.class) {
217 try (GigiPreparedStatement inserter = new GigiPreparedStatement("INSERT INTO certs SET md=?::`mdType`, csr_type=?::`csrType`, memid=?, profile=?")) {
218 inserter.setString(1, md.toString().toLowerCase());
219 inserter.setString(2, this.csrType.toString());
220 inserter.setInt(3, owner.getId());
221 inserter.setInt(4, profile.getId());
223 id = inserter.lastInsertId();
226 try (GigiPreparedStatement san = new GigiPreparedStatement("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`")) {
227 for (SubjectAlternateName subjectAlternateName : sans) {
229 san.setString(2, subjectAlternateName.getName());
230 san.setString(3, subjectAlternateName.getType().getOpensslName());
235 try (GigiPreparedStatement insertAVA = new GigiPreparedStatement("INSERT INTO `certAvas` SET `certId`=?, name=?, value=?")) {
236 insertAVA.setInt(1, id);
237 for (Entry<String, String> e : this.dn.entrySet()) {
238 insertAVA.setString(2, e.getKey());
239 insertAVA.setString(3, e.getValue());
243 addAttachment(AttachmentType.CSR, csr);
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 owner = CertificateOwner.getById(rs.getInt("memid"));
253 profile = CertificateProfile.getById(rs.getInt("profile"));
254 this.serial = rs.getString("serial");
255 this.description = rs.getString("description");
257 try (GigiPreparedStatement ps2 = new GigiPreparedStatement("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?")) {
259 GigiResultSet rs2 = ps2.executeQuery();
260 sans = new LinkedList<>();
262 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
267 public enum CertificateStatus {
269 * This certificate is not in the database, has no id and only exists as
274 * The certificate has been signed. It is stored in the database.
275 * {@link Certificate#cert()} is valid.
280 * The certificate has been revoked.
285 * If this certificate cannot be updated because an error happened in
290 private final Outputable name;
292 private CertificateStatus(String codename) {
293 this.name = new TranslateCommand(codename);
297 public Outputable getName() {
303 public synchronized CertificateStatus getStatus() {
304 try (GigiPreparedStatement searcher = new GigiPreparedStatement("SELECT created, revoked, serial, caid FROM certs WHERE id=?")) {
305 searcher.setInt(1, id);
306 GigiResultSet rs = searcher.executeQuery();
308 throw new IllegalStateException("Certificate not in Database");
311 serial = rs.getString(3);
312 if (rs.getTimestamp(1) == null) {
313 return CertificateStatus.DRAFT;
315 ca = CACertificate.getById(rs.getInt("caid"));
316 if (rs.getTimestamp(1) != null && rs.getTimestamp(2) == null) {
317 return CertificateStatus.ISSUED;
319 return CertificateStatus.REVOKED;
325 * the date from which on the certificate should be valid. (or
326 * null if it should be valid instantly)
328 * the period for which the date should be valid. (a
329 * <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
331 * @return A job which can be used to monitor the progress of this task.
332 * @throws IOException
333 * for problems with writing the CSR/SPKAC
334 * @throws GigiApiException
335 * if the period is bogus
337 public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
338 if (getStatus() != CertificateStatus.DRAFT) {
339 throw new IllegalStateException();
342 return Job.sign(this, start, period);
346 public Job revoke(RevocationType type) {
347 if (getStatus() != CertificateStatus.ISSUED) {
348 throw new IllegalStateException();
350 return Job.revoke(this, type);
353 public Job revoke(String challenge, String signature, String message) {
354 if (getStatus() != CertificateStatus.ISSUED) {
355 throw new IllegalStateException();
357 return Job.revoke(this, challenge, signature, message);
360 public CACertificate getParent() {
361 CertificateStatus status = getStatus();
362 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
363 throw new IllegalStateException(status + " is not wanted here.");
368 public X509Certificate cert() throws IOException, GeneralSecurityException, GigiApiException {
369 CertificateStatus status = getStatus();
370 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
371 throw new IllegalStateException(status + " is not wanted here.");
373 String crtS = getAttachment(AttachmentType.CRT);
374 try (ByteArrayInputStream bais = new ByteArrayInputStream(PEM.decode("CERTIFICATE", crtS))) {
375 CertificateFactory cf = CertificateFactory.getInstance("X.509");
376 return (X509Certificate) cf.generateCertificate(bais);
380 public Certificate renew() {
388 public String getSerial() {
394 public String getDistinguishedName() {
398 public Digest getMessageDigest() {
402 public CertificateOwner getOwner() {
406 public List<SubjectAlternateName> getSANs() {
407 return Collections.unmodifiableList(sans);
410 public CertificateProfile getProfile() {
414 private static final String CONCAT = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
416 public synchronized static Certificate getBySerial(BigInteger serial) {
417 if (serial == null) {
420 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`")) {
421 ps.setString(1, serial.toString(16));
422 GigiResultSet rs = ps.executeQuery();
426 int id = rs.getInt(1);
427 Certificate c1 = cache.get(id);
431 Certificate certificate = new Certificate(rs);
432 cache.put(certificate);
437 private static ObjectCache<Certificate> cache = new ObjectCache<>();
439 public synchronized static Certificate getById(int id) {
440 Certificate cacheRes = cache.get(id);
441 if (cacheRes != null) {
446 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")) {
448 GigiResultSet rs = ps.executeQuery();
453 Certificate c = new Certificate(rs);
457 } catch (IllegalArgumentException e) {
463 public static String escapeAVA(String value) {
465 return value.replace("\\", "\\\\").replace("/", "\\/");
468 public static String stringifyDN(HashMap<String, String> contents) {
469 StringBuffer res = new StringBuffer();
470 for (Entry<String, String> i : contents.entrySet()) {
471 res.append("/" + i.getKey() + "=");
472 res.append(escapeAVA(i.getValue()));
474 return res.toString();
477 public static HashMap<String, String> buildDN(String... contents) {
478 HashMap<String, String> res = new HashMap<>();
479 for (int i = 0; i + 1 < contents.length; i += 2) {
480 res.put(contents[i], contents[i + 1]);
485 public java.util.Date getRevocationDate() {
486 if (getStatus() == CertificateStatus.REVOKED) {
487 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT revoked FROM certs WHERE id=?")) {
488 prep.setInt(1, getId());
489 GigiResultSet res = prep.executeQuery();
491 return new java.util.Date(res.getTimestamp("revoked").getTime());
498 public void setLoginEnabled(boolean activate) {
500 if ( !isLoginEnabled()) {
501 try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `logincerts` SET `id`=?")) {
507 try (GigiPreparedStatement prep = new GigiPreparedStatement("DELETE FROM `logincerts` WHERE `id`=?")) {
514 public boolean isLoginEnabled() {
515 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT 1 FROM `logincerts` WHERE `id`=?")) {
517 GigiResultSet res = prep.executeQuery();
522 public static Certificate[] findBySerialPattern(String serial) {
523 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `id` FROM `certs` WHERE `serial` LIKE ? GROUP BY `id` LIMIT 100", true)) {
524 prep.setString(1, serial);
525 return fetchCertsToArray(prep);
529 public static Certificate[] findBySANPattern(String request, SANType type) {
530 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `certId` FROM `subjectAlternativeNames` WHERE `contents` LIKE ? and `type`=?::`SANType` GROUP BY `certId` LIMIT 100", true)) {
531 prep.setString(1, request);
532 prep.setEnum(2, type);
533 return fetchCertsToArray(prep);
537 private static Certificate[] fetchCertsToArray(GigiPreparedStatement prep) {
538 GigiResultSet res = prep.executeQuery();
540 Certificate[] certs = new Certificate[res.getRow()];
542 for (int i = 0; res.next(); i++) {
543 certs[i] = Certificate.getById(res.getInt(1));
548 public void addAttachment(AttachmentType tp, String data) throws GigiApiException {
549 if (getAttachment(tp) != null) {
550 throw new GigiApiException("Cannot override attachment");
553 throw new GigiApiException("Attachment must not be null");
555 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `certificateAttachment` SET `certid`=?, `type`=?::`certificateAttachmentType`, `content`=?")) {
556 ps.setInt(1, getId());
558 ps.setString(3, data);
563 public String getAttachment(AttachmentType tp) throws GigiApiException {
564 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `content` FROM `certificateAttachment` WHERE `certid`=? AND `type`=?::`certificateAttachmentType`")) {
565 ps.setInt(1, getId());
567 GigiResultSet rs = ps.executeQuery();
571 String s = rs.getString(1);
573 throw new GigiApiException("Invalid database state");
579 public void setDescription(String description) {
580 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `certs` SET `description`=? WHERE `id`=?")) {
581 ps.setString(1, description);
585 this.description = description;
588 public String getDescription() {
592 public static Certificate locateCertificate(String serial, String certData) throws GigiApiException {
593 if (serial != null && !serial.isEmpty()) {
594 return getBySerial(normalizeSerial(serial));
597 if (certData != null && !certData.isEmpty()) {
598 final byte[] supplied;
599 final X509Certificate c0;
601 supplied = PEM.decode("CERTIFICATE", certData);
602 c0 = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(supplied));
603 } catch (IllegalArgumentException e1) {
604 throw new GigiApiException(NOT_PARSED);
605 } catch (CertificateException e1) {
606 throw new GigiApiException(NOT_PARSED);
609 Certificate c = getBySerial(c0.getSerialNumber());
613 X509Certificate cert = c.cert();
614 if ( !Arrays.equals(supplied, cert.getEncoded())) {
618 } catch (IOException e) {
619 throw new GigiApiException(NOT_LOADED);
620 } catch (GeneralSecurityException e) {
621 throw new GigiApiException(NOT_LOADED);
624 throw new GigiApiException("No information to identify the correct certificate was provided.");
627 public static BigInteger normalizeSerial(String serial) throws GigiApiException {
628 serial = serial.replace(" ", "");
629 serial = serial.toLowerCase();
630 if (serial.matches("[0-9a-f]{2}(:[0-9a-f]{2})*")) {
631 serial = serial.replace(":", "");
634 while (idx < serial.length() && serial.charAt(idx) == '0') {
637 serial = serial.substring(idx);
638 if ( !serial.matches("[0-9a-f]+")) {
639 throw new GigiApiException("Malformed serial");
641 return new BigInteger(serial, 16);