]> WPIA git - gigi.git/blob - src/org/cacert/gigi/Certificate.java
Enhance certificate issuance form.
[gigi.git] / src / org / cacert / gigi / Certificate.java
1 package org.cacert.gigi;
2
3 import java.io.File;
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;
11 import java.sql.PreparedStatement;
12 import java.sql.ResultSet;
13 import java.sql.SQLException;
14 import java.util.Arrays;
15 import java.util.Collections;
16 import java.util.LinkedList;
17 import java.util.List;
18
19 import org.cacert.gigi.database.DatabaseConnection;
20 import org.cacert.gigi.util.Job;
21 import org.cacert.gigi.util.Job.JobType;
22 import org.cacert.gigi.util.KeyStorage;
23 import org.cacert.gigi.util.Notary;
24
25 public class Certificate {
26
27     public enum SANType {
28         EMAIL("email"), DNS("DNS");
29
30         private final String opensslName;
31
32         private SANType(String opensslName) {
33             this.opensslName = opensslName;
34         }
35
36         public String getOpensslName() {
37             return opensslName;
38         }
39     }
40
41     public static class SubjectAlternateName implements Comparable<SubjectAlternateName> {
42
43         private SANType type;
44
45         private String name;
46
47         public SubjectAlternateName(SANType type, String name) {
48             this.type = type;
49             this.name = name;
50         }
51
52         public String getName() {
53             return name;
54         }
55
56         public SANType getType() {
57             return type;
58         }
59
60         @Override
61         public int compareTo(SubjectAlternateName o) {
62             int i = type.compareTo(o.type);
63             if (i != 0) {
64                 return i;
65             }
66             return name.compareTo(o.name);
67         }
68
69         @Override
70         public int hashCode() {
71             final int prime = 31;
72             int result = 1;
73             result = prime * result + ((name == null) ? 0 : name.hashCode());
74             result = prime * result + ((type == null) ? 0 : type.hashCode());
75             return result;
76         }
77
78         @Override
79         public boolean equals(Object obj) {
80             if (this == obj) {
81                 return true;
82             }
83             if (obj == null) {
84                 return false;
85             }
86             if (getClass() != obj.getClass()) {
87                 return false;
88             }
89             SubjectAlternateName other = (SubjectAlternateName) obj;
90             if (name == null) {
91                 if (other.name != null) {
92                     return false;
93                 }
94             } else if ( !name.equals(other.name)) {
95                 return false;
96             }
97             if (type != other.type) {
98                 return false;
99             }
100             return true;
101         }
102
103     }
104
105     public enum CSRType {
106         CSR, SPKAC;
107     }
108
109     private int id;
110
111     private int ownerId;
112
113     private String serial;
114
115     private String dn;
116
117     private String md;
118
119     private String csrName;
120
121     private String crtName;
122
123     private String csr = null;
124
125     private CSRType csrType;
126
127     private List<SubjectAlternateName> sans;
128
129     private CertificateProfile profile;
130
131     public Certificate(int ownerId, String dn, String md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) {
132         this.ownerId = ownerId;
133         this.dn = dn;
134         this.md = md;
135         this.csr = csr;
136         this.csrType = csrType;
137         this.profile = profile;
138         this.sans = Arrays.asList(sans);
139     }
140
141     private Certificate(String serial) {
142         try {
143             PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id,subject, md, csr_name, crt_name,memid, profile FROM `certs` WHERE serial=?");
144             ps.setString(1, serial);
145             ResultSet rs = ps.executeQuery();
146             if ( !rs.next()) {
147                 throw new IllegalArgumentException("Invalid mid " + serial);
148             }
149             this.id = rs.getInt(1);
150             dn = rs.getString(2);
151             md = rs.getString(3);
152             csrName = rs.getString(4);
153             crtName = rs.getString(5);
154             ownerId = rs.getInt(6);
155             profile = CertificateProfile.getById(rs.getInt(7));
156             this.serial = serial;
157
158             PreparedStatement ps2 = DatabaseConnection.getInstance().prepare("SELECT contents, type FROM `subjectAlternativeNames` WHERE certId=?");
159             ps2.setInt(1, id);
160             ResultSet rs2 = ps2.executeQuery();
161             sans = new LinkedList<>();
162             while (rs2.next()) {
163                 sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
164             }
165             rs2.close();
166
167             rs.close();
168         } catch (SQLException e) {
169             e.printStackTrace();
170         }
171     }
172
173     public enum CertificateStatus {
174         /**
175          * This certificate is not in the database, has no id and only exists as
176          * this java object.
177          */
178         DRAFT(),
179         /**
180          * The certificate has been signed. It is stored in the database.
181          * {@link Certificate#cert()} is valid.
182          */
183         ISSUED(),
184
185         /**
186          * The certificate has been revoked.
187          */
188         REVOKED(),
189
190         /**
191          * If this certificate cannot be updated because an error happened in
192          * the signer.
193          */
194         ERROR();
195
196         private CertificateStatus() {}
197
198     }
199
200     public CertificateStatus getStatus() throws SQLException {
201         if (id == 0) {
202             return CertificateStatus.DRAFT;
203         }
204         PreparedStatement searcher = DatabaseConnection.getInstance().prepare("SELECT crt_name, created, revoked, serial FROM certs WHERE id=?");
205         searcher.setInt(1, id);
206         ResultSet rs = searcher.executeQuery();
207         if ( !rs.next()) {
208             throw new IllegalStateException("Certificate not in Database");
209         }
210
211         crtName = rs.getString(1);
212         serial = rs.getString(4);
213         if (rs.getTime(2) == null) {
214             return CertificateStatus.DRAFT;
215         }
216         if (rs.getTime(2) != null && rs.getTime(3) == null) {
217             return CertificateStatus.ISSUED;
218         }
219         return CertificateStatus.REVOKED;
220     }
221
222     public Job issue() throws IOException, SQLException {
223         if (getStatus() != CertificateStatus.DRAFT) {
224             throw new IllegalStateException();
225         }
226         Notary.writeUserAgreement(ownerId, "CCA", "issue certificate", "", true, 0);
227
228         PreparedStatement inserter = DatabaseConnection.getInstance().prepare("INSERT INTO certs SET md=?, subject=?, csr_type=?, crt_name='', memid=?, profile=?");
229         inserter.setString(1, md);
230         inserter.setString(2, dn);
231         inserter.setString(3, csrType.toString());
232         inserter.setInt(4, ownerId);
233         inserter.setInt(5, profile.getId());
234         inserter.execute();
235         id = DatabaseConnection.lastInsertId(inserter);
236         File csrFile = KeyStorage.locateCsr(id);
237         csrName = csrFile.getPath();
238         FileOutputStream fos = new FileOutputStream(csrFile);
239         fos.write(csr.getBytes());
240         fos.close();
241
242         // TODO draft to insert SANs
243         PreparedStatement san = DatabaseConnection.getInstance().prepare("INSERT INTO subjectAlternativeNames SET certId=?, contents=?, type=?");
244         for (SubjectAlternateName subjectAlternateName : sans) {
245             san.setInt(1, id);
246             san.setString(2, subjectAlternateName.getName());
247             san.setString(3, subjectAlternateName.getType().getOpensslName());
248             san.execute();
249         }
250
251         PreparedStatement updater = DatabaseConnection.getInstance().prepare("UPDATE certs SET csr_name=? WHERE id=?");
252         updater.setString(1, csrName);
253         updater.setInt(2, id);
254         updater.execute();
255         return Job.submit(this, JobType.SIGN);
256
257     }
258
259     public Job revoke() throws SQLException {
260         if (getStatus() != CertificateStatus.ISSUED) {
261             throw new IllegalStateException();
262         }
263         return Job.submit(this, JobType.REVOKE);
264
265     }
266
267     public X509Certificate cert() throws IOException, GeneralSecurityException, SQLException {
268         CertificateStatus status = getStatus();
269         if (status != CertificateStatus.ISSUED) {
270             throw new IllegalStateException(status + " is not wanted here.");
271         }
272         InputStream is = null;
273         X509Certificate crt = null;
274         try {
275             is = new FileInputStream(crtName);
276             CertificateFactory cf = CertificateFactory.getInstance("X.509");
277             crt = (X509Certificate) cf.generateCertificate(is);
278         } finally {
279             if (is != null) {
280                 is.close();
281             }
282         }
283         return crt;
284     }
285
286     public Certificate renew() {
287         return null;
288     }
289
290     public int getId() {
291         return id;
292     }
293
294     public String getSerial() {
295         try {
296             getStatus();
297         } catch (SQLException e) {
298             e.printStackTrace();
299         } // poll changes
300         return serial;
301     }
302
303     public String getDistinguishedName() {
304         return dn;
305     }
306
307     public String getMessageDigest() {
308         return md;
309     }
310
311     public int getOwnerId() {
312         return ownerId;
313     }
314
315     public List<SubjectAlternateName> getSANs() {
316         return Collections.unmodifiableList(sans);
317     }
318
319     public CertificateProfile getProfile() {
320         return profile;
321     }
322
323     public static Certificate getBySerial(String serial) {
324         // TODO caching?
325         try {
326             return new Certificate(serial);
327         } catch (IllegalArgumentException e) {
328
329         }
330         return null;
331     }
332
333 }