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.sql.PreparedStatement;
13 import java.sql.ResultSet;
14 import java.sql.SQLException;
15 import java.util.Arrays;
16 import java.util.Collections;
17 import java.util.LinkedList;
18 import java.util.List;
20 import org.cacert.gigi.GigiApiException;
21 import org.cacert.gigi.database.DatabaseConnection;
22 import org.cacert.gigi.util.Job;
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;
120 private String csrName;
122 private String crtName;
124 private String csr = null;
126 private CSRType csrType;
128 private List<SubjectAlternateName> sans;
130 private CertificateProfile profile;
132 public Certificate(int ownerId, String dn, String md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) {
133 this.ownerId = ownerId;
137 this.csrType = csrType;
138 this.profile = profile;
139 this.sans = Arrays.asList(sans);
142 private Certificate(String serial) {
144 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id,subject, md, csr_name, crt_name,memid, profile FROM `certs` WHERE serial=?");
145 ps.setString(1, serial);
146 ResultSet rs = ps.executeQuery();
148 throw new IllegalArgumentException("Invalid mid " + serial);
150 this.id = rs.getInt(1);
151 dn = rs.getString(2);
152 md = rs.getString(3);
153 csrName = rs.getString(4);
154 crtName = rs.getString(5);
155 ownerId = rs.getInt(6);
156 profile = CertificateProfile.getById(rs.getInt(7));
157 this.serial = serial;
159 PreparedStatement ps2 = DatabaseConnection.getInstance().prepare("SELECT contents, type FROM `subjectAlternativeNames` WHERE certId=?");
161 ResultSet rs2 = ps2.executeQuery();
162 sans = new LinkedList<>();
164 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
169 } catch (SQLException e) {
174 public enum CertificateStatus {
176 * This certificate is not in the database, has no id and only exists as
181 * The certificate has been signed. It is stored in the database.
182 * {@link Certificate#cert()} is valid.
187 * The certificate has been revoked.
192 * If this certificate cannot be updated because an error happened in
197 private CertificateStatus() {}
201 public CertificateStatus getStatus() throws SQLException {
203 return CertificateStatus.DRAFT;
205 PreparedStatement searcher = DatabaseConnection.getInstance().prepare("SELECT crt_name, created, revoked, serial FROM certs WHERE id=?");
206 searcher.setInt(1, id);
207 ResultSet rs = searcher.executeQuery();
209 throw new IllegalStateException("Certificate not in Database");
212 crtName = rs.getString(1);
213 serial = rs.getString(4);
214 if (rs.getTime(2) == null) {
215 return CertificateStatus.DRAFT;
217 if (rs.getTime(2) != null && rs.getTime(3) == null) {
218 return CertificateStatus.ISSUED;
220 return CertificateStatus.REVOKED;
225 * the date from which on the certificate should be valid. (or
226 * null if it should be valid instantly)
228 * the period for which the date should be valid. (a
229 * <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
231 * @return A job which can be used to monitor the progress of this task.
232 * @throws IOException
233 * for problems with writing the CSR/SPKAC
234 * @throws SQLException
235 * for problems with writing to the DB
236 * @throws GigiApiException
237 * if the period is bogus
239 public Job issue(Date start, String period) throws IOException, SQLException, GigiApiException {
240 if (getStatus() != CertificateStatus.DRAFT) {
241 throw new IllegalStateException();
243 Notary.writeUserAgreement(ownerId, "CCA", "issue certificate", "", true, 0);
245 PreparedStatement inserter = DatabaseConnection.getInstance().prepare("INSERT INTO certs SET md=?, subject=?, csr_type=?, crt_name='', memid=?, profile=?");
246 inserter.setString(1, md);
247 inserter.setString(2, dn);
248 inserter.setString(3, csrType.toString());
249 inserter.setInt(4, ownerId);
250 inserter.setInt(5, profile.getId());
252 id = DatabaseConnection.lastInsertId(inserter);
253 File csrFile = KeyStorage.locateCsr(id);
254 csrName = csrFile.getPath();
255 FileOutputStream fos = new FileOutputStream(csrFile);
256 fos.write(csr.getBytes());
259 // TODO draft to insert SANs
260 PreparedStatement san = DatabaseConnection.getInstance().prepare("INSERT INTO subjectAlternativeNames SET certId=?, contents=?, type=?");
261 for (SubjectAlternateName subjectAlternateName : sans) {
263 san.setString(2, subjectAlternateName.getName());
264 san.setString(3, subjectAlternateName.getType().getOpensslName());
268 PreparedStatement updater = DatabaseConnection.getInstance().prepare("UPDATE certs SET csr_name=? WHERE id=?");
269 updater.setString(1, csrName);
270 updater.setInt(2, id);
272 return Job.sign(this, start, period);
276 public Job revoke() throws SQLException {
277 if (getStatus() != CertificateStatus.ISSUED) {
278 throw new IllegalStateException();
280 return Job.revoke(this);
284 public X509Certificate cert() throws IOException, GeneralSecurityException, SQLException {
285 CertificateStatus status = getStatus();
286 if (status != CertificateStatus.ISSUED) {
287 throw new IllegalStateException(status + " is not wanted here.");
289 InputStream is = null;
290 X509Certificate crt = null;
292 is = new FileInputStream(crtName);
293 CertificateFactory cf = CertificateFactory.getInstance("X.509");
294 crt = (X509Certificate) cf.generateCertificate(is);
303 public Certificate renew() {
311 public String getSerial() {
314 } catch (SQLException e) {
320 public String getDistinguishedName() {
324 public String getMessageDigest() {
328 public int getOwnerId() {
332 public List<SubjectAlternateName> getSANs() {
333 return Collections.unmodifiableList(sans);
336 public CertificateProfile getProfile() {
340 public static Certificate getBySerial(String serial) {
343 return new Certificate(serial);
344 } catch (IllegalArgumentException e) {