]> WPIA git - gigi.git/blob - src/org/cacert/gigi/pages/account/CertificateIssueForm.java
FIX: Cleanup fields
[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     public 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     private User u;
98
99     private CSRType csrType;
100
101     private String csr;
102
103     private String spkacChallenge;
104
105     public String CN = DEFAULT_CN;
106
107     private Set<SubjectAlternateName> SANs = new LinkedHashSet<>();
108
109     private Digest selectedDigest = Digest.getDefault();
110
111     private boolean login;
112
113     private 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     private 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                                         profile = CertificateProfile.getByName("server");
182                                     } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
183                                         // client
184                                         profile = CertificateProfile.getByName("client");
185                                     } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
186                                         // code sign
187                                     } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
188                                         // emailProtection
189                                         profile = CertificateProfile.getByName("mail");
190                                     } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
191                                         // timestamp
192                                     } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
193                                         // OCSP
194                                     }
195                                 }
196                             } else {
197                                 // Unknown requested extension
198                             }
199                         }
200
201                     }
202                     out.println(parsed.getSubjectName().getCommonName());
203                     out.println(parsed.getSubjectName().getCountry());
204
205                     out.println("CSR DN: " + parsed.getSubjectName() + "<br/>");
206                     PublicKey pk = parsed.getSubjectPublicKeyInfo();
207                     checkKeyStrength(pk, out);
208                     String sign = getSignatureAlgorithm(data);
209                     guessDigest(sign);
210
211                     out.println("<br/>digest: " + sign + "<br/>");
212
213                     this.csr = csr;
214                     this.csrType = CSRType.CSR;
215                 } else if (spkac != null) {
216                     String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
217                     byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
218                     SPKAC parsed = new SPKAC(data);
219                     if ( !parsed.getChallenge().equals(spkacChallenge)) {
220                         throw new GigiApiException("Challenge mismatch");
221                     }
222                     checkKeyStrength(parsed.getPubkey(), out);
223                     String sign = getSignatureAlgorithm(data);
224                     guessDigest(sign);
225                     out.println("<br/>digest: " + sign + "<br/>");
226
227                     // spkacChallenge
228                     this.csr = "SPKAC=" + cleanedSPKAC;
229                     this.csrType = CSRType.SPKAC;
230
231                 } else {
232                     login = "1".equals(req.getParameter("login"));
233                     CN = req.getParameter("CN");
234                     String hashAlg = req.getParameter("hash_alg");
235                     if (hashAlg != null) {
236                         selectedDigest = Digest.valueOf(hashAlg);
237                     }
238                     profile = CertificateProfile.getByName(req.getParameter("profile"));
239
240                     String pDNS = null;
241                     String pMail = null;
242                     Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
243                     boolean server = profile.getKeyName().equals("server");
244                     for (SubjectAlternateName san : parseSANBox(req.getParameter("SANs"))) {
245                         if (san.getType() == SANType.DNS) {
246                             if (u.isValidDomain(san.getName()) && server) {
247                                 if (pDNS == null) {
248                                     pDNS = san.getName();
249                                 }
250                                 filteredSANs.add(san);
251                                 continue;
252                             }
253                         } else if (san.getType() == SANType.EMAIL) {
254                             if (u.isValidEmail(san.getName()) && !server) {
255                                 if (pMail == null) {
256                                     pMail = san.getName();
257                                 }
258                                 filteredSANs.add(san);
259                                 continue;
260                             }
261                         }
262                         outputError(out, req, "The requested Subject alternate name \"%s\" has been removed.",//
263                                 san.getType().toString().toLowerCase() + ":" + san.getName());
264                     }
265                     SANs = filteredSANs;
266                     if ( !u.isValidName(CN) && !server && !CN.equals(DEFAULT_CN)) {
267                         CN = DEFAULT_CN;
268                         outputError(out, req, "The real name entered cannot be verified with your account.");
269                     }
270
271                     final StringBuffer subject = new StringBuffer();
272                     if (server && pDNS != null) {
273                         subject.append("/commonName=");
274                         subject.append(pDNS);
275                         if (pMail != null) {
276                             outputError(out, req, "No email is included in this certificate.");
277                         }
278                         if (CN.equals("")) {
279                             CN = "";
280                             outputError(out, req, "No real name is included in this certificate.");
281                         }
282                     } else {
283                         subject.append("/commonName=");
284                         subject.append(CN);
285                         if (pMail != null) {
286                             subject.append("/emailAddress=");
287                             subject.append(pMail);
288                         }
289                     }
290                     if (req.getParameter("CCA") == null) {
291                         outputError(out, req, "You need to accept the CCA.");
292                     }
293                     if (isFailed(out)) {
294                         return false;
295                     }
296
297                     result = new Certificate(LoginPage.getUser(req).getId(), subject.toString(), selectedDigest.toString(), //
298                             this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
299                     result.issue().waitFor(60000);
300                     return true;
301                 }
302             } catch (IOException e) {
303                 e.printStackTrace();
304             } catch (IllegalArgumentException e) {
305                 e.printStackTrace();
306                 throw new GigiApiException("Certificate Request format is invalid.");
307             } catch (GeneralSecurityException e) {
308                 e.printStackTrace();
309                 throw new GigiApiException("Certificate Request format is invalid.");
310             } catch (InterruptedException e) {
311                 e.printStackTrace();
312             } catch (SQLException e) {
313                 throw new GigiApiException(e);
314             }
315         } catch (GigiApiException e) {
316             e.format(out, Page.getLanguage(req));
317         }
318         return false;
319     }
320
321     private void guessDigest(String sign) {
322         if (sign.toLowerCase().startsWith("sha512")) {
323             selectedDigest = Digest.SHA512;
324         } else if (sign.toLowerCase().startsWith("sha384")) {
325             selectedDigest = Digest.SHA384;
326         }
327     }
328
329     private TreeSet<SubjectAlternateName> parseSANBox(String SANs) {
330         String[] SANparts = SANs.split("[\r\n]+|, *");
331         TreeSet<SubjectAlternateName> parsedNames = new TreeSet<>();
332         for (String SANline : SANparts) {
333             String[] parts = SANline.split(":", 2);
334             if (parts.length == 1) {
335                 if (parts[0].trim().equals("")) {
336                     continue;
337                 }
338                 if (parts[0].contains("@")) {
339                     parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
340                 } else {
341                     parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
342                 }
343                 continue;
344             }
345             try {
346                 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase());
347                 if (t == null) {
348                     continue;
349                 }
350                 parsedNames.add(new SubjectAlternateName(t, parts[1]));
351             } catch (IllegalArgumentException e) {
352                 // invalid enum type
353                 continue;
354             }
355         }
356         return parsedNames;
357     }
358
359     private void checkKeyStrength(PublicKey pk, PrintWriter out) {
360         out.println("Type: " + pk.getAlgorithm() + "<br/>");
361         if (pk instanceof RSAPublicKey) {
362             out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
363             out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
364         } else if (pk instanceof DSAPublicKey) {
365             DSAPublicKey dpk = (DSAPublicKey) pk;
366             out.println("Length: " + dpk.getY().bitLength() + "<br/>");
367             out.println(dpk.getParams());
368         } else if (pk instanceof ECPublicKey) {
369             ECPublicKey epk = (ECPublicKey) pk;
370             out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
371             out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
372             out.println(epk.getParams().getCurve());
373         }
374     }
375
376     private static String getSignatureAlgorithm(byte[] data) throws IOException {
377         DerInputStream in = new DerInputStream(data);
378         DerValue[] seq = in.getSequence(3);
379         return AlgorithmId.parse(seq[1]).getName();
380     }
381
382     @Override
383     public void output(PrintWriter out, Language l, Map<String, Object> vars) {
384         if (csr == null) {
385             HashMap<String, Object> vars2 = new HashMap<String, Object>(vars);
386             vars2.put("csrf", getCSRFToken());
387             vars2.put("csrf_name", getCsrfFieldName());
388             vars2.put("spkacChallenge", spkacChallenge);
389             tIni.output(out, l, vars2);
390             return;
391         } else {
392             super.output(out, l, vars);
393         }
394     }
395
396     @Override
397     protected void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
398         HashMap<String, Object> vars2 = new HashMap<String, Object>(vars);
399         vars2.put("CCA", "<a href='/policy/CAcertCommunityAgreement.html'>CCA</a>");
400
401         StringBuffer content = new StringBuffer();
402         for (SubjectAlternateName SAN : SANs) {
403             content.append(SAN.getType().toString().toLowerCase());
404             content.append(':');
405             content.append(SAN.getName());
406             content.append('\n');
407         }
408
409         vars2.put("CN", CN);
410         vars2.put("emails", content.toString());
411         vars2.put("hashs", new HashAlgorithms(selectedDigest));
412         vars2.put("profiles", new IterableDataset() {
413
414             int i = 1;
415
416             @Override
417             public boolean next(Language l, Map<String, Object> vars) {
418                 CertificateProfile cp = CertificateProfile.getById(i++);
419                 if (cp == null) {
420                     return false;
421                 }
422                 if (cp.getId() == profile.getId()) {
423                     vars.put("selected", " selected");
424                 } else {
425                     vars.put("selected", "");
426                 }
427                 vars.put("key", cp.getKeyName());
428                 vars.put("name", cp.getVisibleName());
429                 return true;
430             }
431         });
432         t.output(out, l, vars2);
433     }
434 }