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.DatabaseConnection;
21 import org.cacert.gigi.database.GigiPreparedStatement;
22 import org.cacert.gigi.database.GigiResultSet;
23 import org.cacert.gigi.util.KeyStorage;
24 import org.cacert.gigi.util.Notary;
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, String 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 GigiPreparedStatement inserter = DatabaseConnection.getInstance().prepare("INSERT INTO certs SET md=?::`mdType`, csr_type=?::`csrType`, crt_name='', memid=?, profile=?");
154 inserter.setString(1, md.toLowerCase());
155 inserter.setString(2, csrType.toString());
156 inserter.setInt(3, owner.getId());
157 inserter.setInt(4, profile.getId());
159 id = inserter.lastInsertId();
161 GigiPreparedStatement san = DatabaseConnection.getInstance().prepare("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`");
162 for (SubjectAlternateName subjectAlternateName : sans) {
164 san.setString(2, subjectAlternateName.getName());
165 san.setString(3, subjectAlternateName.getType().getOpensslName());
169 GigiPreparedStatement insertAVA = DatabaseConnection.getInstance().prepare("INSERT INTO `certAvas` SET `certId`=?, name=?, value=?");
170 insertAVA.setInt(1, id);
171 for (Entry<String, String> e : dn.entrySet()) {
172 insertAVA.setString(2, e.getKey());
173 insertAVA.setString(3, e.getValue());
176 File csrFile = KeyStorage.locateCsr(id);
177 csrName = csrFile.getPath();
178 try (FileOutputStream fos = new FileOutputStream(csrFile)) {
179 fos.write(csr.getBytes("UTF-8"));
182 GigiPreparedStatement updater = DatabaseConnection.getInstance().prepare("UPDATE `certs` SET `csr_name`=? WHERE id=?");
183 updater.setString(1, csrName);
184 updater.setInt(2, id);
191 private Certificate(GigiResultSet rs) {
192 this.id = rs.getInt("id");
193 dnString = rs.getString("subject");
194 md = rs.getString("md");
195 csrName = rs.getString("csr_name");
196 crtName = rs.getString("crt_name");
197 owner = CertificateOwner.getById(rs.getInt("memid"));
198 profile = CertificateProfile.getById(rs.getInt("profile"));
199 this.serial = rs.getString("serial");
201 GigiPreparedStatement ps2 = DatabaseConnection.getInstance().prepare("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?");
203 GigiResultSet rs2 = ps2.executeQuery();
204 sans = new LinkedList<>();
206 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
213 public enum CertificateStatus {
215 * This certificate is not in the database, has no id and only exists as
220 * The certificate has been signed. It is stored in the database.
221 * {@link Certificate#cert()} is valid.
226 * The certificate has been revoked.
231 * If this certificate cannot be updated because an error happened in
236 private CertificateStatus() {}
240 public synchronized CertificateStatus getStatus() {
241 GigiPreparedStatement searcher = DatabaseConnection.getInstance().prepare("SELECT crt_name, created, revoked, serial, caid FROM certs WHERE id=?");
242 searcher.setInt(1, id);
243 GigiResultSet rs = searcher.executeQuery();
245 throw new IllegalStateException("Certificate not in Database");
248 crtName = rs.getString(1);
249 serial = rs.getString(4);
250 if (rs.getTimestamp(2) == null) {
251 return CertificateStatus.DRAFT;
253 ca = CACertificate.getById(rs.getInt("caid"));
254 if (rs.getTimestamp(2) != null && rs.getTimestamp(3) == null) {
255 return CertificateStatus.ISSUED;
257 return CertificateStatus.REVOKED;
262 * the date from which on the certificate should be valid. (or
263 * null if it should be valid instantly)
265 * the period for which the date should be valid. (a
266 * <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
268 * @return A job which can be used to monitor the progress of this task.
269 * @throws IOException
270 * for problems with writing the CSR/SPKAC
271 * @throws GigiApiException
272 * if the period is bogus
274 public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
275 if (getStatus() != CertificateStatus.DRAFT) {
276 throw new IllegalStateException();
278 Notary.writeUserAgreement(actor, "CCA", "issue certificate", "", true, 0);
280 return Job.sign(this, start, period);
284 public Job revoke() {
285 if (getStatus() != CertificateStatus.ISSUED) {
286 throw new IllegalStateException();
288 return Job.revoke(this);
292 public CACertificate getParent() {
293 CertificateStatus status = getStatus();
294 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
295 throw new IllegalStateException(status + " is not wanted here.");
300 public X509Certificate cert() throws IOException, GeneralSecurityException {
301 CertificateStatus status = getStatus();
302 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
303 throw new IllegalStateException(status + " is not wanted here.");
305 InputStream is = null;
306 X509Certificate crt = null;
308 is = new FileInputStream(crtName);
309 CertificateFactory cf = CertificateFactory.getInstance("X.509");
310 crt = (X509Certificate) cf.generateCertificate(is);
319 public Certificate renew() {
327 public String getSerial() {
333 public String getDistinguishedName() {
337 public String getMessageDigest() {
341 public CertificateOwner getOwner() {
345 public List<SubjectAlternateName> getSANs() {
346 return Collections.unmodifiableList(sans);
349 public CertificateProfile getProfile() {
353 public synchronized static Certificate getBySerial(String serial) {
354 if (serial == null || "".equals(serial)) {
358 String concat = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
359 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("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`");
360 ps.setString(1, serial);
361 GigiResultSet rs = ps.executeQuery();
365 int id = rs.getInt(1);
366 Certificate c1 = cache.get(id);
370 Certificate certificate = new Certificate(rs);
371 cache.put(certificate);
373 } catch (IllegalArgumentException e) {
379 private static ObjectCache<Certificate> cache = new ObjectCache<>();
381 public synchronized static Certificate getById(int id) {
382 Certificate cacheRes = cache.get(id);
383 if (cacheRes != null) {
388 String concat = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
389 GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("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");
391 GigiResultSet rs = ps.executeQuery();
396 Certificate c = new Certificate(rs);
399 } catch (IllegalArgumentException e) {
405 public static String escapeAVA(String value) {
407 return value.replace("\\", "\\\\").replace("/", "\\/");
410 public static String stringifyDN(HashMap<String, String> contents) {
411 StringBuffer res = new StringBuffer();
412 for (Entry<String, String> i : contents.entrySet()) {
413 res.append("/" + i.getKey() + "=");
414 res.append(escapeAVA(i.getValue()));
416 return res.toString();
419 public static HashMap<String, String> buildDN(String... contents) {
420 HashMap<String, String> res = new HashMap<>();
421 for (int i = 0; i + 1 < contents.length; i += 2) {
422 res.put(contents[i], contents[i + 1]);
427 public java.util.Date getRevocationDate() {
428 if (getStatus() == CertificateStatus.REVOKED) {
429 GigiPreparedStatement prep = DatabaseConnection.getInstance().prepare("SELECT revoked FROM certs WHERE id=?");
430 prep.setInt(1, getId());
431 GigiResultSet res = prep.executeQuery();
434 return new java.util.Date(res.getDate("revoked").getTime());