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.HashSet;
13 import java.util.LinkedHashSet;
15 import java.util.TreeSet;
17 import javax.servlet.http.HttpServletRequest;
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.CertificateOwner;
26 import org.cacert.gigi.dbObjects.CertificateProfile;
27 import org.cacert.gigi.dbObjects.CertificateProfile.PropertyTemplate;
28 import org.cacert.gigi.dbObjects.Digest;
29 import org.cacert.gigi.dbObjects.Group;
30 import org.cacert.gigi.dbObjects.Organisation;
31 import org.cacert.gigi.dbObjects.User;
32 import org.cacert.gigi.output.template.SprintfCommand;
33 import org.cacert.gigi.util.AuthorizationContext;
34 import org.cacert.gigi.util.CAA;
35 import org.cacert.gigi.util.DomainAssessment;
36 import org.cacert.gigi.util.PEM;
37 import org.cacert.gigi.util.RateLimit;
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;
61 public class CertificateRequest {
63 public static final String DEFAULT_CN = "CAcert WoT User";
65 public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
66 1, 3, 6, 1, 5, 5, 7, 3, 1
69 public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
70 1, 3, 6, 1, 5, 5, 7, 3, 2
73 public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
74 1, 3, 6, 1, 5, 5, 7, 3, 3
77 public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
78 1, 3, 6, 1, 5, 5, 7, 3, 4
81 public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
82 1, 3, 6, 1, 5, 5, 7, 3, 8
85 public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
86 1, 3, 6, 1, 5, 5, 7, 3, 9
89 private CSRType csrType;
91 private final PublicKey pk;
95 public String name = DEFAULT_CN;
97 private Set<SubjectAlternateName> SANs;
99 private Digest selectedDigest = Digest.getDefault();
101 private CertificateProfile profile = CertificateProfile.getById(1);
103 private String ou = "";
105 private AuthorizationContext ctx;
107 private String pDNS, pMail;
109 public CertificateRequest(AuthorizationContext c, String csr) throws IOException, GeneralSecurityException, GigiApiException {
110 this(c, csr, (CertificateProfile) null);
113 public CertificateRequest(AuthorizationContext ctx, String csr, CertificateProfile cp) throws GeneralSecurityException, IOException, IOException {
117 } else if (ctx.getActor().getAssurancePoints() > 50) {
118 profile = CertificateProfile.getByName("client-a");
120 byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
121 PKCS10 parsed = new PKCS10(data);
122 PKCS10Attributes atts = parsed.getAttributes();
124 TreeSet<SubjectAlternateName> SANs = new TreeSet<>();
125 for (RDN r : parsed.getSubjectName().rdns()) {
126 for (AVA a : r.avas()) {
127 if (a.getObjectIdentifier().equals((Object) PKCS9Attribute.EMAIL_ADDRESS_OID)) {
128 SANs.add(new SubjectAlternateName(SANType.EMAIL, a.getValueString()));
129 } else if (a.getObjectIdentifier().equals((Object) X500Name.commonName_oid)) {
130 String value = a.getValueString();
131 if (value.contains(".") && !value.contains(" ")) {
132 SANs.add(new SubjectAlternateName(SANType.DNS, value));
136 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
137 // TODO? parse invalid SANs
142 for (PKCS10Attribute b : atts.getAttributes()) {
144 if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
149 for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
150 if (c instanceof SubjectAlternativeNameExtension) {
152 SubjectAlternativeNameExtension san = (SubjectAlternativeNameExtension) c;
153 GeneralNames obj = san.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
154 for (int i = 0; i < obj.size(); i++) {
155 GeneralName generalName = obj.get(i);
156 GeneralNameInterface peeled = generalName.getName();
157 if (peeled instanceof DNSName) {
158 SANs.add(new SubjectAlternateName(SANType.DNS, ((DNSName) peeled).getName()));
159 } else if (peeled instanceof RFC822Name) {
160 SANs.add(new SubjectAlternateName(SANType.EMAIL, ((RFC822Name) peeled).getName()));
163 } else if (c instanceof ExtendedKeyUsageExtension) {
164 ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
165 String appendix = "";
166 if (ctx.getActor().getAssurancePoints() >= 50) {
169 for (String s : ekue.getExtendedKeyUsage()) {
170 if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
172 profile = CertificateProfile.getByName("server" + appendix);
173 } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
175 profile = CertificateProfile.getByName("client" + appendix);
176 } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
178 } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
180 profile = CertificateProfile.getByName("mail" + appendix);
181 } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
183 } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
188 // Unknown requested extension
194 pk = parsed.getSubjectPublicKeyInfo();
195 String sign = getSignatureAlgorithm(data);
199 this.csrType = CSRType.CSR;
202 public CertificateRequest(AuthorizationContext ctx, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
204 String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
205 byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
206 SPKAC parsed = new SPKAC(data);
207 if ( !parsed.getChallenge().equals(spkacChallenge)) {
208 throw new GigiApiException("Challenge mismatch");
210 pk = parsed.getPubkey();
211 String sign = getSignatureAlgorithm(data);
213 this.SANs = new HashSet<>();
214 this.csr = "SPKAC=" + cleanedSPKAC;
215 this.csrType = CSRType.SPKAC;
219 private static String getSignatureAlgorithm(byte[] data) throws IOException {
220 DerInputStream in = new DerInputStream(data);
221 DerValue[] seq = in.getSequence(3);
222 return AlgorithmId.parse(seq[1]).getName();
225 private void guessDigest(String sign) {
226 if (sign.toLowerCase().startsWith("sha512")) {
227 selectedDigest = Digest.SHA512;
228 } else if (sign.toLowerCase().startsWith("sha384")) {
229 selectedDigest = Digest.SHA384;
233 public void checkKeyStrength(PrintWriter out) {
234 out.println("Type: " + pk.getAlgorithm() + "<br/>");
235 if (pk instanceof RSAPublicKey) {
236 out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
237 out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
238 } else if (pk instanceof DSAPublicKey) {
239 DSAPublicKey dpk = (DSAPublicKey) pk;
240 out.println("Length: " + dpk.getY().bitLength() + "<br/>");
241 out.println(dpk.getParams());
242 } else if (pk instanceof ECPublicKey) {
243 ECPublicKey epk = (ECPublicKey) pk;
244 out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
245 out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
246 out.println(epk.getParams().getCurve());
250 private Set<SubjectAlternateName> parseSANBox(String SANs) {
251 String[] SANparts = SANs.split("[\r\n]+|, *");
252 Set<SubjectAlternateName> parsedNames = new LinkedHashSet<>();
253 for (String SANline : SANparts) {
254 String[] parts = SANline.split(":", 2);
255 if (parts.length == 1) {
256 if (parts[0].trim().equals("")) {
259 if (parts[0].contains("@")) {
260 parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
262 parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
267 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase().trim());
271 parsedNames.add(new SubjectAlternateName(t, parts[1].trim()));
272 } catch (IllegalArgumentException e) {
280 public Set<SubjectAlternateName> getSANs() {
284 public String getName() {
288 public synchronized String getOu() {
289 if (ctx.getTarget() instanceof Organisation) {
292 throw new IllegalStateException();
295 public Digest getSelectedDigest() {
296 return selectedDigest;
299 public CertificateProfile getProfile() {
303 public synchronized boolean update(String nameIn, String hashAlg, String profileStr, String newOrgStr, String ou, String SANsStr, PrintWriter out, HttpServletRequest req) throws GigiApiException {
304 GigiApiException error = new GigiApiException();
306 if (hashAlg != null) {
307 selectedDigest = Digest.valueOf(hashAlg);
309 this.profile = CertificateProfile.getByName(profileStr);
310 if (ctx.getTarget() instanceof Organisation) {
314 if ( !this.profile.canBeIssuedBy(ctx.getTarget(), ctx.getActor())) {
315 this.profile = CertificateProfile.getById(1);
316 error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
320 verifySANs(error, profile, parseSANBox(SANsStr), ctx.getTarget(), ctx.getActor());
322 if ( !error.isEmpty()) {
328 private void verifySANs(GigiApiException error, CertificateProfile p, Set<SubjectAlternateName> sANs2, CertificateOwner owner, User user) {
329 Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
330 PropertyTemplate domainTemp = p.getTemplates().get("domain");
331 PropertyTemplate emailTemp = p.getTemplates().get("email");
334 for (SubjectAlternateName san : sANs2) {
335 if (san.getType() == SANType.DNS) {
336 if (domainTemp != null && owner.isValidDomain(san.getName())) {
339 DomainAssessment.checkCertifiableDomain(san.getName(), user.isInGroup(Group.CODESIGNING), false);
341 } catch (GigiApiException e) {
344 if ( !valid || !CAA.verifyDomainAccess(owner, p, san.getName()) || (pDNS != null && !domainTemp.isMultiple())) {
348 pDNS = san.getName();
350 filteredSANs.add(san);
354 } else if (san.getType() == SANType.EMAIL) {
355 if (emailTemp != null && owner.isValidEmail(san.getName())) {
356 if (pMail != null && !emailTemp.isMultiple()) {
360 pMail = san.getName();
362 filteredSANs.add(san);
367 error.mergeInto(new GigiApiException(SprintfCommand.createSimple(//
368 "The requested Subject alternate name \"{0}\" has been removed.", san.getType().toString().toLowerCase() + ":" + san.getName())));
373 // domain email name name=WoTUser orga
374 public synchronized Certificate draft() throws GigiApiException {
376 GigiApiException error = new GigiApiException();
378 HashMap<String, String> subject = new HashMap<>();
379 PropertyTemplate domainTemp = profile.getTemplates().get("domain");
380 PropertyTemplate emailTemp = profile.getTemplates().get("email");
381 PropertyTemplate nameTemp = profile.getTemplates().get("name");
382 PropertyTemplate wotUserTemp = profile.getTemplates().get("name=WoTUser");
383 verifySANs(error, profile, SANs, ctx.getTarget(), ctx.getActor());
385 // Ok, let's determine the CN
387 // 1. the user's "real name", iff the real name is to be included i.e.
388 // not empty (name), or to be forced to WOTUser
390 // 2. the user's "primary domain", iff "1." doesn't match and there is a
391 // primary domain. (domainTemp != null)
393 String verifiedCN = null;
394 if (ctx.getTarget() instanceof Organisation) {
395 if ( !name.equals("")) {
399 verifiedCN = verifyName(error, nameTemp, wotUserTemp, verifiedCN);
401 if (pDNS == null && domainTemp != null && domainTemp.isRequired()) {
402 error.mergeInto(new GigiApiException("Server Certificates require a DNS name."));
403 } else if (domainTemp != null && verifiedCN == null) {
404 // user may add domains
407 if (verifiedCN != null) {
408 subject.put("CN", verifiedCN);
412 if (emailTemp != null) {
413 subject.put("EMAIL", pMail);
415 // verify SANs should prevent this
417 error.mergeInto(new GigiApiException("You may not include an email in this certificate."));
420 if (emailTemp != null && emailTemp.isRequired()) {
421 error.mergeInto(new GigiApiException("You need to include an email in this certificate."));
425 if (ctx.getTarget() instanceof Organisation) {
426 Organisation org = (Organisation) ctx.getTarget();
427 subject.put("O", org.getName());
428 subject.put("C", org.getState());
429 subject.put("ST", org.getProvince());
430 subject.put("L", org.getCity());
432 subject.put("OU", ou);
435 System.out.println(subject);
436 if ( !error.isEmpty()) {
440 if (RATE_LIMIT.isLimitExceeded(Integer.toString(ctx.getActor().getId()))) {
441 throw new GigiApiException("Rate Limit Exceeded");
443 return new Certificate(ctx.getTarget(), ctx.getActor(), subject, selectedDigest, //
444 this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
445 } catch (IOException e) {
451 // 100 per 10 minutes
452 public static final RateLimit RATE_LIMIT = new RateLimit(100, 10 * 60 * 1000);
454 private String verifyName(GigiApiException error, PropertyTemplate nameTemp, PropertyTemplate wotUserTemp, String verifiedCN) {
456 // possible configurations: name {y,null,?}, name=WoTUser {y,null}
461 // ? y -> real, default
462 // ? null -> real, default, null
463 boolean realIsOK = false;
464 boolean nullIsOK = false;
465 boolean defaultIsOK = false;
466 if (wotUserTemp != null && ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple())) {
467 error.mergeInto(new GigiApiException("Internal configuration error detected."));
469 if (nameTemp != null && nameTemp.isRequired() && !nameTemp.isMultiple()) {
471 } else if (nameTemp == null) {
472 defaultIsOK = wotUserTemp != null;
473 nullIsOK = !defaultIsOK;
474 } else if (nameTemp != null && !nameTemp.isRequired() && !nameTemp.isMultiple()) {
477 nullIsOK = wotUserTemp == null;
479 error.mergeInto(new GigiApiException("Internal configuration error detected."));
481 if (ctx.getTarget() instanceof User) {
482 User u = (User) ctx.getTarget();
483 if (name != null && u.isValidName(name)) {
487 error.mergeInto(new GigiApiException("Your real name is not allowed in this certificate."));
490 } else if (nullIsOK) {
494 } else if (name != null && name.equals(DEFAULT_CN)) {
498 error.mergeInto(new GigiApiException("The default name is not allowed in this certificate."));
501 } else if (realIsOK) {
502 name = u.getName().toString();
505 } else if (name == null || name.equals("")) {
509 error.mergeInto(new GigiApiException("A name is required in this certificate."));
512 } else if (realIsOK) {
513 name = u.getName().toString();
517 error.mergeInto(new GigiApiException("The name you entered was invalid."));
520 if (wotUserTemp != null) {
521 if ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple()) {
522 error.mergeInto(new GigiApiException("Internal configuration error detected."));
524 if ( !name.equals(DEFAULT_CN)) {
526 error.mergeInto(new GigiApiException("You may not change the name for this certificate type."));
528 verifiedCN = DEFAULT_CN;
532 if (nameTemp != null) {
533 if (name.equals("")) {
534 if (nameTemp.isRequired()) {
535 // nothing, but required
537 error.mergeInto(new GigiApiException("No name entered, but one was required."));
539 // nothing and not required
542 } else if (u.isValidName(name)) {
545 if (nameTemp.isRequired()) {
546 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."));
547 } else if (name.equals(DEFAULT_CN)) {
548 verifiedCN = DEFAULT_CN;
551 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."));
555 if ( !name.equals("")) {
557 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
567 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));