]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/Certificate.java
upd: split certificate issuance as organisation into seperate
[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 implements IdCachable {
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 CertificateOwner 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(CertificateOwner owner, User actor, HashMap<String, String> dn, String md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException, IOException {
137         if ( !profile.canBeIssuedBy(owner, actor)) {
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         synchronized (Certificate.class) {
152
153             GigiPreparedStatement inserter = DatabaseConnection.getInstance().prepare("INSERT INTO certs SET md=?::`mdType`, csr_type=?::`csrType`, crt_name='', memid=?, profile=?");
154             inserter.setString(1, md.toLowerCase());
155             inserter.setString(2, csrType.toString());
156             inserter.setInt(3, owner.getId());
157             inserter.setInt(4, profile.getId());
158             inserter.execute();
159             id = inserter.lastInsertId();
160
161             GigiPreparedStatement san = DatabaseConnection.getInstance().prepare("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`");
162             for (SubjectAlternateName subjectAlternateName : sans) {
163                 san.setInt(1, id);
164                 san.setString(2, subjectAlternateName.getName());
165                 san.setString(3, subjectAlternateName.getType().getOpensslName());
166                 san.execute();
167             }
168
169             GigiPreparedStatement insertAVA = DatabaseConnection.getInstance().prepare("INSERT INTO `certAvas` SET `certId`=?, name=?, value=?");
170             insertAVA.setInt(1, id);
171             for (Entry<String, String> e : dn.entrySet()) {
172                 insertAVA.setString(2, e.getKey());
173                 insertAVA.setString(3, e.getValue());
174                 insertAVA.execute();
175             }
176             File csrFile = KeyStorage.locateCsr(id);
177             csrName = csrFile.getPath();
178             try (FileOutputStream fos = new FileOutputStream(csrFile)) {
179                 fos.write(csr.getBytes("UTF-8"));
180             }
181
182             GigiPreparedStatement updater = DatabaseConnection.getInstance().prepare("UPDATE `certs` SET `csr_name`=? WHERE id=?");
183             updater.setString(1, csrName);
184             updater.setInt(2, id);
185             updater.execute();
186
187             cache.put(this);
188         }
189     }
190
191     private Certificate(GigiResultSet rs) {
192         this.id = rs.getInt("id");
193         dnString = rs.getString("subject");
194         md = rs.getString("md");
195         csrName = rs.getString("csr_name");
196         crtName = rs.getString("crt_name");
197         owner = CertificateOwner.getById(rs.getInt("memid"));
198         profile = CertificateProfile.getById(rs.getInt("profile"));
199         this.serial = rs.getString("serial");
200
201         GigiPreparedStatement ps2 = DatabaseConnection.getInstance().prepare("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?");
202         ps2.setInt(1, id);
203         GigiResultSet rs2 = ps2.executeQuery();
204         sans = new LinkedList<>();
205         while (rs2.next()) {
206             sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
207         }
208         rs2.close();
209
210         rs.close();
211     }
212
213     public enum CertificateStatus {
214         /**
215          * This certificate is not in the database, has no id and only exists as
216          * this java object.
217          */
218         DRAFT(),
219         /**
220          * The certificate has been signed. It is stored in the database.
221          * {@link Certificate#cert()} is valid.
222          */
223         ISSUED(),
224
225         /**
226          * The certificate has been revoked.
227          */
228         REVOKED(),
229
230         /**
231          * If this certificate cannot be updated because an error happened in
232          * the signer.
233          */
234         ERROR();
235
236         private CertificateStatus() {}
237
238     }
239
240     public synchronized CertificateStatus getStatus() {
241         if (id == 0) {
242             return CertificateStatus.DRAFT;
243         }
244         GigiPreparedStatement searcher = DatabaseConnection.getInstance().prepare("SELECT crt_name, created, revoked, serial, caid FROM certs WHERE id=?");
245         searcher.setInt(1, id);
246         GigiResultSet rs = searcher.executeQuery();
247         if ( !rs.next()) {
248             throw new IllegalStateException("Certificate not in Database");
249         }
250
251         crtName = rs.getString(1);
252         serial = rs.getString(4);
253         if (rs.getTimestamp(2) == null) {
254             return CertificateStatus.DRAFT;
255         }
256         ca = CACertificate.getById(rs.getInt("caid"));
257         if (rs.getTimestamp(2) != null && rs.getTimestamp(3) == null) {
258             return CertificateStatus.ISSUED;
259         }
260         return CertificateStatus.REVOKED;
261     }
262
263     /**
264      * @param start
265      *            the date from which on the certificate should be valid. (or
266      *            null if it should be valid instantly)
267      * @param period
268      *            the period for which the date should be valid. (a
269      *            <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
270      *            months)
271      * @return A job which can be used to monitor the progress of this task.
272      * @throws IOException
273      *             for problems with writing the CSR/SPKAC
274      * @throws GigiApiException
275      *             if the period is bogus
276      */
277     public Job issue(Date start, String period, User actor) throws IOException, GigiApiException {
278         if (getStatus() != CertificateStatus.DRAFT) {
279             throw new IllegalStateException();
280         }
281         Notary.writeUserAgreement(actor, "CCA", "issue certificate", "", true, 0);
282
283         return Job.sign(this, start, period);
284
285     }
286
287     public Job revoke() {
288         if (getStatus() != CertificateStatus.ISSUED) {
289             throw new IllegalStateException();
290         }
291         return Job.revoke(this);
292
293     }
294
295     public CACertificate getParent() {
296         CertificateStatus status = getStatus();
297         if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
298             throw new IllegalStateException(status + " is not wanted here.");
299         }
300         return ca;
301     }
302
303     public X509Certificate cert() throws IOException, GeneralSecurityException {
304         CertificateStatus status = getStatus();
305         if (status != CertificateStatus.REVOKED && status != CertificateStatus.ISSUED) {
306             throw new IllegalStateException(status + " is not wanted here.");
307         }
308         InputStream is = null;
309         X509Certificate crt = null;
310         try {
311             is = new FileInputStream(crtName);
312             CertificateFactory cf = CertificateFactory.getInstance("X.509");
313             crt = (X509Certificate) cf.generateCertificate(is);
314         } finally {
315             if (is != null) {
316                 is.close();
317             }
318         }
319         return crt;
320     }
321
322     public Certificate renew() {
323         return null;
324     }
325
326     public int getId() {
327         return id;
328     }
329
330     public String getSerial() {
331         getStatus();
332         // poll changes
333         return serial;
334     }
335
336     public String getDistinguishedName() {
337         return dnString;
338     }
339
340     public String getMessageDigest() {
341         return md;
342     }
343
344     public CertificateOwner getOwner() {
345         return owner;
346     }
347
348     public List<SubjectAlternateName> getSANs() {
349         return Collections.unmodifiableList(sans);
350     }
351
352     public CertificateProfile getProfile() {
353         return profile;
354     }
355
356     public synchronized static Certificate getBySerial(String serial) {
357         if (serial == null || "".equals(serial)) {
358             return null;
359         }
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             if ( !rs.next()) {
366                 return null;
367             }
368             int id = rs.getInt(1);
369             Certificate c1 = cache.get(id);
370             if (c1 != null) {
371                 return c1;
372             }
373             Certificate certificate = new Certificate(rs);
374             cache.put(certificate);
375             return certificate;
376         } catch (IllegalArgumentException e) {
377
378         }
379         return null;
380     }
381
382     private static ObjectCache<Certificate> cache = new ObjectCache<>();
383
384     public synchronized static Certificate getById(int id) {
385         Certificate cacheRes = cache.get(id);
386         if (cacheRes != null) {
387             return cacheRes;
388         }
389
390         try {
391             String concat = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
392             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");
393             ps.setInt(1, id);
394             GigiResultSet rs = ps.executeQuery();
395             if ( !rs.next()) {
396                 return null;
397             }
398
399             Certificate c = new Certificate(rs);
400             cache.put(c);
401             return c;
402         } catch (IllegalArgumentException e) {
403
404         }
405         return null;
406     }
407
408     public static String escapeAVA(String value) {
409
410         return value.replace("\\", "\\\\").replace("/", "\\/");
411     }
412
413     public static String stringifyDN(HashMap<String, String> contents) {
414         StringBuffer res = new StringBuffer();
415         for (Entry<String, String> i : contents.entrySet()) {
416             res.append("/" + i.getKey() + "=");
417             res.append(escapeAVA(i.getValue()));
418         }
419         return res.toString();
420     }
421
422     public static HashMap<String, String> buildDN(String... contents) {
423         HashMap<String, String> res = new HashMap<>();
424         for (int i = 0; i + 1 < contents.length; i += 2) {
425             res.put(contents[i], contents[i + 1]);
426         }
427         return res;
428     }
429
430     public java.util.Date getRevocationDate() {
431         if (getStatus() == CertificateStatus.REVOKED) {
432             GigiPreparedStatement prep = DatabaseConnection.getInstance().prepare("SELECT revoked FROM certs WHERE id=?");
433             prep.setInt(1, getId());
434             GigiResultSet res = prep.executeQuery();
435             res.beforeFirst();
436             if (res.next()) {
437                 return new java.util.Date(res.getDate("revoked").getTime());
438             }
439         }
440         return null;
441     }
442 }