]> WPIA git - gigi.git/blob - src/org/cacert/gigi/pages/account/certs/CertificateRequest.java
UPD: extract certificate requests out of form (preparing for API)
[gigi.git] / src / org / cacert / gigi / pages / account / certs / CertificateRequest.java
1 package org.cacert.gigi.pages.account.certs;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.security.GeneralSecurityException;
6 import java.security.PublicKey;
7 import java.security.interfaces.DSAPublicKey;
8 import java.security.interfaces.ECPublicKey;
9 import java.security.interfaces.RSAPublicKey;
10 import java.util.Arrays;
11 import java.util.Base64;
12 import java.util.HashMap;
13 import java.util.LinkedHashSet;
14 import java.util.Set;
15 import java.util.TreeSet;
16
17 import javax.servlet.http.HttpServletRequest;
18
19 import org.cacert.gigi.GigiApiException;
20 import org.cacert.gigi.crypto.SPKAC;
21 import org.cacert.gigi.dbObjects.Certificate;
22 import org.cacert.gigi.dbObjects.Certificate.CSRType;
23 import org.cacert.gigi.dbObjects.Certificate.SANType;
24 import org.cacert.gigi.dbObjects.Certificate.SubjectAlternateName;
25 import org.cacert.gigi.dbObjects.CertificateProfile;
26 import org.cacert.gigi.dbObjects.Digest;
27 import org.cacert.gigi.dbObjects.Organisation;
28 import org.cacert.gigi.dbObjects.User;
29 import org.cacert.gigi.output.template.Scope;
30 import org.cacert.gigi.output.template.SprintfCommand;
31 import org.cacert.gigi.util.PEM;
32
33 import sun.security.pkcs.PKCS9Attribute;
34 import sun.security.pkcs10.PKCS10;
35 import sun.security.pkcs10.PKCS10Attribute;
36 import sun.security.pkcs10.PKCS10Attributes;
37 import sun.security.util.DerInputStream;
38 import sun.security.util.DerValue;
39 import sun.security.util.ObjectIdentifier;
40 import sun.security.x509.AVA;
41 import sun.security.x509.AlgorithmId;
42 import sun.security.x509.CertificateExtensions;
43 import sun.security.x509.DNSName;
44 import sun.security.x509.ExtendedKeyUsageExtension;
45 import sun.security.x509.Extension;
46 import sun.security.x509.GeneralName;
47 import sun.security.x509.GeneralNameInterface;
48 import sun.security.x509.GeneralNames;
49 import sun.security.x509.PKIXExtensions;
50 import sun.security.x509.RDN;
51 import sun.security.x509.RFC822Name;
52 import sun.security.x509.SubjectAlternativeNameExtension;
53 import sun.security.x509.X500Name;
54
55 public class CertificateRequest {
56
57     public static final String DEFAULT_CN = "CAcert WoT User";
58
59     public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
60             1, 3, 6, 1, 5, 5, 7, 3, 1
61     });
62
63     public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
64             1, 3, 6, 1, 5, 5, 7, 3, 2
65     });
66
67     public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
68             1, 3, 6, 1, 5, 5, 7, 3, 3
69     });
70
71     public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
72             1, 3, 6, 1, 5, 5, 7, 3, 4
73     });
74
75     public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
76             1, 3, 6, 1, 5, 5, 7, 3, 8
77     });
78
79     public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
80             1, 3, 6, 1, 5, 5, 7, 3, 9
81     });
82
83     private CSRType csrType;
84
85     private final PublicKey pk;
86
87     private String csr;
88
89     public String CN = DEFAULT_CN;
90
91     private Set<SubjectAlternateName> SANs;
92
93     private Digest selectedDigest = Digest.getDefault();
94
95     private CertificateProfile profile = CertificateProfile.getById(1);
96
97     private String ou = "";
98
99     private Organisation org = null;
100
101     private User u;
102
103     private String pDNS, pMail;
104
105     public CertificateRequest(User issuer, String csr) throws IOException, GeneralSecurityException, GigiApiException {
106         u = issuer;
107         byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
108         PKCS10 parsed = new PKCS10(data);
109         PKCS10Attributes atts = parsed.getAttributes();
110
111         TreeSet<SubjectAlternateName> SANs = new TreeSet<>();
112         for (RDN r : parsed.getSubjectName().rdns()) {
113             for (AVA a : r.avas()) {
114                 if (a.getObjectIdentifier().equals((Object) PKCS9Attribute.EMAIL_ADDRESS_OID)) {
115                     SANs.add(new SubjectAlternateName(SANType.EMAIL, a.getValueString()));
116                 } else if (a.getObjectIdentifier().equals((Object) X500Name.commonName_oid)) {
117                     String value = a.getValueString();
118                     if (value.contains(".") && !value.contains(" ")) {
119                         SANs.add(new SubjectAlternateName(SANType.DNS, value));
120                     } else {
121                         CN = value;
122                     }
123                 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
124                     // TODO? parse invalid SANs
125                 }
126             }
127         }
128
129         for (PKCS10Attribute b : atts.getAttributes()) {
130
131             if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
132                 // unknown attrib
133                 continue;
134             }
135
136             for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
137                 if (c instanceof SubjectAlternativeNameExtension) {
138
139                     SubjectAlternativeNameExtension san = (SubjectAlternativeNameExtension) c;
140                     GeneralNames obj = san.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
141                     for (int i = 0; i < obj.size(); i++) {
142                         GeneralName generalName = obj.get(i);
143                         GeneralNameInterface peeled = generalName.getName();
144                         if (peeled instanceof DNSName) {
145                             SANs.add(new SubjectAlternateName(SANType.DNS, ((DNSName) peeled).getName()));
146                         } else if (peeled instanceof RFC822Name) {
147                             SANs.add(new SubjectAlternateName(SANType.EMAIL, ((RFC822Name) peeled).getName()));
148                         }
149                     }
150                 } else if (c instanceof ExtendedKeyUsageExtension) {
151                     ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
152                     for (String s : ekue.getExtendedKeyUsage()) {
153                         if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
154                             // server
155                             profile = CertificateProfile.getByName("server");
156                         } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
157                             // client
158                             profile = CertificateProfile.getByName("client");
159                         } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
160                             // code sign
161                         } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
162                             // emailProtection
163                             profile = CertificateProfile.getByName("mail");
164                         } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
165                             // timestamp
166                         } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
167                             // OCSP
168                         }
169                     }
170                 } else {
171                     // Unknown requested extension
172                 }
173             }
174
175         }
176         GigiApiException error = new GigiApiException();
177         this.SANs = verifySANs(error, false, SANs);
178         if ( !error.isEmpty()) {
179             throw error;
180         }
181         pk = parsed.getSubjectPublicKeyInfo();
182         String sign = getSignatureAlgorithm(data);
183         guessDigest(sign);
184
185         this.csr = csr;
186         this.csrType = CSRType.CSR;
187     }
188
189     public CertificateRequest(User issuer, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
190         u = issuer;
191         String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
192         byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
193         SPKAC parsed = new SPKAC(data);
194         if ( !parsed.getChallenge().equals(spkacChallenge)) {
195             throw new GigiApiException("Challenge mismatch");
196         }
197         pk = parsed.getPubkey();
198         String sign = getSignatureAlgorithm(data);
199         guessDigest(sign);
200
201         this.csr = "SPKAC=" + cleanedSPKAC;
202         this.csrType = CSRType.SPKAC;
203
204     }
205
206     private static String getSignatureAlgorithm(byte[] data) throws IOException {
207         DerInputStream in = new DerInputStream(data);
208         DerValue[] seq = in.getSequence(3);
209         return AlgorithmId.parse(seq[1]).getName();
210     }
211
212     private void guessDigest(String sign) {
213         if (sign.toLowerCase().startsWith("sha512")) {
214             selectedDigest = Digest.SHA512;
215         } else if (sign.toLowerCase().startsWith("sha384")) {
216             selectedDigest = Digest.SHA384;
217         }
218     }
219
220     public void checkKeyStrength(PrintWriter out) {
221         out.println("Type: " + pk.getAlgorithm() + "<br/>");
222         if (pk instanceof RSAPublicKey) {
223             out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
224             out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
225         } else if (pk instanceof DSAPublicKey) {
226             DSAPublicKey dpk = (DSAPublicKey) pk;
227             out.println("Length: " + dpk.getY().bitLength() + "<br/>");
228             out.println(dpk.getParams());
229         } else if (pk instanceof ECPublicKey) {
230             ECPublicKey epk = (ECPublicKey) pk;
231             out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
232             out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
233             out.println(epk.getParams().getCurve());
234         }
235     }
236
237     private TreeSet<SubjectAlternateName> parseSANBox(String SANs) {
238         String[] SANparts = SANs.split("[\r\n]+|, *");
239         TreeSet<SubjectAlternateName> parsedNames = new TreeSet<>();
240         for (String SANline : SANparts) {
241             String[] parts = SANline.split(":", 2);
242             if (parts.length == 1) {
243                 if (parts[0].trim().equals("")) {
244                     continue;
245                 }
246                 if (parts[0].contains("@")) {
247                     parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
248                 } else {
249                     parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
250                 }
251                 continue;
252             }
253             try {
254                 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase());
255                 if (t == null) {
256                     continue;
257                 }
258                 parsedNames.add(new SubjectAlternateName(t, parts[1]));
259             } catch (IllegalArgumentException e) {
260                 // invalid enum type
261                 continue;
262             }
263         }
264         return parsedNames;
265     }
266
267     public Set<SubjectAlternateName> getSANs() {
268         return SANs;
269     }
270
271     public String getCN() {
272         return CN;
273     }
274
275     public Organisation getOrg() {
276         return org;
277     }
278
279     public String getOu() {
280         return ou;
281     }
282
283     public Digest getSelectedDigest() {
284         return selectedDigest;
285     }
286
287     public CertificateProfile getProfile() {
288         return profile;
289     }
290
291     public boolean update(String CNin, String hashAlg, String profileStr, String newOrgStr, String ou, String SANsStr, PrintWriter out, HttpServletRequest req) throws GigiApiException {
292         GigiApiException error = new GigiApiException();
293         this.CN = CNin;
294         if (hashAlg != null) {
295             selectedDigest = Digest.valueOf(hashAlg);
296         }
297         this.profile = CertificateProfile.getByName(profileStr);
298         if (newOrgStr != null) {
299             Organisation neworg = Organisation.getById(Integer.parseInt(newOrgStr));
300             if (neworg == null || u.getOrganisations().contains(neworg)) {
301                 org = neworg;
302             } else {
303                 error.mergeInto(new GigiApiException("Selected Organisation is not part of your account."));
304             }
305         }
306         this.ou = ou;
307
308         boolean server = profile.getKeyName().equals("server");
309         SANs = verifySANs(error, server, parseSANBox(SANsStr));
310
311         if ( !error.isEmpty()) {
312             throw error;
313         }
314         return true;
315     }
316
317     private Set<SubjectAlternateName> verifySANs(GigiApiException error, boolean server, TreeSet<SubjectAlternateName> parseSANBox) {
318         Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
319         for (SubjectAlternateName san : parseSANBox) {
320             if (san.getType() == SANType.DNS) {
321                 if (u.isValidDomain(san.getName()) && server) {
322                     if (pDNS == null) {
323                         pDNS = san.getName();
324                     }
325                     filteredSANs.add(san);
326                     continue;
327                 }
328             } else if (san.getType() == SANType.EMAIL) {
329                 if (u.isValidEmail(san.getName()) && !server) {
330                     if (pMail == null) {
331                         pMail = san.getName();
332                     }
333                     filteredSANs.add(san);
334                     continue;
335                 }
336             }
337             HashMap<String, Object> vars = new HashMap<>();
338             vars.put("SAN", san.getType().toString().toLowerCase() + ":" + san.getName());
339             error.mergeInto(new GigiApiException(new Scope(new SprintfCommand(//
340                     "The requested Subject alternate name \"%s\" has been removed.", Arrays.asList("$SAN")), vars)));
341         }
342         return filteredSANs;
343     }
344
345     public Certificate draft() throws GigiApiException {
346
347         GigiApiException error = new GigiApiException();
348         if ( !u.canIssue(this.profile)) {
349             this.profile = CertificateProfile.getById(1);
350             error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
351             throw error;
352         }
353
354         boolean server = profile.getKeyName().equals("server");
355         if ( !u.isValidName(CN) && !server && !CN.equals(DEFAULT_CN)) {
356             this.CN = DEFAULT_CN;
357             error.mergeInto(new GigiApiException("The name entered, does not match the details in your account. You cannot issue certificates with this name. Enter a name that matches the one that has been assured in your account."));
358         }
359
360         HashMap<String, String> subject = new HashMap<>();
361         if (server && pDNS != null) {
362             subject.put("CN", pDNS);
363             if (pMail != null) {
364                 error.mergeInto(new GigiApiException("No email is included in this certificate."));
365             }
366             if (CN.equals("")) {
367                 CN = "";
368                 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
369             }
370         } else {
371             u.isValidName(CN);
372             subject.put("CN", CN);
373             if (pMail != null) {
374                 subject.put("EMAIL", pMail);
375             }
376         }
377         if (org != null) {
378             subject.put("O", org.getName());
379             subject.put("C", org.getState());
380             subject.put("ST", org.getProvince());
381             subject.put("L", org.getCity());
382             subject.put("OU", ou);
383         }
384
385         if ( !error.isEmpty()) {
386             throw error;
387         }
388         return new Certificate(u, subject, selectedDigest.toString(), //
389                 this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
390     }
391 }