]> WPIA git - gigi.git/blob - src/org/cacert/gigi/pages/account/certs/CertificateIssueForm.java
ADD: Organisation selection in certificateIssueForm
[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     public CertificateIssueForm(HttpServletRequest hsr) {
121         super(hsr);
122         u = Page.getUser(hsr);
123         spkacChallenge = RandomToken.generateToken(16);
124     }
125
126     private Certificate result;
127
128     public Certificate getResult() {
129         return result;
130     }
131
132     @Override
133     public boolean submit(PrintWriter out, HttpServletRequest req) {
134         String csr = req.getParameter("CSR");
135         String spkac = req.getParameter("SPKAC");
136         try {
137             try {
138                 if (csr != null) {
139                     byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
140                     PKCS10 parsed = new PKCS10(data);
141                     PKCS10Attributes atts = parsed.getAttributes();
142
143                     for (PKCS10Attribute b : atts.getAttributes()) {
144
145                         if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
146                             // unknown attrib
147                             continue;
148                         }
149
150                         for (RDN r : parsed.getSubjectName().rdns()) {
151                             for (AVA a : r.avas()) {
152                                 if (a.getObjectIdentifier().equals((Object) PKCS9Attribute.EMAIL_ADDRESS_OID)) {
153                                     SANs.add(new SubjectAlternateName(SANType.EMAIL, a.getValueString()));
154                                 } else if (a.getObjectIdentifier().equals((Object) X500Name.commonName_oid)) {
155                                     String value = a.getValueString();
156                                     if (value.contains(".") && !value.contains(" ")) {
157                                         SANs.add(new SubjectAlternateName(SANType.DNS, value));
158                                     } else {
159                                         CN = value;
160                                     }
161                                 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
162                                     // parse invalid SANs
163                                 }
164                             }
165                         }
166
167                         for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
168                             if (c instanceof SubjectAlternativeNameExtension) {
169
170                                 SubjectAlternativeNameExtension san = (SubjectAlternativeNameExtension) c;
171                                 GeneralNames obj = san.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
172                                 for (int i = 0; i < obj.size(); i++) {
173                                     GeneralName generalName = obj.get(i);
174                                     GeneralNameInterface peeled = generalName.getName();
175                                     if (peeled instanceof DNSName) {
176                                         SANs.add(new SubjectAlternateName(SANType.DNS, ((DNSName) peeled).getName()));
177                                     } else if (peeled instanceof RFC822Name) {
178                                         SANs.add(new SubjectAlternateName(SANType.EMAIL, ((RFC822Name) peeled).getName()));
179                                     }
180                                 }
181                             } else if (c instanceof ExtendedKeyUsageExtension) {
182                                 ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
183                                 for (String s : ekue.getExtendedKeyUsage()) {
184                                     if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
185                                         // server
186                                         profile = CertificateProfile.getByName("server");
187                                     } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
188                                         // client
189                                         profile = CertificateProfile.getByName("client");
190                                     } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
191                                         // code sign
192                                     } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
193                                         // emailProtection
194                                         profile = CertificateProfile.getByName("mail");
195                                     } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
196                                         // timestamp
197                                     } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
198                                         // OCSP
199                                     }
200                                 }
201                             } else {
202                                 // Unknown requested extension
203                             }
204                         }
205
206                     }
207                     out.println(parsed.getSubjectName().getCommonName());
208                     out.println(parsed.getSubjectName().getCountry());
209
210                     out.println("CSR DN: " + parsed.getSubjectName() + "<br/>");
211                     PublicKey pk = parsed.getSubjectPublicKeyInfo();
212                     checkKeyStrength(pk, out);
213                     String sign = getSignatureAlgorithm(data);
214                     guessDigest(sign);
215
216                     out.println("<br/>digest: " + sign + "<br/>");
217
218                     this.csr = csr;
219                     this.csrType = CSRType.CSR;
220                 } else if (spkac != null) {
221                     String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
222                     byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
223                     SPKAC parsed = new SPKAC(data);
224                     if ( !parsed.getChallenge().equals(spkacChallenge)) {
225                         throw new GigiApiException("Challenge mismatch");
226                     }
227                     checkKeyStrength(parsed.getPubkey(), out);
228                     String sign = getSignatureAlgorithm(data);
229                     guessDigest(sign);
230                     out.println("<br/>digest: " + sign + "<br/>");
231
232                     // spkacChallenge
233                     this.csr = "SPKAC=" + cleanedSPKAC;
234                     this.csrType = CSRType.SPKAC;
235
236                 } else {
237                     login = "1".equals(req.getParameter("login"));
238                     issueDate.update(req);
239                     CN = req.getParameter("CN");
240                     String hashAlg = req.getParameter("hash_alg");
241                     if (hashAlg != null) {
242                         selectedDigest = Digest.valueOf(hashAlg);
243                     }
244                     profile = CertificateProfile.getByName(req.getParameter("profile"));
245                     if ( !u.canIssue(profile)) {
246                         profile = CertificateProfile.getById(1);
247                         outputError(out, req, "Certificate Profile is invalid.");
248                         return false;
249                     }
250
251                     String pDNS = null;
252                     String pMail = null;
253                     Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
254                     boolean server = profile.getKeyName().equals("server");
255                     for (SubjectAlternateName san : parseSANBox(req.getParameter("SANs"))) {
256                         if (san.getType() == SANType.DNS) {
257                             if (u.isValidDomain(san.getName()) && server) {
258                                 if (pDNS == null) {
259                                     pDNS = san.getName();
260                                 }
261                                 filteredSANs.add(san);
262                                 continue;
263                             }
264                         } else if (san.getType() == SANType.EMAIL) {
265                             if (u.isValidEmail(san.getName()) && !server) {
266                                 if (pMail == null) {
267                                     pMail = san.getName();
268                                 }
269                                 filteredSANs.add(san);
270                                 continue;
271                             }
272                         }
273                         outputError(out, req, "The requested Subject alternate name \"%s\" has been removed.",//
274                                 san.getType().toString().toLowerCase() + ":" + san.getName());
275                     }
276                     SANs = filteredSANs;
277                     if ( !u.isValidName(CN) && !server && !CN.equals(DEFAULT_CN)) {
278                         CN = DEFAULT_CN;
279                         outputError(out, req, "The real name entered cannot be verified with your account.");
280                     }
281
282                     final StringBuffer subject = new StringBuffer();
283                     if (server && pDNS != null) {
284                         subject.append("/commonName=");
285                         subject.append(pDNS);
286                         if (pMail != null) {
287                             outputError(out, req, "No email is included in this certificate.");
288                         }
289                         if (CN.equals("")) {
290                             CN = "";
291                             outputError(out, req, "No real name is included in this certificate.");
292                         }
293                     } else {
294                         subject.append("/commonName=");
295                         subject.append(CN);
296                         if (pMail != null) {
297                             subject.append("/emailAddress=");
298                             subject.append(pMail);
299                         }
300                     }
301                     if (req.getParameter("CCA") == null) {
302                         outputError(out, req, "You need to accept the CCA.");
303                     }
304                     if (isFailed(out)) {
305                         return false;
306                     }
307
308                     result = new Certificate(LoginPage.getUser(req), subject.toString(), selectedDigest.toString(), //
309                             this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
310                     result.issue(issueDate.getFrom(), issueDate.getTo()).waitFor(60000);
311                     return true;
312                 }
313             } catch (IOException e) {
314                 e.printStackTrace();
315             } catch (IllegalArgumentException e) {
316                 e.printStackTrace();
317                 throw new GigiApiException("Certificate Request format is invalid.");
318             } catch (GeneralSecurityException e) {
319                 e.printStackTrace();
320                 throw new GigiApiException("Certificate Request format is invalid.");
321             } catch (InterruptedException e) {
322                 e.printStackTrace();
323             }
324         } catch (GigiApiException e) {
325             e.format(out, Page.getLanguage(req));
326         }
327         return false;
328     }
329
330     private void guessDigest(String sign) {
331         if (sign.toLowerCase().startsWith("sha512")) {
332             selectedDigest = Digest.SHA512;
333         } else if (sign.toLowerCase().startsWith("sha384")) {
334             selectedDigest = Digest.SHA384;
335         }
336     }
337
338     private TreeSet<SubjectAlternateName> parseSANBox(String SANs) {
339         String[] SANparts = SANs.split("[\r\n]+|, *");
340         TreeSet<SubjectAlternateName> parsedNames = new TreeSet<>();
341         for (String SANline : SANparts) {
342             String[] parts = SANline.split(":", 2);
343             if (parts.length == 1) {
344                 if (parts[0].trim().equals("")) {
345                     continue;
346                 }
347                 if (parts[0].contains("@")) {
348                     parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
349                 } else {
350                     parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
351                 }
352                 continue;
353             }
354             try {
355                 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase());
356                 if (t == null) {
357                     continue;
358                 }
359                 parsedNames.add(new SubjectAlternateName(t, parts[1]));
360             } catch (IllegalArgumentException e) {
361                 // invalid enum type
362                 continue;
363             }
364         }
365         return parsedNames;
366     }
367
368     private void checkKeyStrength(PublicKey pk, PrintWriter out) {
369         out.println("Type: " + pk.getAlgorithm() + "<br/>");
370         if (pk instanceof RSAPublicKey) {
371             out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
372             out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
373         } else if (pk instanceof DSAPublicKey) {
374             DSAPublicKey dpk = (DSAPublicKey) pk;
375             out.println("Length: " + dpk.getY().bitLength() + "<br/>");
376             out.println(dpk.getParams());
377         } else if (pk instanceof ECPublicKey) {
378             ECPublicKey epk = (ECPublicKey) pk;
379             out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
380             out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
381             out.println(epk.getParams().getCurve());
382         }
383     }
384
385     private static String getSignatureAlgorithm(byte[] data) throws IOException {
386         DerInputStream in = new DerInputStream(data);
387         DerValue[] seq = in.getSequence(3);
388         return AlgorithmId.parse(seq[1]).getName();
389     }
390
391     @Override
392     public void output(PrintWriter out, Language l, Map<String, Object> vars) {
393         if (csr == null) {
394             HashMap<String, Object> vars2 = new HashMap<String, Object>(vars);
395             vars2.put("csrf", getCSRFToken());
396             vars2.put("csrf_name", getCsrfFieldName());
397             vars2.put("spkacChallenge", spkacChallenge);
398             tIni.output(out, l, vars2);
399             return;
400         } else {
401             super.output(out, l, vars);
402         }
403     }
404
405     @Override
406     protected void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
407         HashMap<String, Object> vars2 = new HashMap<String, Object>(vars);
408         vars2.put("CCA", "<a href='/policy/CAcertCommunityAgreement.html'>CCA</a>");
409
410         StringBuffer content = new StringBuffer();
411         for (SubjectAlternateName SAN : SANs) {
412             content.append(SAN.getType().toString().toLowerCase());
413             content.append(':');
414             content.append(SAN.getName());
415             content.append('\n');
416         }
417
418         vars2.put("CN", CN);
419         vars2.put("validity", issueDate);
420         vars2.put("emails", content.toString());
421         vars2.put("hashs", new HashAlgorithms(selectedDigest));
422         vars2.put("profiles", new IterableDataset() {
423
424             int i = 1;
425
426             @Override
427             public boolean next(Language l, Map<String, Object> vars) {
428                 CertificateProfile cp;
429                 do {
430                     cp = CertificateProfile.getById(i++);
431                     if (cp == null) {
432                         return false;
433                     }
434                 } while ( !u.canIssue(cp));
435
436                 if (cp.getId() == profile.getId()) {
437                     vars.put("selected", " selected");
438                 } else {
439                     vars.put("selected", "");
440                 }
441                 vars.put("key", cp.getKeyName());
442                 vars.put("name", cp.getVisibleName());
443                 return true;
444             }
445         });
446         final List<Organisation> orgs = u.getOrganisations();
447         vars2.put("orga", orgs.size() == 0 ? null : new IterableDataset() {
448
449             Iterator<Organisation> iter = orgs.iterator();
450
451             @Override
452             public boolean next(Language l, Map<String, Object> vars) {
453                 if ( !iter.hasNext()) {
454                     return false;
455                 }
456                 Organisation orga = iter.next();
457                 vars.put("key", orga.getId());
458                 vars.put("name", orga.getName());
459                 return true;
460             }
461         });
462
463         t.output(out, l, vars2);
464     }
465 }