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