1 package org.cacert.gigi.pages.account.certs;
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;
17 import java.util.TreeSet;
19 import javax.servlet.http.HttpServletRequest;
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.HashAlgorithms;
34 import org.cacert.gigi.output.template.Form;
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;
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;
65 * This class represents a form that is used for issuing certificates. This
66 * class uses "sun.security" and therefore needs "-XDignore.symbol.file"
68 public class CertificateIssueForm extends Form {
70 public static final String DEFAULT_CN = "CAcert WoT User";
72 private final static Template t = new Template(CertificateIssueForm.class.getResource("CertificateIssueForm.templ"));
74 private final static Template tIni = new Template(CertificateAdd.class.getResource("RequestCertificate.templ"));
76 public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
77 1, 3, 6, 1, 5, 5, 7, 3, 1
80 public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
81 1, 3, 6, 1, 5, 5, 7, 3, 2
84 public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
85 1, 3, 6, 1, 5, 5, 7, 3, 3
88 public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
89 1, 3, 6, 1, 5, 5, 7, 3, 4
92 public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
93 1, 3, 6, 1, 5, 5, 7, 3, 8
96 public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
97 1, 3, 6, 1, 5, 5, 7, 3, 9
102 private CSRType csrType;
106 private String spkacChallenge;
108 public String CN = DEFAULT_CN;
110 private Set<SubjectAlternateName> SANs = new LinkedHashSet<>();
112 private Digest selectedDigest = Digest.getDefault();
114 CertificateValiditySelector issueDate = new CertificateValiditySelector();
116 private boolean login;
118 private CertificateProfile profile = CertificateProfile.getById(1);
120 private String ou = "";
122 private Organisation org = null;
124 public CertificateIssueForm(HttpServletRequest hsr) {
126 u = Page.getUser(hsr);
127 spkacChallenge = RandomToken.generateToken(16);
130 private Certificate result;
132 public Certificate getResult() {
137 public boolean submit(PrintWriter out, HttpServletRequest req) {
138 String csr = req.getParameter("CSR");
139 String spkac = req.getParameter("SPKAC");
143 byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
144 PKCS10 parsed = new PKCS10(data);
145 PKCS10Attributes atts = parsed.getAttributes();
147 for (PKCS10Attribute b : atts.getAttributes()) {
149 if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
154 for (RDN r : parsed.getSubjectName().rdns()) {
155 for (AVA a : r.avas()) {
156 if (a.getObjectIdentifier().equals((Object) PKCS9Attribute.EMAIL_ADDRESS_OID)) {
157 SANs.add(new SubjectAlternateName(SANType.EMAIL, a.getValueString()));
158 } else if (a.getObjectIdentifier().equals((Object) X500Name.commonName_oid)) {
159 String value = a.getValueString();
160 if (value.contains(".") && !value.contains(" ")) {
161 SANs.add(new SubjectAlternateName(SANType.DNS, value));
165 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
166 // parse invalid SANs
171 for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
172 if (c instanceof SubjectAlternativeNameExtension) {
174 SubjectAlternativeNameExtension san = (SubjectAlternativeNameExtension) c;
175 GeneralNames obj = san.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
176 for (int i = 0; i < obj.size(); i++) {
177 GeneralName generalName = obj.get(i);
178 GeneralNameInterface peeled = generalName.getName();
179 if (peeled instanceof DNSName) {
180 SANs.add(new SubjectAlternateName(SANType.DNS, ((DNSName) peeled).getName()));
181 } else if (peeled instanceof RFC822Name) {
182 SANs.add(new SubjectAlternateName(SANType.EMAIL, ((RFC822Name) peeled).getName()));
185 } else if (c instanceof ExtendedKeyUsageExtension) {
186 ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
187 for (String s : ekue.getExtendedKeyUsage()) {
188 if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
190 profile = CertificateProfile.getByName("server");
191 } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
193 profile = CertificateProfile.getByName("client");
194 } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
196 } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
198 profile = CertificateProfile.getByName("mail");
199 } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
201 } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
206 // Unknown requested extension
211 out.println(parsed.getSubjectName().getCommonName());
212 out.println(parsed.getSubjectName().getCountry());
214 out.println("CSR DN: " + parsed.getSubjectName() + "<br/>");
215 PublicKey pk = parsed.getSubjectPublicKeyInfo();
216 checkKeyStrength(pk, out);
217 String sign = getSignatureAlgorithm(data);
220 out.println("<br/>digest: " + sign + "<br/>");
223 this.csrType = CSRType.CSR;
224 } else if (spkac != null) {
225 String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
226 byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
227 SPKAC parsed = new SPKAC(data);
228 if ( !parsed.getChallenge().equals(spkacChallenge)) {
229 throw new GigiApiException("Challenge mismatch");
231 checkKeyStrength(parsed.getPubkey(), out);
232 String sign = getSignatureAlgorithm(data);
234 out.println("<br/>digest: " + sign + "<br/>");
237 this.csr = "SPKAC=" + cleanedSPKAC;
238 this.csrType = CSRType.SPKAC;
241 login = "1".equals(req.getParameter("login"));
242 issueDate.update(req);
243 CN = req.getParameter("CN");
244 String hashAlg = req.getParameter("hash_alg");
245 if (hashAlg != null) {
246 selectedDigest = Digest.valueOf(hashAlg);
248 profile = CertificateProfile.getByName(req.getParameter("profile"));
249 String newOrgStr = req.getParameter("org");
250 if (newOrgStr != null) {
251 Organisation neworg = Organisation.getById(Integer.parseInt(newOrgStr));
252 if (neworg == null || u.getOrganisations().contains(neworg)) {
255 outputError(out, req, "Selected Organisation is not part of your account.");
258 ou = req.getParameter("OU");
259 if ( !u.canIssue(profile)) {
260 profile = CertificateProfile.getById(1);
261 outputError(out, req, "Certificate Profile is invalid.");
267 Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
268 boolean server = profile.getKeyName().equals("server");
269 for (SubjectAlternateName san : parseSANBox(req.getParameter("SANs"))) {
270 if (san.getType() == SANType.DNS) {
271 if (u.isValidDomain(san.getName()) && server) {
273 pDNS = san.getName();
275 filteredSANs.add(san);
278 } else if (san.getType() == SANType.EMAIL) {
279 if (u.isValidEmail(san.getName()) && !server) {
281 pMail = san.getName();
283 filteredSANs.add(san);
287 outputError(out, req, "The requested Subject alternate name \"%s\" has been removed.",//
288 san.getType().toString().toLowerCase() + ":" + san.getName());
291 if ( !u.isValidName(CN) && !server && !CN.equals(DEFAULT_CN)) {
293 outputError(out, req, "The name entered, does not match the details in your account. You cannot issue certificates with this name. Enter a name that matches the one that has been assured in your account.");
296 HashMap<String, String> subject = new HashMap<>();
297 if (server && pDNS != null) {
298 subject.put("CN", pDNS);
300 outputError(out, req, "No email is included in this certificate.");
304 outputError(out, req, "No real name is included in this certificate. The real name, you entered will be ignored.");
307 subject.put("CN", CN);
309 subject.put("EMAIL", pMail);
313 subject.put("O", org.getName());
314 subject.put("C", org.getState());
315 subject.put("ST", org.getProvince());
316 subject.put("L", org.getCity());
317 subject.put("OU", ou);
319 if (req.getParameter("CCA") == null) {
320 outputError(out, req, "You need to accept the CCA.");
326 result = new Certificate(LoginPage.getUser(req), subject, selectedDigest.toString(), //
327 this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
328 result.issue(issueDate.getFrom(), issueDate.getTo()).waitFor(60000);
331 } catch (IOException e) {
333 } catch (IllegalArgumentException e) {
335 throw new GigiApiException("Certificate Request format is invalid.");
336 } catch (GeneralSecurityException e) {
338 throw new GigiApiException("Certificate Request format is invalid.");
339 } catch (InterruptedException e) {
342 } catch (GigiApiException e) {
343 e.format(out, Page.getLanguage(req));
348 private void guessDigest(String sign) {
349 if (sign.toLowerCase().startsWith("sha512")) {
350 selectedDigest = Digest.SHA512;
351 } else if (sign.toLowerCase().startsWith("sha384")) {
352 selectedDigest = Digest.SHA384;
356 private TreeSet<SubjectAlternateName> parseSANBox(String SANs) {
357 String[] SANparts = SANs.split("[\r\n]+|, *");
358 TreeSet<SubjectAlternateName> parsedNames = new TreeSet<>();
359 for (String SANline : SANparts) {
360 String[] parts = SANline.split(":", 2);
361 if (parts.length == 1) {
362 if (parts[0].trim().equals("")) {
365 if (parts[0].contains("@")) {
366 parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
368 parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
373 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase());
377 parsedNames.add(new SubjectAlternateName(t, parts[1]));
378 } catch (IllegalArgumentException e) {
386 private void checkKeyStrength(PublicKey pk, PrintWriter out) {
387 out.println("Type: " + pk.getAlgorithm() + "<br/>");
388 if (pk instanceof RSAPublicKey) {
389 out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
390 out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
391 } else if (pk instanceof DSAPublicKey) {
392 DSAPublicKey dpk = (DSAPublicKey) pk;
393 out.println("Length: " + dpk.getY().bitLength() + "<br/>");
394 out.println(dpk.getParams());
395 } else if (pk instanceof ECPublicKey) {
396 ECPublicKey epk = (ECPublicKey) pk;
397 out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
398 out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
399 out.println(epk.getParams().getCurve());
403 private static String getSignatureAlgorithm(byte[] data) throws IOException {
404 DerInputStream in = new DerInputStream(data);
405 DerValue[] seq = in.getSequence(3);
406 return AlgorithmId.parse(seq[1]).getName();
410 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
412 HashMap<String, Object> vars2 = new HashMap<String, Object>(vars);
413 vars2.put("csrf", getCSRFToken());
414 vars2.put("csrf_name", getCsrfFieldName());
415 vars2.put("spkacChallenge", spkacChallenge);
416 tIni.output(out, l, vars2);
419 super.output(out, l, vars);
424 protected void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
425 HashMap<String, Object> vars2 = new HashMap<String, Object>(vars);
426 vars2.put("CCA", "<a href='/policy/CAcertCommunityAgreement.html'>CCA</a>");
428 StringBuffer content = new StringBuffer();
429 for (SubjectAlternateName SAN : SANs) {
430 content.append(SAN.getType().toString().toLowerCase());
432 content.append(SAN.getName());
433 content.append('\n');
437 vars2.put("department", ou);
438 vars2.put("validity", issueDate);
439 vars2.put("emails", content.toString());
440 vars2.put("hashs", new HashAlgorithms(selectedDigest));
441 vars2.put("profiles", new IterableDataset() {
446 public boolean next(Language l, Map<String, Object> vars) {
447 CertificateProfile cp;
449 cp = CertificateProfile.getById(i++);
453 } while ( !u.canIssue(cp));
455 if (cp.getId() == profile.getId()) {
456 vars.put("selected", " selected");
458 vars.put("selected", "");
460 vars.put("key", cp.getKeyName());
461 vars.put("name", cp.getVisibleName());
465 final List<Organisation> orgs = u.getOrganisations();
466 vars2.put("orga", orgs.size() == 0 ? null : new IterableDataset() {
468 Iterator<Organisation> iter = orgs.iterator();
471 public boolean next(Language l, Map<String, Object> vars) {
472 if ( !iter.hasNext()) {
475 Organisation orga = iter.next();
476 vars.put("key", orga.getId());
477 vars.put("name", orga.getName());
479 vars.put("selected", " selected");
481 vars.put("selected", "");
487 t.output(out, l, vars2);