1 package org.cacert.gigi.pages.account;
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;
16 import java.util.TreeSet;
18 import javax.servlet.http.HttpServletRequest;
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.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;
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;
63 * This class represents a form that is used for issuing certificates. This
64 * class uses "sun.security" and therefore needs "-XDignore.symbol.file"
66 public class CertificateIssueForm extends Form {
68 public static final String DEFAULT_CN = "CAcert WoT User";
70 private final static Template t = new Template(CertificateIssueForm.class.getResource("CertificateIssueForm.templ"));
72 private final static Template tIni = new Template(CertificateAdd.class.getResource("RequestCertificate.templ"));
74 public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
75 1, 3, 6, 1, 5, 5, 7, 3, 1
78 public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
79 1, 3, 6, 1, 5, 5, 7, 3, 2
82 public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
83 1, 3, 6, 1, 5, 5, 7, 3, 3
86 public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
87 1, 3, 6, 1, 5, 5, 7, 3, 4
90 public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
91 1, 3, 6, 1, 5, 5, 7, 3, 8
94 public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
95 1, 3, 6, 1, 5, 5, 7, 3, 9
100 private CSRType csrType;
104 private String spkacChallenge;
106 public String CN = DEFAULT_CN;
108 private Set<SubjectAlternateName> SANs = new LinkedHashSet<>();
110 private Digest selectedDigest = Digest.getDefault();
112 CertificateValiditySelector issueDate = new CertificateValiditySelector();
114 private boolean login;
116 private CertificateProfile profile = CertificateProfile.getById(1);
118 public CertificateIssueForm(HttpServletRequest hsr) {
120 u = Page.getUser(hsr);
121 spkacChallenge = RandomToken.generateToken(16);
124 private Certificate result;
126 public Certificate getResult() {
131 public boolean submit(PrintWriter out, HttpServletRequest req) {
132 String csr = req.getParameter("CSR");
133 String spkac = req.getParameter("SPKAC");
137 byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
138 PKCS10 parsed = new PKCS10(data);
139 PKCS10Attributes atts = parsed.getAttributes();
141 for (PKCS10Attribute b : atts.getAttributes()) {
143 if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
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));
159 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
160 // parse invalid SANs
165 for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
166 if (c instanceof SubjectAlternativeNameExtension) {
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()));
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())) {
184 profile = CertificateProfile.getByName("server");
185 } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
187 profile = CertificateProfile.getByName("client");
188 } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
190 } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
192 profile = CertificateProfile.getByName("mail");
193 } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
195 } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
200 // Unknown requested extension
205 out.println(parsed.getSubjectName().getCommonName());
206 out.println(parsed.getSubjectName().getCountry());
208 out.println("CSR DN: " + parsed.getSubjectName() + "<br/>");
209 PublicKey pk = parsed.getSubjectPublicKeyInfo();
210 checkKeyStrength(pk, out);
211 String sign = getSignatureAlgorithm(data);
214 out.println("<br/>digest: " + sign + "<br/>");
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");
225 checkKeyStrength(parsed.getPubkey(), out);
226 String sign = getSignatureAlgorithm(data);
228 out.println("<br/>digest: " + sign + "<br/>");
231 this.csr = "SPKAC=" + cleanedSPKAC;
232 this.csrType = CSRType.SPKAC;
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);
242 profile = CertificateProfile.getByName(req.getParameter("profile"));
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) {
252 pDNS = san.getName();
254 filteredSANs.add(san);
257 } else if (san.getType() == SANType.EMAIL) {
258 if (u.isValidEmail(san.getName()) && !server) {
260 pMail = san.getName();
262 filteredSANs.add(san);
266 outputError(out, req, "The requested Subject alternate name \"%s\" has been removed.",//
267 san.getType().toString().toLowerCase() + ":" + san.getName());
270 if ( !u.isValidName(CN) && !server && !CN.equals(DEFAULT_CN)) {
272 outputError(out, req, "The real name entered cannot be verified with your account.");
275 final StringBuffer subject = new StringBuffer();
276 if (server && pDNS != null) {
277 subject.append("/commonName=");
278 subject.append(pDNS);
280 outputError(out, req, "No email is included in this certificate.");
284 outputError(out, req, "No real name is included in this certificate.");
287 subject.append("/commonName=");
290 subject.append("/emailAddress=");
291 subject.append(pMail);
294 if (req.getParameter("CCA") == null) {
295 outputError(out, req, "You need to accept the CCA.");
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);
306 } catch (IOException e) {
308 } catch (IllegalArgumentException e) {
310 throw new GigiApiException("Certificate Request format is invalid.");
311 } catch (GeneralSecurityException e) {
313 throw new GigiApiException("Certificate Request format is invalid.");
314 } catch (InterruptedException e) {
316 } catch (SQLException e) {
317 throw new GigiApiException(e);
319 } catch (GigiApiException e) {
320 e.format(out, Page.getLanguage(req));
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;
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("")) {
342 if (parts[0].contains("@")) {
343 parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
345 parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
350 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase());
354 parsedNames.add(new SubjectAlternateName(t, parts[1]));
355 } catch (IllegalArgumentException e) {
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());
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();
387 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
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);
396 super.output(out, l, vars);
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>");
405 StringBuffer content = new StringBuffer();
406 for (SubjectAlternateName SAN : SANs) {
407 content.append(SAN.getType().toString().toLowerCase());
409 content.append(SAN.getName());
410 content.append('\n');
414 vars2.put("validity", issueDate);
415 vars2.put("emails", content.toString());
416 vars2.put("hashs", new HashAlgorithms(selectedDigest));
417 vars2.put("profiles", new IterableDataset() {
422 public boolean next(Language l, Map<String, Object> vars) {
423 CertificateProfile cp = CertificateProfile.getById(i++);
427 if (cp.getId() == profile.getId()) {
428 vars.put("selected", " selected");
430 vars.put("selected", "");
432 vars.put("key", cp.getKeyName());
433 vars.put("name", cp.getVisibleName());
437 t.output(out, l, vars2);