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