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