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