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