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.MessageDigest;
8 import java.security.NoSuchAlgorithmException;
9 import java.security.cert.CertificateEncodingException;
10 import java.security.cert.CertificateException;
11 import java.security.cert.CertificateFactory;
12 import java.security.cert.X509Certificate;
14 import java.util.Arrays;
15 import java.util.Collections;
16 import java.util.HashMap;
17 import java.util.LinkedList;
18 import java.util.List;
19 import java.util.Locale;
20 import java.util.Map.Entry;
22 import javax.xml.bind.DatatypeConverter;
24 import club.wpia.gigi.GigiApiException;
25 import club.wpia.gigi.database.DBEnum;
26 import club.wpia.gigi.database.GigiPreparedStatement;
27 import club.wpia.gigi.database.GigiResultSet;
28 import club.wpia.gigi.output.template.Outputable;
29 import club.wpia.gigi.output.template.TranslateCommand;
30 import club.wpia.gigi.pages.account.certs.CertificateRequest;
31 import club.wpia.gigi.util.PEM;
33 public class Certificate implements IdCachable {
35 public enum RevocationType implements DBEnum {
36 USER("user"), SUPPORT("support"), PING_TIMEOUT("ping_timeout"), KEY_COMPROMISE("key_compromise");
38 private final String dbName;
40 private RevocationType(String dbName) {
45 public String getDBName() {
49 public static RevocationType fromString(String s) {
50 return valueOf(s.toUpperCase(Locale.ENGLISH));
54 public enum AttachmentType implements DBEnum {
58 public String getDBName() {
63 public enum SANType implements DBEnum {
64 EMAIL("email"), DNS("DNS");
66 private final String opensslName;
68 private SANType(String opensslName) {
69 this.opensslName = opensslName;
72 public String getOpensslName() {
77 public String getDBName() {
82 public static class SubjectAlternateName implements Comparable<SubjectAlternateName> {
88 public SubjectAlternateName(SANType type, String name) {
93 public String getName() {
97 public SANType getType() {
102 public int compareTo(SubjectAlternateName o) {
103 int i = type.compareTo(o.type);
107 return name.compareTo(o.name);
111 public int hashCode() {
112 final int prime = 31;
114 result = prime * result + ((name == null) ? 0 : name.hashCode());
115 result = prime * result + ((type == null) ? 0 : type.hashCode());
120 public boolean equals(Object obj) {
127 if (getClass() != obj.getClass()) {
130 SubjectAlternateName other = (SubjectAlternateName) obj;
132 if (other.name != null) {
135 } else if ( !name.equals(other.name)) {
138 if (type != other.type) {
146 public enum CSRType {
152 private CertificateOwner owner;
154 private String serial;
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;
172 private String description = "";
176 public static final TranslateCommand NOT_LOADED = new TranslateCommand("Certificate could not be loaded");
178 public static final TranslateCommand NOT_PARSED = new TranslateCommand("Certificate could not be parsed");
181 * Creates a new Certificate. WARNING: this is an internal API. Creating
182 * certificates for users must be done using the {@link CertificateRequest}
186 * the owner for whom the certificate should be created.
188 * the acting user that creates the certificate
190 * the distinguished name of the subject of this certificate (as
191 * Map using OpenSSL-Style keys)
193 * the {@link Digest} to sign the certificate with
195 * the CSR/SPKAC-Request containing the public key in question
197 * the type of the csr parameter
199 * the profile under which this certificate is to be issued
201 * additional subject alternative names
202 * @throws GigiApiException
203 * in case the request is malformed or internal errors occur
204 * @throws IOException
205 * when the request cannot be written.
207 public Certificate(CertificateOwner owner, User actor, HashMap<String, String> dn, Digest md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException, IOException {
208 if ( !profile.canBeIssuedBy(owner, actor)) {
209 throw new GigiApiException("You are not allowed to issue these certificates.");
213 if (dn.size() == 0) {
214 throw new GigiApiException("DN must not be empty.");
216 dnString = stringifyDN(dn);
219 this.csrType = csrType;
220 this.profile = profile;
221 this.sans = Arrays.asList(sans);
223 synchronized (Certificate.class) {
225 try (GigiPreparedStatement inserter = new GigiPreparedStatement("INSERT INTO certs SET md=?::`mdType`, csr_type=?::`csrType`, memid=?, profile=?, actorid=?")) {
226 inserter.setString(1, md.toString().toLowerCase());
227 inserter.setString(2, this.csrType.toString());
228 inserter.setInt(3, owner.getId());
229 inserter.setInt(4, profile.getId());
230 inserter.setInt(5, this.actor.getId());
232 id = inserter.lastInsertId();
235 try (GigiPreparedStatement san = new GigiPreparedStatement("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`")) {
236 for (SubjectAlternateName subjectAlternateName : sans) {
238 san.setString(2, subjectAlternateName.getName());
239 san.setString(3, subjectAlternateName.getType().getOpensslName());
244 try (GigiPreparedStatement insertAVA = new GigiPreparedStatement("INSERT INTO `certAvas` SET `certId`=?, name=?, value=?")) {
245 insertAVA.setInt(1, id);
246 for (Entry<String, String> e : this.dn.entrySet()) {
247 insertAVA.setString(2, e.getKey());
248 insertAVA.setString(3, e.getValue());
252 addAttachment(AttachmentType.CSR, csr);
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 owner = CertificateOwner.getById(rs.getInt("memid"));
262 profile = CertificateProfile.getById(rs.getInt("profile"));
263 this.serial = rs.getString("serial");
264 this.description = rs.getString("description");
265 this.actor = User.getById(rs.getInt("actorid"));
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 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 serial = rs.getString(3);
322 if (rs.getTimestamp(1) == null) {
323 return CertificateStatus.DRAFT;
325 ca = CACertificate.getById(rs.getInt("caid"));
326 if (rs.getTimestamp(1) != null && rs.getTimestamp(2) == null) {
327 return CertificateStatus.ISSUED;
329 return CertificateStatus.REVOKED;
335 * the date from which on the certificate should be valid. (or
336 * null if it should be valid instantly)
338 * the period for which the date should be valid. (a
339 * <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
341 * @return A job which can be used to monitor the progress of this task.
342 * @throws IOException
343 * for problems with writing the CSR/SPKAC
344 * @throws GigiApiException
345 * if the period is bogus
347 public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
348 if (getStatus() != CertificateStatus.DRAFT) {
349 throw new IllegalStateException();
352 return Job.sign(this, start, period);
356 public Job revoke(RevocationType type) {
357 if (getStatus() != CertificateStatus.ISSUED) {
358 throw new IllegalStateException();
360 return Job.revoke(this, type);
363 public Job revoke(String challenge, String signature, String message) {
364 if (getStatus() != CertificateStatus.ISSUED) {
365 throw new IllegalStateException();
367 return Job.revoke(this, challenge, signature, message);
370 public CACertificate getParent() {
371 CertificateStatus status = getStatus();
372 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
373 throw new IllegalStateException(status + " is not wanted here.");
378 public X509Certificate cert() throws IOException, GeneralSecurityException, GigiApiException {
379 CertificateStatus status = getStatus();
380 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
381 throw new IllegalStateException(status + " is not wanted here.");
383 String crtS = getAttachment(AttachmentType.CRT);
384 try (ByteArrayInputStream bais = new ByteArrayInputStream(PEM.decode("CERTIFICATE", crtS))) {
385 CertificateFactory cf = CertificateFactory.getInstance("X.509");
386 return (X509Certificate) cf.generateCertificate(bais);
390 public Certificate renew() {
398 public String getSerial() {
404 public String getDistinguishedName() {
408 public Digest getMessageDigest() {
412 public CertificateOwner getOwner() {
416 public List<SubjectAlternateName> getSANs() {
417 return Collections.unmodifiableList(sans);
420 public CertificateProfile getProfile() {
424 private static final String CONCAT = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
426 public synchronized static Certificate getBySerial(BigInteger serial) {
427 if (serial == null) {
430 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT certs.id, " + CONCAT + " as `subject`, `md`,`memid`, `profile`, `certs`.`serial`, `certs`.`description`, `certs`.`actorid` FROM `certs` LEFT JOIN `certAvas` ON `certAvas`.`certId`=`certs`.`id` WHERE `serial`=? GROUP BY `certs`.`id`")) {
431 ps.setString(1, serial.toString(16));
432 GigiResultSet rs = ps.executeQuery();
436 int id = rs.getInt(1);
437 Certificate c1 = cache.get(id);
441 Certificate certificate = new Certificate(rs);
442 cache.put(certificate);
447 private static ObjectCache<Certificate> cache = new ObjectCache<>();
449 public synchronized static Certificate getById(int id) {
450 Certificate cacheRes = cache.get(id);
451 if (cacheRes != null) {
456 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT certs.id, " + CONCAT + " as subject, md, memid, profile, certs.serial, description, actorid FROM `certs` LEFT JOIN `certAvas` ON `certAvas`.`certId`=certs.id WHERE certs.id=? GROUP BY certs.id")) {
458 GigiResultSet rs = ps.executeQuery();
463 Certificate c = new Certificate(rs);
467 } catch (IllegalArgumentException e) {
473 public static String escapeAVA(String value) {
475 return value.replace("\\", "\\\\").replace("/", "\\/");
478 public static String stringifyDN(HashMap<String, String> contents) {
479 StringBuffer res = new StringBuffer();
480 for (Entry<String, String> i : contents.entrySet()) {
481 res.append("/" + i.getKey() + "=");
482 res.append(escapeAVA(i.getValue()));
484 return res.toString();
487 public static HashMap<String, String> buildDN(String... contents) {
488 HashMap<String, String> res = new HashMap<>();
489 for (int i = 0; i + 1 < contents.length; i += 2) {
490 res.put(contents[i], contents[i + 1]);
495 public java.util.Date getRevocationDate() {
496 if (getStatus() == CertificateStatus.REVOKED) {
497 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT revoked FROM certs WHERE id=?")) {
498 prep.setInt(1, getId());
499 GigiResultSet res = prep.executeQuery();
501 return new java.util.Date(res.getTimestamp("revoked").getTime());
508 public java.util.Date getExpiryDate() {
509 if (getStatus() == CertificateStatus.ISSUED) {
510 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT expire FROM certs WHERE id=?")) {
511 prep.setInt(1, getId());
512 GigiResultSet res = prep.executeQuery();
514 return res.getTimestamp("expire");
521 public void setLoginEnabled(boolean activate) {
523 if ( !isLoginEnabled()) {
524 try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `logincerts` SET `id`=?")) {
530 try (GigiPreparedStatement prep = new GigiPreparedStatement("DELETE FROM `logincerts` WHERE `id`=?")) {
537 public boolean isLoginEnabled() {
538 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT 1 FROM `logincerts` WHERE `id`=?")) {
540 GigiResultSet res = prep.executeQuery();
545 public static Certificate[] findBySerialPattern(String serial) {
546 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `id` FROM `certs` WHERE `serial` LIKE ? GROUP BY `id` LIMIT 100", true)) {
547 prep.setString(1, serial);
548 return fetchCertsToArray(prep);
552 public static Certificate[] findBySANPattern(String request, SANType type) {
553 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT `certId` FROM `subjectAlternativeNames` WHERE `contents` LIKE ? and `type`=?::`SANType` GROUP BY `certId` LIMIT 100", true)) {
554 prep.setString(1, request);
555 prep.setEnum(2, type);
556 return fetchCertsToArray(prep);
560 private static Certificate[] fetchCertsToArray(GigiPreparedStatement prep) {
561 GigiResultSet res = prep.executeQuery();
563 Certificate[] certs = new Certificate[res.getRow()];
565 for (int i = 0; res.next(); i++) {
566 certs[i] = Certificate.getById(res.getInt(1));
571 public void addAttachment(AttachmentType tp, String data) throws GigiApiException {
572 if (getAttachment(tp) != null) {
573 throw new GigiApiException("Cannot override attachment");
576 throw new GigiApiException("Attachment must not be null");
578 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `certificateAttachment` SET `certid`=?, `type`=?::`certificateAttachmentType`, `content`=?")) {
579 ps.setInt(1, getId());
581 ps.setString(3, data);
586 public String getAttachment(AttachmentType tp) throws GigiApiException {
587 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `content` FROM `certificateAttachment` WHERE `certid`=? AND `type`=?::`certificateAttachmentType`")) {
588 ps.setInt(1, getId());
590 GigiResultSet rs = ps.executeQuery();
594 String s = rs.getString(1);
596 throw new GigiApiException("Invalid database state");
602 public void setDescription(String description) {
603 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `certs` SET `description`=? WHERE `id`=?")) {
604 ps.setString(1, description);
608 this.description = description;
611 public String getDescription() {
615 public User getActor() {
619 public static Certificate locateCertificate(String serial, String certData) throws GigiApiException {
620 if (serial != null && !serial.isEmpty()) {
621 return getBySerial(normalizeSerial(serial));
624 if (certData != null && !certData.isEmpty()) {
625 final byte[] supplied;
626 final X509Certificate c0;
628 supplied = PEM.decode("CERTIFICATE", certData);
629 c0 = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(supplied));
630 } catch (IllegalArgumentException e1) {
631 throw new GigiApiException(NOT_PARSED);
632 } catch (CertificateException e1) {
633 throw new GigiApiException(NOT_PARSED);
636 Certificate c = getBySerial(c0.getSerialNumber());
640 X509Certificate cert = c.cert();
641 if ( !Arrays.equals(supplied, cert.getEncoded())) {
645 } catch (IOException e) {
646 throw new GigiApiException(NOT_LOADED);
647 } catch (GeneralSecurityException e) {
648 throw new GigiApiException(NOT_LOADED);
651 throw new GigiApiException("No information to identify the correct certificate was provided.");
654 public static BigInteger normalizeSerial(String serial) throws GigiApiException {
655 serial = serial.replace(" ", "");
656 serial = serial.toLowerCase();
657 if (serial.matches("[0-9a-f]{2}(:[0-9a-f]{2})*")) {
658 serial = serial.replace(":", "");
661 while (idx < serial.length() && serial.charAt(idx) == '0') {
664 serial = serial.substring(idx);
665 if ( !serial.matches("[0-9a-f]+")) {
666 throw new GigiApiException("Malformed serial");
668 return new BigInteger(serial, 16);
671 public String getFingerprint(String algorithm) throws IOException, GeneralSecurityException, GigiApiException {
672 X509Certificate certx = cert();
673 return getFingerprint(certx, algorithm);
676 protected static String getFingerprint(X509Certificate cert, String algorithm) throws NoSuchAlgorithmException, CertificateEncodingException {
677 MessageDigest md = MessageDigest.getInstance(algorithm);
678 byte[] der = cert.getEncoded();
680 byte[] digest = md.digest();
681 String digestHex = DatatypeConverter.printHexBinary(digest);
682 return digestHex.toLowerCase();