]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/Certificate.java
refactor: move job to dbObjects Package
[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.HashMap;
15 import java.util.LinkedList;
16 import java.util.List;
17 import java.util.Map.Entry;
18
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;
25
26 public class Certificate {
27
28     public enum SANType {
29         EMAIL("email"), DNS("DNS");
30
31         private final String opensslName;
32
33         private SANType(String opensslName) {
34             this.opensslName = opensslName;
35         }
36
37         public String getOpensslName() {
38             return opensslName;
39         }
40     }
41
42     public static class SubjectAlternateName implements Comparable<SubjectAlternateName> {
43
44         private SANType type;
45
46         private String name;
47
48         public SubjectAlternateName(SANType type, String name) {
49             this.type = type;
50             this.name = name;
51         }
52
53         public String getName() {
54             return name;
55         }
56
57         public SANType getType() {
58             return type;
59         }
60
61         @Override
62         public int compareTo(SubjectAlternateName o) {
63             int i = type.compareTo(o.type);
64             if (i != 0) {
65                 return i;
66             }
67             return name.compareTo(o.name);
68         }
69
70         @Override
71         public int hashCode() {
72             final int prime = 31;
73             int result = 1;
74             result = prime * result + ((name == null) ? 0 : name.hashCode());
75             result = prime * result + ((type == null) ? 0 : type.hashCode());
76             return result;
77         }
78
79         @Override
80         public boolean equals(Object obj) {
81             if (this == obj) {
82                 return true;
83             }
84             if (obj == null) {
85                 return false;
86             }
87             if (getClass() != obj.getClass()) {
88                 return false;
89             }
90             SubjectAlternateName other = (SubjectAlternateName) obj;
91             if (name == null) {
92                 if (other.name != null) {
93                     return false;
94                 }
95             } else if ( !name.equals(other.name)) {
96                 return false;
97             }
98             if (type != other.type) {
99                 return false;
100             }
101             return true;
102         }
103
104     }
105
106     public enum CSRType {
107         CSR, SPKAC;
108     }
109
110     private int id;
111
112     private User owner;
113
114     private String serial;
115
116     private String md;
117
118     private String csrName;
119
120     private String crtName;
121
122     private String csr = null;
123
124     private CSRType csrType;
125
126     private List<SubjectAlternateName> sans;
127
128     private CertificateProfile profile;
129
130     private HashMap<String, String> dn;
131
132     private String dnString;
133
134     private CACertificate ca;
135
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.");
139         }
140         this.owner = owner;
141         this.dn = dn;
142         if (dn.size() == 0) {
143             throw new GigiApiException("DN must not be empty");
144         }
145         dnString = stringifyDN(dn);
146         this.md = md;
147         this.csr = csr;
148         this.csrType = csrType;
149         this.profile = profile;
150         this.sans = Arrays.asList(sans);
151     }
152
153     private Certificate(GigiResultSet rs) {
154         //
155         if ( !rs.next()) {
156             throw new IllegalArgumentException("Invalid mid " + serial);
157         }
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");
166
167         GigiPreparedStatement ps2 = DatabaseConnection.getInstance().prepare("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?");
168         ps2.setInt(1, id);
169         GigiResultSet rs2 = ps2.executeQuery();
170         sans = new LinkedList<>();
171         while (rs2.next()) {
172             sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
173         }
174         rs2.close();
175
176         rs.close();
177     }
178
179     public enum CertificateStatus {
180         /**
181          * This certificate is not in the database, has no id and only exists as
182          * this java object.
183          */
184         DRAFT(),
185         /**
186          * The certificate has been signed. It is stored in the database.
187          * {@link Certificate#cert()} is valid.
188          */
189         ISSUED(),
190
191         /**
192          * The certificate has been revoked.
193          */
194         REVOKED(),
195
196         /**
197          * If this certificate cannot be updated because an error happened in
198          * the signer.
199          */
200         ERROR();
201
202         private CertificateStatus() {}
203
204     }
205
206     public synchronized CertificateStatus getStatus() {
207         if (id == 0) {
208             return CertificateStatus.DRAFT;
209         }
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();
213         if ( !rs.next()) {
214             throw new IllegalStateException("Certificate not in Database");
215         }
216
217         crtName = rs.getString(1);
218         serial = rs.getString(4);
219         if (rs.getTimestamp(2) == null) {
220             return CertificateStatus.DRAFT;
221         }
222         ca = CACertificate.getById(rs.getInt("caid"));
223         if (rs.getTimestamp(2) != null && rs.getTimestamp(3) == null) {
224             return CertificateStatus.ISSUED;
225         }
226         return CertificateStatus.REVOKED;
227     }
228
229     /**
230      * @param start
231      *            the date from which on the certificate should be valid. (or
232      *            null if it should be valid instantly)
233      * @param period
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
236      *            months)
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
242      */
243     public Job issue(Date start, String period) throws IOException, GigiApiException {
244         if (getStatus() != CertificateStatus.DRAFT) {
245             throw new IllegalStateException();
246         }
247         Notary.writeUserAgreement(owner, "CCA", "issue certificate", "", true, 0);
248
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());
254         inserter.execute();
255         id = inserter.lastInsertId();
256
257         GigiPreparedStatement san = DatabaseConnection.getInstance().prepare("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`");
258         for (SubjectAlternateName subjectAlternateName : sans) {
259             san.setInt(1, id);
260             san.setString(2, subjectAlternateName.getName());
261             san.setString(3, subjectAlternateName.getType().getOpensslName());
262             san.execute();
263         }
264
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());
270             insertAVA.execute();
271         }
272         File csrFile = KeyStorage.locateCsr(id);
273         csrName = csrFile.getPath();
274         try (FileOutputStream fos = new FileOutputStream(csrFile)) {
275             fos.write(csr.getBytes("UTF-8"));
276         }
277
278         GigiPreparedStatement updater = DatabaseConnection.getInstance().prepare("UPDATE `certs` SET `csr_name`=? WHERE id=?");
279         updater.setString(1, csrName);
280         updater.setInt(2, id);
281         updater.execute();
282         return Job.sign(this, start, period);
283
284     }
285
286     public Job revoke() {
287         if (getStatus() != CertificateStatus.ISSUED) {
288             throw new IllegalStateException();
289         }
290         return Job.revoke(this);
291
292     }
293
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.");
298         }
299         return ca;
300     }
301
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.");
306         }
307         InputStream is = null;
308         X509Certificate crt = null;
309         try {
310             is = new FileInputStream(crtName);
311             CertificateFactory cf = CertificateFactory.getInstance("X.509");
312             crt = (X509Certificate) cf.generateCertificate(is);
313         } finally {
314             if (is != null) {
315                 is.close();
316             }
317         }
318         return crt;
319     }
320
321     public Certificate renew() {
322         return null;
323     }
324
325     public int getId() {
326         return id;
327     }
328
329     public String getSerial() {
330         getStatus();
331         // poll changes
332         return serial;
333     }
334
335     public String getDistinguishedName() {
336         return dnString;
337     }
338
339     public String getMessageDigest() {
340         return md;
341     }
342
343     public User getOwner() {
344         return owner;
345     }
346
347     public List<SubjectAlternateName> getSANs() {
348         return Collections.unmodifiableList(sans);
349     }
350
351     public CertificateProfile getProfile() {
352         return profile;
353     }
354
355     public static Certificate getBySerial(String serial) {
356         if (serial == null || "".equals(serial)) {
357             return null;
358         }
359         // TODO caching?
360         try {
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) {
367
368         }
369         return null;
370     }
371
372     public static Certificate getById(int id) {
373
374         // TODO caching?
375         try {
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");
378             ps.setInt(1, id);
379             GigiResultSet rs = ps.executeQuery();
380
381             return new Certificate(rs);
382         } catch (IllegalArgumentException e) {
383
384         }
385         return null;
386     }
387
388     public static String escapeAVA(String value) {
389
390         return value.replace("\\", "\\\\").replace("/", "\\/");
391     }
392
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()));
398         }
399         return res.toString();
400     }
401
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]);
406         }
407         return res;
408     }
409
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();
415             res.beforeFirst();
416             if (res.next()) {
417                 return new java.util.Date(res.getDate("revoked").getTime());
418             }
419         }
420         return null;
421     }
422 }