]> WPIA git - gigi.git/blob - src/org/cacert/gigi/dbObjects/Certificate.java
upd: convert to PostgreSQL
[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.Job;
24 import org.cacert.gigi.util.KeyStorage;
25 import org.cacert.gigi.util.Notary;
26
27 public class Certificate {
28
29     public enum SANType {
30         EMAIL("email"), DNS("DNS");
31
32         private final String opensslName;
33
34         private SANType(String opensslName) {
35             this.opensslName = opensslName;
36         }
37
38         public String getOpensslName() {
39             return opensslName;
40         }
41     }
42
43     public static class SubjectAlternateName implements Comparable<SubjectAlternateName> {
44
45         private SANType type;
46
47         private String name;
48
49         public SubjectAlternateName(SANType type, String name) {
50             this.type = type;
51             this.name = name;
52         }
53
54         public String getName() {
55             return name;
56         }
57
58         public SANType getType() {
59             return type;
60         }
61
62         @Override
63         public int compareTo(SubjectAlternateName o) {
64             int i = type.compareTo(o.type);
65             if (i != 0) {
66                 return i;
67             }
68             return name.compareTo(o.name);
69         }
70
71         @Override
72         public int hashCode() {
73             final int prime = 31;
74             int result = 1;
75             result = prime * result + ((name == null) ? 0 : name.hashCode());
76             result = prime * result + ((type == null) ? 0 : type.hashCode());
77             return result;
78         }
79
80         @Override
81         public boolean equals(Object obj) {
82             if (this == obj) {
83                 return true;
84             }
85             if (obj == null) {
86                 return false;
87             }
88             if (getClass() != obj.getClass()) {
89                 return false;
90             }
91             SubjectAlternateName other = (SubjectAlternateName) obj;
92             if (name == null) {
93                 if (other.name != null) {
94                     return false;
95                 }
96             } else if ( !name.equals(other.name)) {
97                 return false;
98             }
99             if (type != other.type) {
100                 return false;
101             }
102             return true;
103         }
104
105     }
106
107     public enum CSRType {
108         CSR, SPKAC;
109     }
110
111     private int id;
112
113     private User owner;
114
115     private String serial;
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     private HashMap<String, String> dn;
132
133     private String dnString;
134
135     private CACertificate ca;
136
137     public Certificate(User owner, HashMap<String, String> dn, String md, String csr, CSRType csrType, CertificateProfile profile, SubjectAlternateName... sans) throws GigiApiException {
138         if ( !profile.canBeIssuedBy(owner)) {
139             throw new GigiApiException("You are not allowed to issue these certificates.");
140         }
141         this.owner = owner;
142         this.dn = dn;
143         if (dn.size() == 0) {
144             throw new GigiApiException("DN must not be empty");
145         }
146         dnString = stringifyDN(dn);
147         this.md = md;
148         this.csr = csr;
149         this.csrType = csrType;
150         this.profile = profile;
151         this.sans = Arrays.asList(sans);
152     }
153
154     private Certificate(GigiResultSet rs) {
155         //
156         if ( !rs.next()) {
157             throw new IllegalArgumentException("Invalid mid " + serial);
158         }
159         this.id = rs.getInt("id");
160         dnString = rs.getString("subject");
161         md = rs.getString("md");
162         csrName = rs.getString("csr_name");
163         crtName = rs.getString("crt_name");
164         owner = User.getById(rs.getInt("memid"));
165         profile = CertificateProfile.getById(rs.getInt("profile"));
166         this.serial = rs.getString("serial");
167
168         GigiPreparedStatement ps2 = DatabaseConnection.getInstance().prepare("SELECT `contents`, `type` FROM `subjectAlternativeNames` WHERE `certId`=?");
169         ps2.setInt(1, id);
170         GigiResultSet rs2 = ps2.executeQuery();
171         sans = new LinkedList<>();
172         while (rs2.next()) {
173             sans.add(new SubjectAlternateName(SANType.valueOf(rs2.getString("type").toUpperCase()), rs2.getString("contents")));
174         }
175         rs2.close();
176
177         rs.close();
178     }
179
180     public enum CertificateStatus {
181         /**
182          * This certificate is not in the database, has no id and only exists as
183          * this java object.
184          */
185         DRAFT(),
186         /**
187          * The certificate has been signed. It is stored in the database.
188          * {@link Certificate#cert()} is valid.
189          */
190         ISSUED(),
191
192         /**
193          * The certificate has been revoked.
194          */
195         REVOKED(),
196
197         /**
198          * If this certificate cannot be updated because an error happened in
199          * the signer.
200          */
201         ERROR();
202
203         private CertificateStatus() {}
204
205     }
206
207     public synchronized CertificateStatus getStatus() {
208         if (id == 0) {
209             return CertificateStatus.DRAFT;
210         }
211         GigiPreparedStatement searcher = DatabaseConnection.getInstance().prepare("SELECT crt_name, created, revoked, serial, caid FROM certs WHERE id=?");
212         searcher.setInt(1, id);
213         GigiResultSet rs = searcher.executeQuery();
214         if ( !rs.next()) {
215             throw new IllegalStateException("Certificate not in Database");
216         }
217
218         crtName = rs.getString(1);
219         serial = rs.getString(4);
220         if (rs.getTimestamp(2) == null) {
221             return CertificateStatus.DRAFT;
222         }
223         ca = CACertificate.getById(rs.getInt("caid"));
224         if (rs.getTimestamp(2) != null && rs.getTimestamp(3) == null) {
225             return CertificateStatus.ISSUED;
226         }
227         return CertificateStatus.REVOKED;
228     }
229
230     /**
231      * @param start
232      *            the date from which on the certificate should be valid. (or
233      *            null if it should be valid instantly)
234      * @param period
235      *            the period for which the date should be valid. (a
236      *            <code>yyyy-mm-dd</code> or a "2y" (2 calendar years), "6m" (6
237      *            months)
238      * @return A job which can be used to monitor the progress of this task.
239      * @throws IOException
240      *             for problems with writing the CSR/SPKAC
241      * @throws GigiApiException
242      *             if the period is bogus
243      */
244     public Job issue(Date start, String period) throws IOException, GigiApiException {
245         if (getStatus() != CertificateStatus.DRAFT) {
246             throw new IllegalStateException();
247         }
248         Notary.writeUserAgreement(owner, "CCA", "issue certificate", "", true, 0);
249
250         GigiPreparedStatement inserter = DatabaseConnection.getInstance().prepare("INSERT INTO certs SET md=?::`mdType`, csr_type=?::`csrType`, crt_name='', memid=?, profile=?");
251         inserter.setString(1, md.toLowerCase());
252         inserter.setString(2, csrType.toString());
253         inserter.setInt(3, owner.getId());
254         inserter.setInt(4, profile.getId());
255         inserter.execute();
256         id = inserter.lastInsertId();
257
258         GigiPreparedStatement san = DatabaseConnection.getInstance().prepare("INSERT INTO `subjectAlternativeNames` SET `certId`=?, contents=?, type=?::`SANType`");
259         for (SubjectAlternateName subjectAlternateName : sans) {
260             san.setInt(1, id);
261             san.setString(2, subjectAlternateName.getName());
262             san.setString(3, subjectAlternateName.getType().getOpensslName());
263             san.execute();
264         }
265
266         GigiPreparedStatement insertAVA = DatabaseConnection.getInstance().prepare("INSERT INTO `certAvas` SET certid=?, name=?, value=?");
267         insertAVA.setInt(1, id);
268         for (Entry<String, String> e : dn.entrySet()) {
269             insertAVA.setString(2, e.getKey());
270             insertAVA.setString(3, e.getValue());
271             insertAVA.execute();
272         }
273         File csrFile = KeyStorage.locateCsr(id);
274         csrName = csrFile.getPath();
275         try (FileOutputStream fos = new FileOutputStream(csrFile)) {
276             fos.write(csr.getBytes("UTF-8"));
277         }
278
279         GigiPreparedStatement updater = DatabaseConnection.getInstance().prepare("UPDATE `certs` SET `csr_name`=? WHERE id=?");
280         updater.setString(1, csrName);
281         updater.setInt(2, id);
282         updater.execute();
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 User 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 static Certificate getBySerial(String serial) {
357         if (serial == null || "".equals(serial)) {
358             return null;
359         }
360         // TODO caching?
361         try {
362             String concat = "string_agg(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')), '')";
363             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`");
364             ps.setString(1, serial);
365             GigiResultSet rs = ps.executeQuery();
366             return new Certificate(rs);
367         } catch (IllegalArgumentException e) {
368
369         }
370         return null;
371     }
372
373     public static Certificate getById(int id) {
374
375         // TODO caching?
376         try {
377             String concat = "group_concat(concat('/', `name`, '=', REPLACE(REPLACE(value, '\\\\', '\\\\\\\\'), '/', '\\\\/')))";
378             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");
379             ps.setInt(1, id);
380             GigiResultSet rs = ps.executeQuery();
381
382             return new Certificate(rs);
383         } catch (IllegalArgumentException e) {
384
385         }
386         return null;
387     }
388
389     public static String escapeAVA(String value) {
390
391         return value.replace("\\", "\\\\").replace("/", "\\/");
392     }
393
394     public static String stringifyDN(HashMap<String, String> contents) {
395         StringBuffer res = new StringBuffer();
396         for (Entry<String, String> i : contents.entrySet()) {
397             res.append("/" + i.getKey() + "=");
398             res.append(escapeAVA(i.getValue()));
399         }
400         return res.toString();
401     }
402
403     public static HashMap<String, String> buildDN(String... contents) {
404         HashMap<String, String> res = new HashMap<>();
405         for (int i = 0; i + 1 < contents.length; i += 2) {
406             res.put(contents[i], contents[i + 1]);
407         }
408         return res;
409     }
410
411     public java.util.Date getRevocationDate() {
412         if (getStatus() == CertificateStatus.REVOKED) {
413             GigiPreparedStatement prep = DatabaseConnection.getInstance().prepare("SELECT revoked FROM certs WHERE id=?");
414             prep.setInt(1, getId());
415             GigiResultSet res = prep.executeQuery();
416             res.beforeFirst();
417             if (res.next()) {
418                 return new java.util.Date(res.getDate("revoked").getTime());
419             }
420         }
421         return null;
422     }
423 }