]> WPIA git - gigi.git/blob - src/org/cacert/gigi/pages/account/CertificateIssueForm.java
Extract EKU-OIDs to class constants.
[gigi.git] / src / org / cacert / gigi / pages / account / CertificateIssueForm.java
1 package org.cacert.gigi.pages.account;
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.sql.SQLException;
11 import java.util.Base64;
12 import java.util.HashMap;
13 import java.util.LinkedHashSet;
14 import java.util.Map;
15 import java.util.Set;
16 import java.util.TreeSet;
17
18 import javax.servlet.http.HttpServletRequest;
19
20 import org.cacert.gigi.Certificate;
21 import org.cacert.gigi.Certificate.CSRType;
22 import org.cacert.gigi.Certificate.SANType;
23 import org.cacert.gigi.Certificate.SubjectAlternateName;
24 import org.cacert.gigi.CertificateProfile;
25 import org.cacert.gigi.Digest;
26 import org.cacert.gigi.GigiApiException;
27 import org.cacert.gigi.User;
28 import org.cacert.gigi.crypto.SPKAC;
29 import org.cacert.gigi.localisation.Language;
30 import org.cacert.gigi.output.Form;
31 import org.cacert.gigi.output.template.HashAlgorithms;
32 import org.cacert.gigi.output.template.IterableDataset;
33 import org.cacert.gigi.output.template.Template;
34 import org.cacert.gigi.pages.LoginPage;
35 import org.cacert.gigi.pages.Page;
36 import org.cacert.gigi.util.PEM;
37 import org.cacert.gigi.util.RandomToken;
38
39 import sun.security.pkcs.PKCS9Attribute;
40 import sun.security.pkcs10.PKCS10;
41 import sun.security.pkcs10.PKCS10Attribute;
42 import sun.security.pkcs10.PKCS10Attributes;
43 import sun.security.util.DerInputStream;
44 import sun.security.util.DerValue;
45 import sun.security.util.ObjectIdentifier;
46 import sun.security.x509.AVA;
47 import sun.security.x509.AlgorithmId;
48 import sun.security.x509.CertificateExtensions;
49 import sun.security.x509.DNSName;
50 import sun.security.x509.ExtendedKeyUsageExtension;
51 import sun.security.x509.Extension;
52 import sun.security.x509.GeneralName;
53 import sun.security.x509.GeneralNameInterface;
54 import sun.security.x509.GeneralNames;
55 import sun.security.x509.PKIXExtensions;
56 import sun.security.x509.RDN;
57 import sun.security.x509.RFC822Name;
58 import sun.security.x509.SubjectAlternativeNameExtension;
59 import sun.security.x509.X500Name;
60
61 /**
62  * This class represents a form that is used for issuing certificates. This
63  * class uses "sun.security" and therefore needs "-XDignore.symbol.file"
64  */
65 public class CertificateIssueForm extends Form {
66
67     private static final String DEFAULT_CN = "CAcert WoT User";
68
69     private final static Template t = new Template(CertificateIssueForm.class.getResource("CertificateIssueForm.templ"));
70
71     private final static Template tIni = new Template(CertificateAdd.class.getResource("RequestCertificate.templ"));
72
73     public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
74             1, 3, 6, 1, 5, 5, 7, 3, 1
75     });
76
77     public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
78             1, 3, 6, 1, 5, 5, 7, 3, 2
79     });
80
81     public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
82             1, 3, 6, 1, 5, 5, 7, 3, 3
83     });
84
85     public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
86             1, 3, 6, 1, 5, 5, 7, 3, 4
87     });
88
89     public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
90             1, 3, 6, 1, 5, 5, 7, 3, 8
91     });
92
93     public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
94             1, 3, 6, 1, 5, 5, 7, 3, 9
95     });
96
97     User u;
98
99     private CSRType csrType;
100
101     String csr;
102
103     String spkacChallenge;
104
105     public String CN = DEFAULT_CN;
106
107     Set<SubjectAlternateName> SANs = new LinkedHashSet<>();
108
109     Digest selectedDigest = Digest.getDefault();
110
111     boolean login;
112
113     CertificateProfile profile = CertificateProfile.getById(1);
114
115     public CertificateIssueForm(HttpServletRequest hsr) {
116         super(hsr);
117         u = Page.getUser(hsr);
118         spkacChallenge = RandomToken.generateToken(16);
119     }
120
121     Certificate result;
122
123     public Certificate getResult() {
124         return result;
125     }
126
127     @Override
128     public boolean submit(PrintWriter out, HttpServletRequest req) {
129         String csr = req.getParameter("CSR");
130         String spkac = req.getParameter("SPKAC");
131         try {
132             try {
133                 if (csr != null) {
134                     byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
135                     PKCS10 parsed = new PKCS10(data);
136                     PKCS10Attributes atts = parsed.getAttributes();
137
138                     for (PKCS10Attribute b : atts.getAttributes()) {
139
140                         if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
141                             // unknown attrib
142                             continue;
143                         }
144
145                         for (RDN r : parsed.getSubjectName().rdns()) {
146                             for (AVA a : r.avas()) {
147                                 if (a.getObjectIdentifier().equals((Object) PKCS9Attribute.EMAIL_ADDRESS_OID)) {
148                                     SANs.add(new SubjectAlternateName(SANType.EMAIL, a.getValueString()));
149                                 } else if (a.getObjectIdentifier().equals((Object) X500Name.commonName_oid)) {
150                                     String value = a.getValueString();
151                                     if (value.contains(".") && !value.contains(" ")) {
152                                         SANs.add(new SubjectAlternateName(SANType.DNS, value));
153                                     } else {
154                                         CN = value;
155                                     }
156                                 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
157                                     // parse invalid SANs
158                                 }
159                             }
160                         }
161
162                         for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
163                             if (c instanceof SubjectAlternativeNameExtension) {
164
165                                 SubjectAlternativeNameExtension san = (SubjectAlternativeNameExtension) c;
166                                 GeneralNames obj = san.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
167                                 for (int i = 0; i < obj.size(); i++) {
168                                     GeneralName generalName = obj.get(i);
169                                     GeneralNameInterface peeled = generalName.getName();
170                                     if (peeled instanceof DNSName) {
171                                         SANs.add(new SubjectAlternateName(SANType.DNS, ((DNSName) peeled).getName()));
172                                     } else if (peeled instanceof RFC822Name) {
173                                         SANs.add(new SubjectAlternateName(SANType.EMAIL, ((RFC822Name) peeled).getName()));
174                                     }
175                                 }
176                             } else if (c instanceof ExtendedKeyUsageExtension) {
177                                 ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
178                                 for (String s : ekue.getExtendedKeyUsage()) {
179                                     if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
180                                         // server
181                                     } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
182                                         // client
183                                     } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
184                                         // code sign
185                                     } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
186                                         // emailProtection
187                                     } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
188                                         // timestamp
189                                     } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
190                                         // OCSP
191                                     }
192                                 }
193                             } else {
194                                 // Unknown requested extension
195                             }
196                         }
197
198                     }
199                     out.println(parsed.getSubjectName().getCommonName());
200                     out.println(parsed.getSubjectName().getCountry());
201
202                     out.println("CSR DN: " + parsed.getSubjectName() + "<br/>");
203                     PublicKey pk = parsed.getSubjectPublicKeyInfo();
204                     checkKeyStrength(pk, out);
205                     String sign = getSignatureAlgorithm(data);
206                     out.println("<br/>digest: " + sign + "<br/>");
207
208                     this.csr = csr;
209                     this.csrType = CSRType.CSR;
210                 } else if (spkac != null) {
211                     String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
212                     byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
213                     SPKAC parsed = new SPKAC(data);
214                     if ( !parsed.getChallenge().equals(spkacChallenge)) {
215                         throw new GigiApiException("Challenge mismatch");
216                     }
217                     checkKeyStrength(parsed.getPubkey(), out);
218                     String sign = getSignatureAlgorithm(data);
219                     out.println("<br/>digest: " + sign + "<br/>");
220
221                     // spkacChallenge
222                     this.csr = "SPKAC=" + cleanedSPKAC;
223                     this.csrType = CSRType.SPKAC;
224
225                 } else {
226                     login = "1".equals(req.getParameter("login"));
227                     CN = req.getParameter("CN");
228                     String hashAlg = req.getParameter("hash_alg");
229                     if (hashAlg != null) {
230                         selectedDigest = Digest.valueOf(hashAlg);
231                     }
232                     profile = CertificateProfile.getByName(req.getParameter("profile"));
233
234                     String pDNS = null;
235                     String pMail = null;
236                     Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
237                     boolean server = profile.getKeyName().equals("server");
238                     for (SubjectAlternateName san : parseSANBox(req.getParameter("SANs"))) {
239                         if (san.getType() == SANType.DNS) {
240                             if (u.isValidDomain(san.getName()) && server) {
241                                 if (pDNS == null) {
242                                     pDNS = san.getName();
243                                 }
244                                 filteredSANs.add(san);
245                                 continue;
246                             }
247                         } else if (san.getType() == SANType.EMAIL) {
248                             if (u.isValidEmail(san.getName()) && !server) {
249                                 if (pMail == null) {
250                                     pMail = san.getName();
251                                 }
252                                 filteredSANs.add(san);
253                                 continue;
254                             }
255                         }
256                         outputError(out, req, "The requested Subject alternate name \"%s\" has been removed.",//
257                                 san.getType().toString().toLowerCase() + ":" + san.getName());
258                     }
259                     SANs = filteredSANs;
260                     if ( !u.isValidName(CN) && !server && !CN.equals(DEFAULT_CN)) {
261                         CN = DEFAULT_CN;
262                         outputError(out, req, "The real name entered cannot be verified with your account.");
263                     }
264
265                     final StringBuffer subject = new StringBuffer();
266                     if (server && pDNS != null) {
267                         subject.append("/commonName=");
268                         subject.append(pDNS);
269                         if (pMail != null) {
270                             outputError(out, req, "No email is included in this certificate.");
271                         }
272                         if (CN.equals("")) {
273                             CN = "";
274                             outputError(out, req, "No real name is included in this certificate.");
275                         }
276                     } else {
277                         subject.append("/commonName=");
278                         subject.append(CN);
279                         if (pMail != null) {
280                             subject.append("/emailAddress=");
281                             subject.append(pMail);
282                         }
283                     }
284                     if (req.getParameter("CCA") == null) {
285                         outputError(out, req, "You need to accept the CCA.");
286                     }
287                     if (isFailed(out)) {
288                         return false;
289                     }
290
291                     result = new Certificate(LoginPage.getUser(req).getId(), subject.toString(), selectedDigest.toString(), //
292                             this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
293                     result.issue().waitFor(60000);
294                     return true;
295                 }
296             } catch (IOException e) {
297                 e.printStackTrace();
298             } catch (IllegalArgumentException e) {
299                 e.printStackTrace();
300                 throw new GigiApiException("Certificate Request format is invalid.");
301             } catch (GeneralSecurityException e) {
302                 e.printStackTrace();
303                 throw new GigiApiException("Certificate Request format is invalid.");
304             } catch (InterruptedException e) {
305                 e.printStackTrace();
306             } catch (SQLException e) {
307                 throw new GigiApiException(e);
308             }
309         } catch (GigiApiException e) {
310             e.format(out, Page.getLanguage(req));
311         }
312         return false;
313     }
314
315     private TreeSet<SubjectAlternateName> parseSANBox(String SANs) {
316         String[] SANparts = SANs.split("[\r\n]+|, *");
317         TreeSet<SubjectAlternateName> parsedNames = new TreeSet<>();
318         for (String SANline : SANparts) {
319             String[] parts = SANline.split(":", 2);
320             if (parts.length == 1) {
321                 if (parts[0].trim().equals("")) {
322                     continue;
323                 }
324                 if (parts[0].contains("@")) {
325                     parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
326                 } else {
327                     parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
328                 }
329                 continue;
330             }
331             try {
332                 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase());
333                 if (t == null) {
334                     continue;
335                 }
336                 parsedNames.add(new SubjectAlternateName(t, parts[1]));
337             } catch (IllegalArgumentException e) {
338                 // invalid enum type
339                 continue;
340             }
341         }
342         return parsedNames;
343     }
344
345     private void checkKeyStrength(PublicKey pk, PrintWriter out) {
346         out.println("Type: " + pk.getAlgorithm() + "<br/>");
347         if (pk instanceof RSAPublicKey) {
348             out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
349             out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
350         } else if (pk instanceof DSAPublicKey) {
351             DSAPublicKey dpk = (DSAPublicKey) pk;
352             out.println("Length: " + dpk.getY().bitLength() + "<br/>");
353             out.println(dpk.getParams());
354         } else if (pk instanceof ECPublicKey) {
355             ECPublicKey epk = (ECPublicKey) pk;
356             out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
357             out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
358             out.println(epk.getParams().getCurve());
359         }
360     }
361
362     private static String getSignatureAlgorithm(byte[] data) throws IOException {
363         DerInputStream in = new DerInputStream(data);
364         DerValue[] seq = in.getSequence(3);
365         return AlgorithmId.parse(seq[1]).getName();
366     }
367
368     @Override
369     public void output(PrintWriter out, Language l, Map<String, Object> vars) {
370         if (csr == null) {
371             HashMap<String, Object> vars2 = new HashMap<String, Object>(vars);
372             vars2.put("csrf", getCSRFToken());
373             vars2.put("csrf_name", getCsrfFieldName());
374             vars2.put("spkacChallenge", spkacChallenge);
375             tIni.output(out, l, vars2);
376             return;
377         } else {
378             super.output(out, l, vars);
379         }
380     }
381
382     @Override
383     protected void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
384         HashMap<String, Object> vars2 = new HashMap<String, Object>(vars);
385         vars2.put("CCA", "<a href='/policy/CAcertCommunityAgreement.html'>CCA</a>");
386
387         StringBuffer content = new StringBuffer();
388         for (SubjectAlternateName SAN : SANs) {
389             content.append(SAN.getType().toString().toLowerCase());
390             content.append(':');
391             content.append(SAN.getName());
392             content.append('\n');
393         }
394
395         vars2.put("CN", CN);
396         vars2.put("emails", content.toString());
397         vars2.put("hashs", new HashAlgorithms(selectedDigest));
398         vars2.put("profiles", new IterableDataset() {
399
400             int i = 1;
401
402             @Override
403             public boolean next(Language l, Map<String, Object> vars) {
404                 CertificateProfile cp = CertificateProfile.getById(i++);
405                 if (cp == null) {
406                     return false;
407                 }
408                 if (cp.getId() == profile.getId()) {
409                     vars.put("selected", " selected");
410                 } else {
411                     vars.put("selected", "");
412                 }
413                 vars.put("key", cp.getKeyName());
414                 vars.put("name", cp.getVisibleName());
415                 return true;
416             }
417         });
418         t.output(out, l, vars2);
419     }
420 }