]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/Certificate.java
0c63c2cdee088add0a37f51154cd01a41863d76d
[gigi.git] / src / org / cacert / gigi / dbObjects / Certificate.java
1 package org.cacert.gigi.dbObjects;
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.Date;
12 import java.util.Arrays;
13 import java.util.Collections;
14 import java.util.LinkedList;
15 import java.util.List;
16
17 import org.cacert.gigi.GigiApiException;
18 import org.cacert.gigi.database.DatabaseConnection;
19 import org.cacert.gigi.database.GigiPreparedStatement;
20 import org.cacert.gigi.database.GigiResultSet;
21 import org.cacert.gigi.util.Job;
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 User owner;
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(User owner, String dn, String md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException {
132         if ( !owner.canIssue(profile)) {
133             throw new GigiApiException("You are not allowed to issue these certificates.");
134         }
135         this.owner = owner;
136         this.dn = dn;
137         this.md = md;
138         this.csr = csr;
139         this.csrType = csrType;
140         this.profile = profile;
141         this.sans = Arrays.asList(sans);
142     }
143
144     private Certificate(String serial) {
145         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id,subject, md, csr_name, crt_name,memid, profile FROM `certs` WHERE serial=?");
146         ps.setString(1, serial);
147         GigiResultSet rs = ps.executeQuery();
148         if ( !rs.next()) {
149             throw new IllegalArgumentException("Invalid mid " + serial);
150         }
151         this.id = rs.getInt(1);
152         dn = rs.getString(2);
153         md = rs.getString(3);
154         csrName = rs.getString(4);
155         crtName = rs.getString(5);
156         owner = User.getById(rs.getInt(6));
157         profile = CertificateProfile.getById(rs.getInt(7));
158         this.serial = serial;
159
160         GigiPreparedStatement ps2 = DatabaseConnection.getInstance().prepare("SELECT contents, type FROM `subjectAlternativeNames` WHERE certId=?");
161         ps2.setInt(1, id);
162         GigiResultSet rs2 = ps2.executeQuery();
163         sans = new LinkedList<>();
164         while (rs2.next()) {
165             sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
166         }
167         rs2.close();
168
169         rs.close();
170     }
171
172     public enum CertificateStatus {
173         /**
174          * This certificate is not in the database, has no id and only exists as
175          * this java object.
176          */
177         DRAFT(),
178         /**
179          * The certificate has been signed. It is stored in the database.
180          * {@link Certificate#cert()} is valid.
181          */
182         ISSUED(),
183
184         /**
185          * The certificate has been revoked.
186          */
187         REVOKED(),
188
189         /**
190          * If this certificate cannot be updated because an error happened in
191          * the signer.
192          */
193         ERROR();
194
195         private CertificateStatus() {}
196
197     }
198
199     public CertificateStatus getStatus() {
200         if (id == 0) {
201             return CertificateStatus.DRAFT;
202         }
203         GigiPreparedStatement searcher = DatabaseConnection.getInstance().prepare("SELECT crt_name, created, revoked, serial FROM certs WHERE id=?");
204         searcher.setInt(1, id);
205         GigiResultSet rs = searcher.executeQuery();
206         if ( !rs.next()) {
207             throw new IllegalStateException("Certificate not in Database");
208         }
209
210         crtName = rs.getString(1);
211         serial = rs.getString(4);
212         if (rs.getTime(2) == null) {
213             return CertificateStatus.DRAFT;
214         }
215         if (rs.getTime(2) != null && rs.getTime(3) == null) {
216             return CertificateStatus.ISSUED;
217         }
218         return CertificateStatus.REVOKED;
219     }
220
221     /**
222      * @param start
223      *            the date from which on the certificate should be valid. (or
224      *            null if it should be valid instantly)
225      * @param period
226      *            the period for which the date should be valid. (a
227      *            <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
228      *            months)
229      * @return A job which can be used to monitor the progress of this task.
230      * @throws IOException
231      *             for problems with writing the CSR/SPKAC
232      * @throws GigiApiException
233      *             if the period is bogus
234      */
235     public Job issue(Date start, String period) throws IOException, GigiApiException {
236         if (getStatus() != CertificateStatus.DRAFT) {
237             throw new IllegalStateException();
238         }
239         Notary.writeUserAgreement(owner, "CCA", "issue certificate", "", true, 0);
240
241         GigiPreparedStatement inserter = DatabaseConnection.getInstance().prepare("INSERT INTO certs SET md=?, subject=?, csr_type=?, crt_name='', memid=?, profile=?");
242         inserter.setString(1, md);
243         inserter.setString(2, dn);
244         inserter.setString(3, csrType.toString());
245         inserter.setInt(4, owner.getId());
246         inserter.setInt(5, profile.getId());
247         inserter.execute();
248         id = inserter.lastInsertId();
249         File csrFile = KeyStorage.locateCsr(id);
250         csrName = csrFile.getPath();
251         FileOutputStream fos = new FileOutputStream(csrFile);
252         fos.write(csr.getBytes());
253         fos.close();
254
255         // TODO draft to insert SANs
256         GigiPreparedStatement san = DatabaseConnection.getInstance().prepare("INSERT INTO subjectAlternativeNames SET certId=?, contents=?, type=?");
257         for (SubjectAlternateName subjectAlternateName : sans) {
258             san.setInt(1, id);
259             san.setString(2, subjectAlternateName.getName());
260             san.setString(3, subjectAlternateName.getType().getOpensslName());
261             san.execute();
262         }
263
264         GigiPreparedStatement updater = DatabaseConnection.getInstance().prepare("UPDATE certs SET csr_name=? WHERE id=?");
265         updater.setString(1, csrName);
266         updater.setInt(2, id);
267         updater.execute();
268         return Job.sign(this, start, period);
269
270     }
271
272     public Job revoke() {
273         if (getStatus() != CertificateStatus.ISSUED) {
274             throw new IllegalStateException();
275         }
276         return Job.revoke(this);
277
278     }
279
280     public X509Certificate cert() throws IOException, GeneralSecurityException {
281         CertificateStatus status = getStatus();
282         if (status != CertificateStatus.ISSUED) {
283             throw new IllegalStateException(status + " is not wanted here.");
284         }
285         InputStream is = null;
286         X509Certificate crt = null;
287         try {
288             is = new FileInputStream(crtName);
289             CertificateFactory cf = CertificateFactory.getInstance("X.509");
290             crt = (X509Certificate) cf.generateCertificate(is);
291         } finally {
292             if (is != null) {
293                 is.close();
294             }
295         }
296         return crt;
297     }
298
299     public Certificate renew() {
300         return null;
301     }
302
303     public int getId() {
304         return id;
305     }
306
307     public String getSerial() {
308         getStatus();
309         // poll changes
310         return serial;
311     }
312
313     public String getDistinguishedName() {
314         return dn;
315     }
316
317     public String getMessageDigest() {
318         return md;
319     }
320
321     public User getOwner() {
322         return owner;
323     }
324
325     public List<SubjectAlternateName> getSANs() {
326         return Collections.unmodifiableList(sans);
327     }
328
329     public CertificateProfile getProfile() {
330         return profile;
331     }
332
333     public static Certificate getBySerial(String serial) {
334         // TODO caching?
335         try {
336             return new Certificate(serial);
337         } catch (IllegalArgumentException e) {
338
339         }
340         return null;
341     }
342
343 }