1 package org.cacert.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.Map.Entry;
19 import org.cacert.gigi.GigiApiException;
20 import org.cacert.gigi.database.GigiPreparedStatement;
21 import org.cacert.gigi.database.GigiResultSet;
22 import org.cacert.gigi.output.template.Outputable;
23 import org.cacert.gigi.output.template.TranslateCommand;
24 import org.cacert.gigi.util.KeyStorage;
26 public class Certificate implements IdCachable {
29 EMAIL("email"), DNS("DNS");
31 private final String opensslName;
33 private SANType(String opensslName) {
34 this.opensslName = opensslName;
37 public String getOpensslName() {
42 public static class SubjectAlternateName implements Comparable<SubjectAlternateName> {
48 public SubjectAlternateName(SANType type, String name) {
53 public String getName() {
57 public SANType getType() {
62 public int compareTo(SubjectAlternateName o) {
63 int i = type.compareTo(o.type);
67 return name.compareTo(o.name);
71 public int hashCode() {
74 result = prime * result + ((name == null) ? 0 : name.hashCode());
75 result = prime * result + ((type == null) ? 0 : type.hashCode());
80 public boolean equals(Object obj) {
87 if (getClass() != obj.getClass()) {
90 SubjectAlternateName other = (SubjectAlternateName) obj;
92 if (other.name != null) {
95 } else if ( !name.equals(other.name)) {
98 if (type != other.type) {
106 public enum CSRType {
112 private CertificateOwner owner;
114 private String serial;
118 private String csrName;
120 private String crtName;
122 private String csr = null;
124 private CSRType csrType;
126 private List<SubjectAlternateName> sans;
128 private CertificateProfile profile;
130 private HashMap<String, String> dn;
132 private String dnString;
134 private CACertificate ca;
136 public Certificate(CertificateOwner owner, User actor, HashMap<String, String> dn, Digest md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException, IOException {
137 if ( !profile.canBeIssuedBy(owner, actor)) {
138 throw new GigiApiException("You are not allowed to issue these certificates.");
142 if (dn.size() == 0) {
143 throw new GigiApiException("DN must not be empty.");
145 dnString = stringifyDN(dn);
148 this.csrType = csrType;
149 this.profile = profile;
150 this.sans = Arrays.asList(sans);
151 synchronized (Certificate.class) {
153 try (GigiPreparedStatement inserter = new GigiPreparedStatement("INSERT INTO certs SET md=?::`mdType`, csr_type=?::`csrType`, crt_name='', memid=?, profile=?")) {
154 inserter.setString(1, md.toString().toLowerCase());
155 inserter.setString(2, this.csrType.toString());
156 inserter.setInt(3, owner.getId());
157 inserter.setInt(4, profile.getId());
159 id = inserter.lastInsertId();
162 try (GigiPreparedStatement san = new GigiPreparedStatement("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`")) {
163 for (SubjectAlternateName subjectAlternateName : sans) {
165 san.setString(2, subjectAlternateName.getName());
166 san.setString(3, subjectAlternateName.getType().getOpensslName());
171 try (GigiPreparedStatement insertAVA = new GigiPreparedStatement("INSERT INTO `certAvas` SET `certId`=?, name=?, value=?")) {
172 insertAVA.setInt(1, id);
173 for (Entry<String, String> e : this.dn.entrySet()) {
174 insertAVA.setString(2, e.getKey());
175 insertAVA.setString(3, e.getValue());
179 File csrFile = KeyStorage.locateCsr(id);
180 csrName = csrFile.getPath();
181 try (FileOutputStream fos = new FileOutputStream(csrFile)) {
182 fos.write(this.csr.getBytes("UTF-8"));
184 try (GigiPreparedStatement updater = new GigiPreparedStatement("UPDATE `certs` SET `csr_name`=? WHERE id=?")) {
185 updater.setString(1, csrName);
186 updater.setInt(2, id);
194 private Certificate(GigiResultSet rs) {
195 this.id = rs.getInt("id");
196 dnString = rs.getString("subject");
197 md = Digest.valueOf(rs.getString("md").toUpperCase());
198 csrName = rs.getString("csr_name");
199 crtName = rs.getString("crt_name");
200 owner = CertificateOwner.getById(rs.getInt("memid"));
201 profile = CertificateProfile.getById(rs.getInt("profile"));
202 this.serial = rs.getString("serial");
204 try (GigiPreparedStatement ps2 = new GigiPreparedStatement("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?")) {
206 GigiResultSet rs2 = ps2.executeQuery();
207 sans = new LinkedList<>();
209 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
214 public enum CertificateStatus {
216 * This certificate is not in the database, has no id and only exists as
221 * The certificate has been signed. It is stored in the database.
222 * {@link Certificate#cert()} is valid.
227 * The certificate has been revoked.
232 * If this certificate cannot be updated because an error happened in
237 private final Outputable name;
239 private CertificateStatus(String codename) {
240 this.name = new TranslateCommand(codename);
244 public Outputable getName() {
250 public synchronized CertificateStatus getStatus() {
251 try (GigiPreparedStatement searcher = new GigiPreparedStatement("SELECT crt_name, created, revoked, serial, caid FROM certs WHERE id=?")) {
252 searcher.setInt(1, id);
253 GigiResultSet rs = searcher.executeQuery();
255 throw new IllegalStateException("Certificate not in Database");
258 crtName = rs.getString(1);
259 serial = rs.getString(4);
260 if (rs.getTimestamp(2) == null) {
261 return CertificateStatus.DRAFT;
263 ca = CACertificate.getById(rs.getInt("caid"));
264 if (rs.getTimestamp(2) != null && rs.getTimestamp(3) == null) {
265 return CertificateStatus.ISSUED;
267 return CertificateStatus.REVOKED;
273 * the date from which on the certificate should be valid. (or
274 * null if it should be valid instantly)
276 * the period for which the date should be valid. (a
277 * <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
279 * @return A job which can be used to monitor the progress of this task.
280 * @throws IOException
281 * for problems with writing the CSR/SPKAC
282 * @throws GigiApiException
283 * if the period is bogus
285 public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
286 if (getStatus() != CertificateStatus.DRAFT) {
287 throw new IllegalStateException();
290 return Job.sign(this, start, period);
294 public Job revoke() {
295 if (getStatus() != CertificateStatus.ISSUED) {
296 throw new IllegalStateException();
298 return Job.revoke(this);
302 public CACertificate getParent() {
303 CertificateStatus status = getStatus();
304 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
305 throw new IllegalStateException(status + " is not wanted here.");
310 public X509Certificate cert() throws IOException, GeneralSecurityException {
311 CertificateStatus status = getStatus();
312 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
313 throw new IllegalStateException(status + " is not wanted here.");
315 InputStream is = null;
316 X509Certificate crt = null;
318 is = new FileInputStream(crtName);
319 CertificateFactory cf = CertificateFactory.getInstance("X.509");
320 crt = (X509Certificate) cf.generateCertificate(is);
329 public Certificate renew() {
337 public String getSerial() {
343 public String getDistinguishedName() {
347 public Digest getMessageDigest() {
351 public CertificateOwner getOwner() {
355 public List<SubjectAlternateName> getSANs() {
356 return Collections.unmodifiableList(sans);
359 public CertificateProfile getProfile() {
363 public synchronized static Certificate getBySerial(String serial) {
364 if (serial == null || "".equals(serial)) {
367 String concat = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
368 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`")) {
369 ps.setString(1, serial);
370 GigiResultSet rs = ps.executeQuery();
374 int id = rs.getInt(1);
375 Certificate c1 = cache.get(id);
379 Certificate certificate = new Certificate(rs);
380 cache.put(certificate);
385 private static ObjectCache<Certificate> cache = new ObjectCache<>();
387 public synchronized static Certificate getById(int id) {
388 Certificate cacheRes = cache.get(id);
389 if (cacheRes != null) {
394 String concat = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
395 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")) {
397 GigiResultSet rs = ps.executeQuery();
402 Certificate c = new Certificate(rs);
406 } catch (IllegalArgumentException e) {
412 public static String escapeAVA(String value) {
414 return value.replace("\\", "\\\\").replace("/", "\\/");
417 public static String stringifyDN(HashMap<String, String> contents) {
418 StringBuffer res = new StringBuffer();
419 for (Entry<String, String> i : contents.entrySet()) {
420 res.append("/" + i.getKey() + "=");
421 res.append(escapeAVA(i.getValue()));
423 return res.toString();
426 public static HashMap<String, String> buildDN(String... contents) {
427 HashMap<String, String> res = new HashMap<>();
428 for (int i = 0; i + 1 < contents.length; i += 2) {
429 res.put(contents[i], contents[i + 1]);
434 public java.util.Date getRevocationDate() {
435 if (getStatus() == CertificateStatus.REVOKED) {
436 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT revoked FROM certs WHERE id=?")) {
437 prep.setInt(1, getId());
438 GigiResultSet res = prep.executeQuery();
440 return new java.util.Date(res.getDate("revoked").getTime());
447 public void setLoginEnabled(boolean activate) {
449 if ( !isLoginEnabled()) {
450 try (GigiPreparedStatement prep = new GigiPreparedStatement("INSERT INTO `logincerts` SET `id`=?")) {
456 try (GigiPreparedStatement prep = new GigiPreparedStatement("DELETE FROM `logincerts` WHERE `id`=?")) {
463 public boolean isLoginEnabled() {
464 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT 1 FROM `logincerts` WHERE `id`=?")) {
466 GigiResultSet res = prep.executeQuery();