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