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 {
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 {
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(User owner, HashMap<String, String> dn, String md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException {
137 if ( !profile.canBeIssuedBy(owner)) {
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);
153 private Certificate(GigiResultSet rs) {
156 throw new IllegalArgumentException("Invalid mid " + serial);
158 this.id = rs.getInt("id");
159 dnString = rs.getString("subject");
160 md = rs.getString("md");
161 csrName = rs.getString("csr_name");
162 crtName = rs.getString("crt_name");
163 owner = User.getById(rs.getInt("memid"));
164 profile = CertificateProfile.getById(rs.getInt("profile"));
165 this.serial = rs.getString("serial");
167 GigiPreparedStatement ps2 = DatabaseConnection.getInstance().prepare("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?");
169 GigiResultSet rs2 = ps2.executeQuery();
170 sans = new LinkedList<>();
172 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
179 public enum CertificateStatus {
181 * This certificate is not in the database, has no id and only exists as
186 * The certificate has been signed. It is stored in the database.
187 * {@link Certificate#cert()} is valid.
192 * The certificate has been revoked.
197 * If this certificate cannot be updated because an error happened in
202 private CertificateStatus() {}
206 public synchronized CertificateStatus getStatus() {
208 return CertificateStatus.DRAFT;
210 GigiPreparedStatement searcher = DatabaseConnection.getInstance().prepare("SELECT crt_name, created, revoked, serial, caid FROM certs WHERE id=?");
211 searcher.setInt(1, id);
212 GigiResultSet rs = searcher.executeQuery();
214 throw new IllegalStateException("Certificate not in Database");
217 crtName = rs.getString(1);
218 serial = rs.getString(4);
219 if (rs.getTimestamp(2) == null) {
220 return CertificateStatus.DRAFT;
222 ca = CACertificate.getById(rs.getInt("caid"));
223 if (rs.getTimestamp(2) != null && rs.getTimestamp(3) == null) {
224 return CertificateStatus.ISSUED;
226 return CertificateStatus.REVOKED;
231 * the date from which on the certificate should be valid. (or
232 * null if it should be valid instantly)
234 * the period for which the date should be valid. (a
235 * <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
237 * @return A job which can be used to monitor the progress of this task.
238 * @throws IOException
239 * for problems with writing the CSR/SPKAC
240 * @throws GigiApiException
241 * if the period is bogus
243 public Job issue(Date start, String period) throws IOException, GigiApiException {
244 if (getStatus() != CertificateStatus.DRAFT) {
245 throw new IllegalStateException();
247 Notary.writeUserAgreement(owner, "CCA", "issue certificate", "", true, 0);
249 GigiPreparedStatement inserter = DatabaseConnection.getInstance().prepare("INSERT INTO certs SET md=?::`mdType`, csr_type=?::`csrType`, crt_name='', memid=?, profile=?");
250 inserter.setString(1, md.toLowerCase());
251 inserter.setString(2, csrType.toString());
252 inserter.setInt(3, owner.getId());
253 inserter.setInt(4, profile.getId());
255 id = inserter.lastInsertId();
257 GigiPreparedStatement san = DatabaseConnection.getInstance().prepare("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`");
258 for (SubjectAlternateName subjectAlternateName : sans) {
260 san.setString(2, subjectAlternateName.getName());
261 san.setString(3, subjectAlternateName.getType().getOpensslName());
265 GigiPreparedStatement insertAVA = DatabaseConnection.getInstance().prepare("INSERT INTO `certAvas` SET `certId`=?, name=?, value=?");
266 insertAVA.setInt(1, id);
267 for (Entry<String, String> e : dn.entrySet()) {
268 insertAVA.setString(2, e.getKey());
269 insertAVA.setString(3, e.getValue());
272 File csrFile = KeyStorage.locateCsr(id);
273 csrName = csrFile.getPath();
274 try (FileOutputStream fos = new FileOutputStream(csrFile)) {
275 fos.write(csr.getBytes("UTF-8"));
278 GigiPreparedStatement updater = DatabaseConnection.getInstance().prepare("UPDATE `certs` SET `csr_name`=? WHERE id=?");
279 updater.setString(1, csrName);
280 updater.setInt(2, id);
282 return Job.sign(this, start, period);
286 public Job revoke() {
287 if (getStatus() != CertificateStatus.ISSUED) {
288 throw new IllegalStateException();
290 return Job.revoke(this);
294 public CACertificate getParent() {
295 CertificateStatus status = getStatus();
296 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
297 throw new IllegalStateException(status + " is not wanted here.");
302 public X509Certificate cert() throws IOException, GeneralSecurityException {
303 CertificateStatus status = getStatus();
304 if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
305 throw new IllegalStateException(status + " is not wanted here.");
307 InputStream is = null;
308 X509Certificate crt = null;
310 is = new FileInputStream(crtName);
311 CertificateFactory cf = CertificateFactory.getInstance("X.509");
312 crt = (X509Certificate) cf.generateCertificate(is);
321 public Certificate renew() {
329 public String getSerial() {
335 public String getDistinguishedName() {
339 public String getMessageDigest() {
343 public User getOwner() {
347 public List<SubjectAlternateName> getSANs() {
348 return Collections.unmodifiableList(sans);
351 public CertificateProfile getProfile() {
355 public static Certificate getBySerial(String serial) {
356 if (serial == null || "".equals(serial)) {
361 String concat = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
362 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`");
363 ps.setString(1, serial);
364 GigiResultSet rs = ps.executeQuery();
365 return new Certificate(rs);
366 } catch (IllegalArgumentException e) {
372 public static Certificate getById(int id) {
376 String concat = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
377 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");
379 GigiResultSet rs = ps.executeQuery();
381 return new Certificate(rs);
382 } catch (IllegalArgumentException e) {
388 public static String escapeAVA(String value) {
390 return value.replace("\\", "\\\\").replace("/", "\\/");
393 public static String stringifyDN(HashMap<String, String> contents) {
394 StringBuffer res = new StringBuffer();
395 for (Entry<String, String> i : contents.entrySet()) {
396 res.append("/" + i.getKey() + "=");
397 res.append(escapeAVA(i.getValue()));
399 return res.toString();
402 public static HashMap<String, String> buildDN(String... contents) {
403 HashMap<String, String> res = new HashMap<>();
404 for (int i = 0; i + 1 < contents.length; i += 2) {
405 res.put(contents[i], contents[i + 1]);
410 public java.util.Date getRevocationDate() {
411 if (getStatus() == CertificateStatus.REVOKED) {
412 GigiPreparedStatement prep = DatabaseConnection.getInstance().prepare("SELECT revoked FROM certs WHERE id=?");
413 prep.setInt(1, getId());
414 GigiResultSet res = prep.executeQuery();
417 return new java.util.Date(res.getDate("revoked").getTime());