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.util.KeyStorage;
23 import org.cacert.gigi.util.Notary;
25 public class Certificate implements IdCachable {
28 EMAIL("email"), DNS("DNS");
30 private final String opensslName;
32 private SANType(String opensslName) {
33 this.opensslName = opensslName;
36 public String getOpensslName() {
41 public static class SubjectAlternateName implements Comparable<SubjectAlternateName> {
47 public SubjectAlternateName(SANType type, String name) {
52 public String getName() {
56 public SANType getType() {
61 public int compareTo(SubjectAlternateName o) {
62 int i = type.compareTo(o.type);
66 return name.compareTo(o.name);
70 public int hashCode() {
73 result = prime * result + ((name == null) ? 0 : name.hashCode());
74 result = prime * result + ((type == null) ? 0 : type.hashCode());
79 public boolean equals(Object obj) {
86 if (getClass() != obj.getClass()) {
89 SubjectAlternateName other = (SubjectAlternateName) obj;
91 if (other.name != null) {
94 } else if ( !name.equals(other.name)) {
97 if (type != other.type) {
105 public enum CSRType {
111 private CertificateOwner owner;
113 private String serial;
117 private String csrName;
119 private String crtName;
121 private String csr = null;
123 private CSRType csrType;
125 private List<SubjectAlternateName> sans;
127 private CertificateProfile profile;
129 private HashMap<String, String> dn;
131 private String dnString;
133 private CACertificate ca;
135 public Certificate(CertificateOwner owner, User actor, HashMap<String, String> dn, Digest md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException, IOException {
136 if ( !profile.canBeIssuedBy(owner, actor)) {
137 throw new GigiApiException("You are not allowed to issue these certificates.");
141 if (dn.size() == 0) {
142 throw new GigiApiException("DN must not be empty");
144 dnString = stringifyDN(dn);
147 this.csrType = csrType;
148 this.profile = profile;
149 this.sans = Arrays.asList(sans);
150 synchronized (Certificate.class) {
152 try (GigiPreparedStatement inserter = new GigiPreparedStatement("INSERT INTO certs SET md=?::`mdType`, csr_type=?::`csrType`, crt_name='', memid=?, profile=?")) {
153 inserter.setString(1, md.toString().toLowerCase());
154 inserter.setString(2, csrType.toString());
155 inserter.setInt(3, owner.getId());
156 inserter.setInt(4, profile.getId());
158 id = inserter.lastInsertId();
161 try (GigiPreparedStatement san = new GigiPreparedStatement("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());
170 try (GigiPreparedStatement insertAVA = new GigiPreparedStatement("INSERT INTO `certAvas` SET `certId`=?, name=?, value=?")) {
171 insertAVA.setInt(1, id);
172 for (Entry<String, String> e : dn.entrySet()) {
173 insertAVA.setString(2, e.getKey());
174 insertAVA.setString(3, e.getValue());
178 File csrFile = KeyStorage.locateCsr(id);
179 csrName = csrFile.getPath();
180 try (FileOutputStream fos = new FileOutputStream(csrFile)) {
181 fos.write(csr.getBytes("UTF-8"));
183 try (GigiPreparedStatement updater = new GigiPreparedStatement("UPDATE `certs` SET `csr_name`=? WHERE id=?")) {
184 updater.setString(1, csrName);
185 updater.setInt(2, id);
193 private Certificate(GigiResultSet rs) {
194 this.id = rs.getInt("id");
195 dnString = rs.getString("subject");
196 md = Digest.valueOf(rs.getString("md").toUpperCase());
197 csrName = rs.getString("csr_name");
198 crtName = rs.getString("crt_name");
199 owner = CertificateOwner.getById(rs.getInt("memid"));
200 profile = CertificateProfile.getById(rs.getInt("profile"));
201 this.serial = rs.getString("serial");
203 try (GigiPreparedStatement ps2 = new GigiPreparedStatement("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?")) {
205 GigiResultSet rs2 = ps2.executeQuery();
206 sans = new LinkedList<>();
208 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 try (GigiPreparedStatement searcher = new GigiPreparedStatement("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;
263 * the date from which on the certificate should be valid. (or
264 * null if it should be valid instantly)
266 * the period for which the date should be valid. (a
267 * <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
269 * @return A job which can be used to monitor the progress of this task.
270 * @throws IOException
271 * for problems with writing the CSR/SPKAC
272 * @throws GigiApiException
273 * if the period is bogus
275 public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
276 if (getStatus() != CertificateStatus.DRAFT) {
277 throw new IllegalStateException();
279 Notary.writeUserAgreement(actor, "CCA", "issue certificate", "", true, 0);
281 return Job.sign(this, start, period);
285 public Job revoke() {
286 if (getStatus() != CertificateStatus.ISSUED) {
287 throw new IllegalStateException();
289 return Job.revoke(this);
293 public CACertificate getParent() {
294 CertificateStatus status = getStatus();
295 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
296 throw new IllegalStateException(status + " is not wanted here.");
301 public X509Certificate cert() throws IOException, GeneralSecurityException {
302 CertificateStatus status = getStatus();
303 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
304 throw new IllegalStateException(status + " is not wanted here.");
306 InputStream is = null;
307 X509Certificate crt = null;
309 is = new FileInputStream(crtName);
310 CertificateFactory cf = CertificateFactory.getInstance("X.509");
311 crt = (X509Certificate) cf.generateCertificate(is);
320 public Certificate renew() {
328 public String getSerial() {
334 public String getDistinguishedName() {
338 public Digest getMessageDigest() {
342 public CertificateOwner getOwner() {
346 public List<SubjectAlternateName> getSANs() {
347 return Collections.unmodifiableList(sans);
350 public CertificateProfile getProfile() {
354 public synchronized static Certificate getBySerial(String serial) {
355 if (serial == null || "".equals(serial)) {
358 String concat = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
359 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`")) {
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);
376 private static ObjectCache<Certificate> cache = new ObjectCache<>();
378 public synchronized static Certificate getById(int id) {
379 Certificate cacheRes = cache.get(id);
380 if (cacheRes != null) {
385 String concat = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
386 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")) {
388 GigiResultSet rs = ps.executeQuery();
393 Certificate c = new Certificate(rs);
397 } catch (IllegalArgumentException e) {
403 public static String escapeAVA(String value) {
405 return value.replace("\\", "\\\\").replace("/", "\\/");
408 public static String stringifyDN(HashMap<String, String> contents) {
409 StringBuffer res = new StringBuffer();
410 for (Entry<String, String> i : contents.entrySet()) {
411 res.append("/" + i.getKey() + "=");
412 res.append(escapeAVA(i.getValue()));
414 return res.toString();
417 public static HashMap<String, String> buildDN(String... contents) {
418 HashMap<String, String> res = new HashMap<>();
419 for (int i = 0; i + 1 < contents.length; i += 2) {
420 res.put(contents[i], contents[i + 1]);
425 public java.util.Date getRevocationDate() {
426 if (getStatus() == CertificateStatus.REVOKED) {
427 try (GigiPreparedStatement prep = new GigiPreparedStatement("SELECT revoked FROM certs WHERE id=?")) {
428 prep.setInt(1, getId());
429 GigiResultSet res = prep.executeQuery();
431 return new java.util.Date(res.getDate("revoked").getTime());