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.Arrays;
11 import java.util.Base64;
12 import java.util.HashMap;
13 import java.util.HashSet;
14 import java.util.LinkedHashSet;
16 import java.util.TreeSet;
18 import javax.servlet.http.HttpServletRequest;
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.Certificate.CSRType;
24 import org.cacert.gigi.dbObjects.Certificate.SANType;
25 import org.cacert.gigi.dbObjects.Certificate.SubjectAlternateName;
26 import org.cacert.gigi.dbObjects.CertificateOwner;
27 import org.cacert.gigi.dbObjects.CertificateProfile;
28 import org.cacert.gigi.dbObjects.CertificateProfile.PropertyTemplate;
29 import org.cacert.gigi.dbObjects.Digest;
30 import org.cacert.gigi.dbObjects.Organisation;
31 import org.cacert.gigi.dbObjects.User;
32 import org.cacert.gigi.output.template.Scope;
33 import org.cacert.gigi.output.template.SprintfCommand;
34 import org.cacert.gigi.util.AuthorizationContext;
35 import org.cacert.gigi.util.PEM;
36 import org.cacert.gigi.util.RateLimit;
38 import sun.security.pkcs.PKCS9Attribute;
39 import sun.security.pkcs10.PKCS10;
40 import sun.security.pkcs10.PKCS10Attribute;
41 import sun.security.pkcs10.PKCS10Attributes;
42 import sun.security.util.DerInputStream;
43 import sun.security.util.DerValue;
44 import sun.security.util.ObjectIdentifier;
45 import sun.security.x509.AVA;
46 import sun.security.x509.AlgorithmId;
47 import sun.security.x509.CertificateExtensions;
48 import sun.security.x509.DNSName;
49 import sun.security.x509.ExtendedKeyUsageExtension;
50 import sun.security.x509.Extension;
51 import sun.security.x509.GeneralName;
52 import sun.security.x509.GeneralNameInterface;
53 import sun.security.x509.GeneralNames;
54 import sun.security.x509.PKIXExtensions;
55 import sun.security.x509.RDN;
56 import sun.security.x509.RFC822Name;
57 import sun.security.x509.SubjectAlternativeNameExtension;
58 import sun.security.x509.X500Name;
60 public class CertificateRequest {
62 public static final String DEFAULT_CN = "CAcert WoT User";
64 public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
65 1, 3, 6, 1, 5, 5, 7, 3, 1
68 public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
69 1, 3, 6, 1, 5, 5, 7, 3, 2
72 public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
73 1, 3, 6, 1, 5, 5, 7, 3, 3
76 public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
77 1, 3, 6, 1, 5, 5, 7, 3, 4
80 public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
81 1, 3, 6, 1, 5, 5, 7, 3, 8
84 public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
85 1, 3, 6, 1, 5, 5, 7, 3, 9
88 private CSRType csrType;
90 private final PublicKey pk;
94 public String name = DEFAULT_CN;
96 private Set<SubjectAlternateName> SANs;
98 private Digest selectedDigest = Digest.getDefault();
100 private CertificateProfile profile = CertificateProfile.getById(1);
102 private String ou = "";
104 private AuthorizationContext ctx;
106 private String pDNS, pMail;
108 public CertificateRequest(AuthorizationContext c, String csr) throws IOException, GeneralSecurityException, GigiApiException {
109 this(c, csr, (CertificateProfile) null);
112 public CertificateRequest(AuthorizationContext ctx, String csr, CertificateProfile cp) throws GeneralSecurityException, IOException, IOException {
116 } else if (ctx.getActor().getAssurancePoints() > 50) {
117 profile = CertificateProfile.getByName("client-a");
119 byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
120 PKCS10 parsed = new PKCS10(data);
121 PKCS10Attributes atts = parsed.getAttributes();
123 TreeSet<SubjectAlternateName> SANs = new TreeSet<>();
124 for (RDN r : parsed.getSubjectName().rdns()) {
125 for (AVA a : r.avas()) {
126 if (a.getObjectIdentifier().equals((Object) PKCS9Attribute.EMAIL_ADDRESS_OID)) {
127 SANs.add(new SubjectAlternateName(SANType.EMAIL, a.getValueString()));
128 } else if (a.getObjectIdentifier().equals((Object) X500Name.commonName_oid)) {
129 String value = a.getValueString();
130 if (value.contains(".") && !value.contains(" ")) {
131 SANs.add(new SubjectAlternateName(SANType.DNS, value));
135 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
136 // TODO? parse invalid SANs
141 for (PKCS10Attribute b : atts.getAttributes()) {
143 if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
148 for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
149 if (c instanceof SubjectAlternativeNameExtension) {
151 SubjectAlternativeNameExtension san = (SubjectAlternativeNameExtension) c;
152 GeneralNames obj = san.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
153 for (int i = 0; i < obj.size(); i++) {
154 GeneralName generalName = obj.get(i);
155 GeneralNameInterface peeled = generalName.getName();
156 if (peeled instanceof DNSName) {
157 SANs.add(new SubjectAlternateName(SANType.DNS, ((DNSName) peeled).getName()));
158 } else if (peeled instanceof RFC822Name) {
159 SANs.add(new SubjectAlternateName(SANType.EMAIL, ((RFC822Name) peeled).getName()));
162 } else if (c instanceof ExtendedKeyUsageExtension) {
163 ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
164 String appendix = "";
165 if (ctx.getActor().getAssurancePoints() >= 50) {
168 for (String s : ekue.getExtendedKeyUsage()) {
169 if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
171 profile = CertificateProfile.getByName("server" + appendix);
172 } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
174 profile = CertificateProfile.getByName("client" + appendix);
175 } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
177 } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
179 profile = CertificateProfile.getByName("mail" + appendix);
180 } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
182 } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
187 // Unknown requested extension
193 pk = parsed.getSubjectPublicKeyInfo();
194 String sign = getSignatureAlgorithm(data);
198 this.csrType = CSRType.CSR;
201 public CertificateRequest(AuthorizationContext ctx, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
203 String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
204 byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
205 SPKAC parsed = new SPKAC(data);
206 if ( !parsed.getChallenge().equals(spkacChallenge)) {
207 throw new GigiApiException("Challenge mismatch");
209 pk = parsed.getPubkey();
210 String sign = getSignatureAlgorithm(data);
212 this.SANs = new HashSet<>();
213 this.csr = "SPKAC=" + cleanedSPKAC;
214 this.csrType = CSRType.SPKAC;
218 private static String getSignatureAlgorithm(byte[] data) throws IOException {
219 DerInputStream in = new DerInputStream(data);
220 DerValue[] seq = in.getSequence(3);
221 return AlgorithmId.parse(seq[1]).getName();
224 private void guessDigest(String sign) {
225 if (sign.toLowerCase().startsWith("sha512")) {
226 selectedDigest = Digest.SHA512;
227 } else if (sign.toLowerCase().startsWith("sha384")) {
228 selectedDigest = Digest.SHA384;
232 public void checkKeyStrength(PrintWriter out) {
233 out.println("Type: " + pk.getAlgorithm() + "<br/>");
234 if (pk instanceof RSAPublicKey) {
235 out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
236 out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
237 } else if (pk instanceof DSAPublicKey) {
238 DSAPublicKey dpk = (DSAPublicKey) pk;
239 out.println("Length: " + dpk.getY().bitLength() + "<br/>");
240 out.println(dpk.getParams());
241 } else if (pk instanceof ECPublicKey) {
242 ECPublicKey epk = (ECPublicKey) pk;
243 out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
244 out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
245 out.println(epk.getParams().getCurve());
249 private Set<SubjectAlternateName> parseSANBox(String SANs) {
250 String[] SANparts = SANs.split("[\r\n]+|, *");
251 Set<SubjectAlternateName> parsedNames = new LinkedHashSet<>();
252 for (String SANline : SANparts) {
253 String[] parts = SANline.split(":", 2);
254 if (parts.length == 1) {
255 if (parts[0].trim().equals("")) {
258 if (parts[0].contains("@")) {
259 parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
261 parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
266 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase().trim());
270 parsedNames.add(new SubjectAlternateName(t, parts[1].trim()));
271 } catch (IllegalArgumentException e) {
279 public Set<SubjectAlternateName> getSANs() {
283 public String getName() {
287 public synchronized String getOu() {
288 if (ctx.getTarget() instanceof Organisation) {
291 throw new IllegalStateException();
294 public Digest getSelectedDigest() {
295 return selectedDigest;
298 public CertificateProfile getProfile() {
302 public synchronized boolean update(String nameIn, String hashAlg, String profileStr, String newOrgStr, String ou, String SANsStr, PrintWriter out, HttpServletRequest req) throws GigiApiException {
303 GigiApiException error = new GigiApiException();
305 if (hashAlg != null) {
306 selectedDigest = Digest.valueOf(hashAlg);
308 this.profile = CertificateProfile.getByName(profileStr);
309 if (ctx.getTarget() instanceof Organisation) {
313 if ( !this.profile.canBeIssuedBy(ctx.getTarget(), ctx.getActor())) {
314 this.profile = CertificateProfile.getById(1);
315 error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
319 verifySANs(error, profile, parseSANBox(SANsStr), ctx.getTarget());
321 if ( !error.isEmpty()) {
327 private void verifySANs(GigiApiException error, CertificateProfile p, Set<SubjectAlternateName> sANs2, CertificateOwner owner) {
328 Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
329 PropertyTemplate domainTemp = p.getTemplates().get("domain");
330 PropertyTemplate emailTemp = p.getTemplates().get("email");
333 for (SubjectAlternateName san : sANs2) {
334 if (san.getType() == SANType.DNS) {
335 if (domainTemp != null && owner.isValidDomain(san.getName())) {
336 if (pDNS != null && !domainTemp.isMultiple()) {
340 pDNS = san.getName();
342 filteredSANs.add(san);
346 } else if (san.getType() == SANType.EMAIL) {
347 if (emailTemp != null && owner.isValidEmail(san.getName())) {
348 if (pMail != null && !emailTemp.isMultiple()) {
352 pMail = san.getName();
354 filteredSANs.add(san);
359 HashMap<String, Object> vars = new HashMap<>();
360 vars.put("SAN", san.getType().toString().toLowerCase() + ":" + san.getName());
361 error.mergeInto(new GigiApiException(new Scope(new SprintfCommand(//
362 "The requested Subject alternate name \"{0}\" has been removed.", Arrays.asList("${SAN}")), vars)));
367 // domain email name name=WoTUser orga
368 public synchronized Certificate draft() throws GigiApiException {
370 GigiApiException error = new GigiApiException();
372 HashMap<String, String> subject = new HashMap<>();
373 PropertyTemplate domainTemp = profile.getTemplates().get("domain");
374 PropertyTemplate emailTemp = profile.getTemplates().get("email");
375 PropertyTemplate nameTemp = profile.getTemplates().get("name");
376 PropertyTemplate wotUserTemp = profile.getTemplates().get("name=WoTUser");
377 verifySANs(error, profile, SANs, ctx.getTarget());
379 // Ok, let's determine the CN
381 // 1. the user's "real name", iff the real name is to be included i.e.
382 // not empty (name), or to be forced to WOTUser
384 // 2. the user's "primary domain", iff "1." doesn't match and there is a
385 // primary domain. (domainTemp != null)
387 String verifiedCN = null;
388 if (ctx.getTarget() instanceof Organisation) {
389 if ( !name.equals("")) {
393 verifiedCN = verifyName(error, nameTemp, wotUserTemp, verifiedCN);
395 if (pDNS == null && domainTemp != null && domainTemp.isRequired()) {
396 error.mergeInto(new GigiApiException("Server Certificates require a DNS name."));
397 } else if (domainTemp != null && verifiedCN == null) {
398 // user may add domains
401 if (verifiedCN != null) {
402 subject.put("CN", verifiedCN);
406 if (emailTemp != null) {
407 subject.put("EMAIL", pMail);
409 // verify SANs should prevent this
411 error.mergeInto(new GigiApiException("You may not include an email in this certificate."));
414 if (emailTemp != null && emailTemp.isRequired()) {
415 error.mergeInto(new GigiApiException("You need to include an email in this certificate."));
419 if (ctx.getTarget() instanceof Organisation) {
420 Organisation org = (Organisation) ctx.getTarget();
421 subject.put("O", org.getName());
422 subject.put("C", org.getState());
423 subject.put("ST", org.getProvince());
424 subject.put("L", org.getCity());
426 subject.put("OU", ou);
429 System.out.println(subject);
430 if ( !error.isEmpty()) {
434 if (limit.isLimitExceeded(Integer.toString(ctx.getActor().getId()))) {
435 throw new GigiApiException("Rate Limit Exceeded");
437 return new Certificate(ctx.getTarget(), ctx.getActor(), subject, selectedDigest, //
438 this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
439 } catch (IOException e) {
445 // 100 per 10 minutes
446 private static final RateLimit limit = new RateLimit(100, 10 * 60 * 1000);
448 private String verifyName(GigiApiException error, PropertyTemplate nameTemp, PropertyTemplate wotUserTemp, String verifiedCN) {
450 // possible configurations: name {y,null,?}, name=WoTUser {y,null}
455 // ? y -> real, default
456 // ? null -> real, default, null
457 boolean realIsOK = false;
458 boolean nullIsOK = false;
459 boolean defaultIsOK = false;
460 if (wotUserTemp != null && ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple())) {
461 error.mergeInto(new GigiApiException("Internal configuration error detected."));
463 if (nameTemp != null && nameTemp.isRequired() && !nameTemp.isMultiple()) {
465 } else if (nameTemp == null) {
466 defaultIsOK = wotUserTemp != null;
467 nullIsOK = !defaultIsOK;
468 } else if (nameTemp != null && !nameTemp.isRequired() && !nameTemp.isMultiple()) {
471 nullIsOK = wotUserTemp == null;
473 error.mergeInto(new GigiApiException("Internal configuration error detected."));
475 if (ctx.getTarget() instanceof User) {
476 User u = (User) ctx.getTarget();
477 if (name != null && u.isValidName(name)) {
481 error.mergeInto(new GigiApiException("Your real name is not allowed in this certificate."));
484 } else if (nullIsOK) {
488 } else if (name != null && name.equals(DEFAULT_CN)) {
492 error.mergeInto(new GigiApiException("The default name is not allowed in this certificate."));
495 } else if (realIsOK) {
496 name = u.getName().toString();
499 } else if (name == null || name.equals("")) {
503 error.mergeInto(new GigiApiException("A name is required in this certificate."));
506 } else if (realIsOK) {
507 name = u.getName().toString();
511 error.mergeInto(new GigiApiException("The name you entered was invalid."));
514 if (wotUserTemp != null) {
515 if ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple()) {
516 error.mergeInto(new GigiApiException("Internal configuration error detected."));
518 if ( !name.equals(DEFAULT_CN)) {
520 error.mergeInto(new GigiApiException("You may not change the name for this certificate type."));
522 verifiedCN = DEFAULT_CN;
526 if (nameTemp != null) {
527 if (name.equals("")) {
528 if (nameTemp.isRequired()) {
529 // nothing, but required
531 error.mergeInto(new GigiApiException("No name entered, but one was required."));
533 // nothing and not required
536 } else if (u.isValidName(name)) {
539 if (nameTemp.isRequired()) {
540 error.mergeInto(new GigiApiException("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, because a name is required for this certificate type."));
541 } else if (name.equals(DEFAULT_CN)) {
542 verifiedCN = DEFAULT_CN;
545 error.mergeInto(new GigiApiException("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 or keep the default name."));
549 if ( !name.equals("")) {
551 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
561 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));