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 org.cacert.gigi.GigiApiException;
18 import org.cacert.gigi.crypto.SPKAC;
19 import org.cacert.gigi.dbObjects.Certificate;
20 import org.cacert.gigi.dbObjects.Certificate.CSRType;
21 import org.cacert.gigi.dbObjects.Certificate.SANType;
22 import org.cacert.gigi.dbObjects.Certificate.SubjectAlternateName;
23 import org.cacert.gigi.dbObjects.CertificateOwner;
24 import org.cacert.gigi.dbObjects.CertificateProfile;
25 import org.cacert.gigi.dbObjects.CertificateProfile.PropertyTemplate;
26 import org.cacert.gigi.dbObjects.Digest;
27 import org.cacert.gigi.dbObjects.Group;
28 import org.cacert.gigi.dbObjects.Organisation;
29 import org.cacert.gigi.dbObjects.User;
30 import org.cacert.gigi.output.template.SprintfCommand;
31 import org.cacert.gigi.util.AuthorizationContext;
32 import org.cacert.gigi.util.CAA;
33 import org.cacert.gigi.util.DomainAssessment;
34 import org.cacert.gigi.util.PEM;
35 import org.cacert.gigi.util.RateLimit;
37 import sun.security.pkcs.PKCS9Attribute;
38 import sun.security.pkcs10.PKCS10;
39 import sun.security.pkcs10.PKCS10Attribute;
40 import sun.security.pkcs10.PKCS10Attributes;
41 import sun.security.util.DerInputStream;
42 import sun.security.util.DerValue;
43 import sun.security.util.ObjectIdentifier;
44 import sun.security.x509.AVA;
45 import sun.security.x509.AlgorithmId;
46 import sun.security.x509.CertificateExtensions;
47 import sun.security.x509.DNSName;
48 import sun.security.x509.ExtendedKeyUsageExtension;
49 import sun.security.x509.Extension;
50 import sun.security.x509.GeneralName;
51 import sun.security.x509.GeneralNameInterface;
52 import sun.security.x509.GeneralNames;
53 import sun.security.x509.PKIXExtensions;
54 import sun.security.x509.RDN;
55 import sun.security.x509.RFC822Name;
56 import sun.security.x509.SubjectAlternativeNameExtension;
57 import sun.security.x509.X500Name;
59 public class CertificateRequest {
61 public static final String DEFAULT_CN = "CAcert WoT User";
63 public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
64 1, 3, 6, 1, 5, 5, 7, 3, 1
67 public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
68 1, 3, 6, 1, 5, 5, 7, 3, 2
71 public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
72 1, 3, 6, 1, 5, 5, 7, 3, 3
75 public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
76 1, 3, 6, 1, 5, 5, 7, 3, 4
79 public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
80 1, 3, 6, 1, 5, 5, 7, 3, 8
83 public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
84 1, 3, 6, 1, 5, 5, 7, 3, 9
87 private CSRType csrType;
89 private final PublicKey pk;
93 public String name = DEFAULT_CN;
95 private Set<SubjectAlternateName> SANs;
97 private Digest selectedDigest = Digest.getDefault();
99 private CertificateProfile profile = CertificateProfile.getById(1);
101 private String ou = "";
103 private AuthorizationContext ctx;
105 private String pDNS, pMail;
107 public CertificateRequest(AuthorizationContext c, String csr) throws IOException, GeneralSecurityException, GigiApiException {
108 this(c, csr, (CertificateProfile) null);
111 public CertificateRequest(AuthorizationContext ctx, String csr, CertificateProfile cp) throws GeneralSecurityException, IOException, IOException {
115 } else if (ctx.getActor().getAssurancePoints() > 50) {
116 profile = CertificateProfile.getByName("client-a");
118 byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
119 PKCS10 parsed = new PKCS10(data);
120 PKCS10Attributes atts = parsed.getAttributes();
122 TreeSet<SubjectAlternateName> SANs = new TreeSet<>();
123 for (RDN r : parsed.getSubjectName().rdns()) {
124 for (AVA a : r.avas()) {
125 if (a.getObjectIdentifier().equals((Object) PKCS9Attribute.EMAIL_ADDRESS_OID)) {
126 SANs.add(new SubjectAlternateName(SANType.EMAIL, a.getValueString()));
127 } else if (a.getObjectIdentifier().equals((Object) X500Name.commonName_oid)) {
128 String value = a.getValueString();
129 if (value.contains(".") && !value.contains(" ")) {
130 SANs.add(new SubjectAlternateName(SANType.DNS, value));
134 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
135 // TODO? parse invalid SANs
140 for (PKCS10Attribute b : atts.getAttributes()) {
142 if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
147 for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
148 if (c instanceof SubjectAlternativeNameExtension) {
150 SubjectAlternativeNameExtension san = (SubjectAlternativeNameExtension) c;
151 GeneralNames obj = san.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
152 for (int i = 0; i < obj.size(); i++) {
153 GeneralName generalName = obj.get(i);
154 GeneralNameInterface peeled = generalName.getName();
155 if (peeled instanceof DNSName) {
156 SANs.add(new SubjectAlternateName(SANType.DNS, ((DNSName) peeled).getName()));
157 } else if (peeled instanceof RFC822Name) {
158 SANs.add(new SubjectAlternateName(SANType.EMAIL, ((RFC822Name) peeled).getName()));
161 } else if (c instanceof ExtendedKeyUsageExtension) {
162 ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
163 String appendix = "";
164 if (ctx.getActor().getAssurancePoints() >= 50) {
167 for (String s : ekue.getExtendedKeyUsage()) {
168 if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
170 profile = CertificateProfile.getByName("server" + appendix);
171 } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
173 profile = CertificateProfile.getByName("client" + appendix);
174 } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
176 } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
178 profile = CertificateProfile.getByName("mail" + appendix);
179 } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
181 } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
186 // Unknown requested extension
192 pk = parsed.getSubjectPublicKeyInfo();
193 String sign = getSignatureAlgorithm(data);
197 this.csrType = CSRType.CSR;
200 public CertificateRequest(AuthorizationContext ctx, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
202 String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
203 byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
204 SPKAC parsed = new SPKAC(data);
205 if ( !parsed.getChallenge().equals(spkacChallenge)) {
206 throw new GigiApiException("Challenge mismatch");
208 pk = parsed.getPubkey();
209 String sign = getSignatureAlgorithm(data);
211 this.SANs = new HashSet<>();
212 this.csr = "SPKAC=" + cleanedSPKAC;
213 this.csrType = CSRType.SPKAC;
217 private static String getSignatureAlgorithm(byte[] data) throws IOException {
218 DerInputStream in = new DerInputStream(data);
219 DerValue[] seq = in.getSequence(3);
220 return AlgorithmId.parse(seq[1]).getName();
223 private void guessDigest(String sign) {
224 if (sign.toLowerCase().startsWith("sha512")) {
225 selectedDigest = Digest.SHA512;
226 } else if (sign.toLowerCase().startsWith("sha384")) {
227 selectedDigest = Digest.SHA384;
231 public void checkKeyStrength(PrintWriter out) {
232 out.println("Type: " + pk.getAlgorithm() + "<br/>");
233 if (pk instanceof RSAPublicKey) {
234 out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
235 out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
236 } else if (pk instanceof DSAPublicKey) {
237 DSAPublicKey dpk = (DSAPublicKey) pk;
238 out.println("Length: " + dpk.getY().bitLength() + "<br/>");
239 out.println(dpk.getParams());
240 } else if (pk instanceof ECPublicKey) {
241 ECPublicKey epk = (ECPublicKey) pk;
242 out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
243 out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
244 out.println(epk.getParams().getCurve());
248 private Set<SubjectAlternateName> parseSANBox(String SANs) {
249 String[] SANparts = SANs.split("[\r\n]+|, *");
250 Set<SubjectAlternateName> parsedNames = new LinkedHashSet<>();
251 for (String SANline : SANparts) {
252 String[] parts = SANline.split(":", 2);
253 if (parts.length == 1) {
254 if (parts[0].trim().equals("")) {
257 if (parts[0].contains("@")) {
258 parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
260 parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
265 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase().trim());
269 parsedNames.add(new SubjectAlternateName(t, parts[1].trim()));
270 } catch (IllegalArgumentException e) {
278 public Set<SubjectAlternateName> getSANs() {
282 public String getName() {
286 public synchronized String getOu() {
287 if (ctx.getTarget() instanceof Organisation) {
290 throw new IllegalStateException();
293 public Digest getSelectedDigest() {
294 return selectedDigest;
297 public CertificateProfile getProfile() {
301 public synchronized boolean update(String nameIn, String hashAlg, String profileStr, String newOrgStr, String ou, String SANsStr) throws GigiApiException {
302 GigiApiException error = new GigiApiException();
304 if (hashAlg != null) {
305 selectedDigest = Digest.valueOf(hashAlg);
307 this.profile = CertificateProfile.getByName(profileStr);
308 if (ctx.getTarget() instanceof Organisation) {
312 if ( !this.profile.canBeIssuedBy(ctx.getTarget(), ctx.getActor())) {
313 this.profile = CertificateProfile.getById(1);
314 error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
318 verifySANs(error, profile, parseSANBox(SANsStr), ctx.getTarget(), ctx.getActor());
320 if ( !error.isEmpty()) {
326 private void verifySANs(GigiApiException error, CertificateProfile p, Set<SubjectAlternateName> sANs2, CertificateOwner owner, User user) {
327 Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
328 PropertyTemplate domainTemp = p.getTemplates().get("domain");
329 PropertyTemplate emailTemp = p.getTemplates().get("email");
332 for (SubjectAlternateName san : sANs2) {
333 if (san.getType() == SANType.DNS) {
334 if (domainTemp != null && owner.isValidDomain(san.getName())) {
337 DomainAssessment.checkCertifiableDomain(san.getName(), user.isInGroup(Group.CODESIGNING), false);
339 } catch (GigiApiException e) {
342 if ( !valid || !CAA.verifyDomainAccess(owner, p, san.getName()) || (pDNS != null && !domainTemp.isMultiple())) {
346 pDNS = san.getName();
348 filteredSANs.add(san);
352 } else if (san.getType() == SANType.EMAIL) {
353 if (emailTemp != null && owner.isValidEmail(san.getName())) {
354 if (pMail != null && !emailTemp.isMultiple()) {
358 pMail = san.getName();
360 filteredSANs.add(san);
365 error.mergeInto(new GigiApiException(SprintfCommand.createSimple(//
366 "The requested subject alternate name (SAN) \"{0}\" has been removed.", san.getType().toString().toLowerCase() + ":" + san.getName())));
371 // domain email name name=WoTUser orga
372 public synchronized Certificate draft() throws GigiApiException {
374 GigiApiException error = new GigiApiException();
376 HashMap<String, String> subject = new HashMap<>();
377 PropertyTemplate domainTemp = profile.getTemplates().get("domain");
378 PropertyTemplate emailTemp = profile.getTemplates().get("email");
379 PropertyTemplate nameTemp = profile.getTemplates().get("name");
380 PropertyTemplate wotUserTemp = profile.getTemplates().get("name=WoTUser");
381 verifySANs(error, profile, SANs, ctx.getTarget(), ctx.getActor());
383 // Ok, let's determine the CN
385 // 1. the user's "real name", iff the real name is to be included i.e.
386 // not empty (name), or to be forced to WOTUser
388 // 2. the user's "primary domain", iff "1." doesn't match and there is a
389 // primary domain. (domainTemp != null)
391 String verifiedCN = null;
392 if (ctx.getTarget() instanceof Organisation) {
393 if ( !name.equals("")) {
397 verifiedCN = verifyName(error, nameTemp, wotUserTemp, verifiedCN);
399 if (pDNS == null && domainTemp != null && domainTemp.isRequired()) {
400 error.mergeInto(new GigiApiException("Server Certificates require a DNS name."));
401 } else if (domainTemp != null && verifiedCN == null) {
402 // user may add domains
405 if (verifiedCN != null) {
406 subject.put("CN", verifiedCN);
410 if (emailTemp != null) {
411 subject.put("EMAIL", pMail);
413 // verify SANs should prevent this
415 error.mergeInto(new GigiApiException("You may not include an email in this certificate."));
418 if (emailTemp != null && emailTemp.isRequired()) {
419 error.mergeInto(new GigiApiException("You need to include an email in this certificate."));
423 if (ctx.getTarget() instanceof Organisation) {
424 Organisation org = (Organisation) ctx.getTarget();
425 subject.put("O", org.getName());
426 subject.put("C", org.getState().getCode());
427 subject.put("ST", org.getProvince());
428 subject.put("L", org.getCity());
430 subject.put("OU", ou);
433 System.out.println(subject);
434 if ( !error.isEmpty()) {
438 if (RATE_LIMIT.isLimitExceeded(Integer.toString(ctx.getActor().getId()))) {
439 throw new GigiApiException("Rate Limit Exceeded");
441 return new Certificate(ctx.getTarget(), ctx.getActor(), subject, selectedDigest, //
442 this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
443 } catch (IOException e) {
449 // 100 per 10 minutes
450 public static final RateLimit RATE_LIMIT = new RateLimit(100, 10 * 60 * 1000);
452 private String verifyName(GigiApiException error, PropertyTemplate nameTemp, PropertyTemplate wotUserTemp, String verifiedCN) {
454 // possible configurations: name {y,null,?}, name=WoTUser {y,null}
459 // ? y -> real, default
460 // ? null -> real, default, null
461 boolean realIsOK = false;
462 boolean nullIsOK = false;
463 boolean defaultIsOK = false;
464 if (wotUserTemp != null && ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple())) {
465 error.mergeInto(new GigiApiException("Internal configuration error detected."));
467 if (nameTemp != null && nameTemp.isRequired() && !nameTemp.isMultiple()) {
469 } else if (nameTemp == null) {
470 defaultIsOK = wotUserTemp != null;
471 nullIsOK = !defaultIsOK;
472 } else if (nameTemp != null && !nameTemp.isRequired() && !nameTemp.isMultiple()) {
475 nullIsOK = wotUserTemp == null;
477 error.mergeInto(new GigiApiException("Internal configuration error detected."));
479 if (ctx.getTarget() instanceof User) {
480 User u = (User) ctx.getTarget();
481 if (name != null && u.isValidName(name)) {
485 error.mergeInto(new GigiApiException("Your real name is not allowed in this certificate."));
488 } else if (nullIsOK) {
492 } else if (name != null && name.equals(DEFAULT_CN)) {
496 error.mergeInto(new GigiApiException("The default name is not allowed in this certificate."));
499 } else if (realIsOK) {
500 name = u.getPreferredName().toString();
503 } else if (name == null || name.equals("")) {
507 error.mergeInto(new GigiApiException("A name is required in this certificate."));
510 } else if (realIsOK) {
511 name = u.getPreferredName().toString();
515 error.mergeInto(new GigiApiException("The name you entered was invalid."));
518 if (wotUserTemp != null) {
519 if ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple()) {
520 error.mergeInto(new GigiApiException("Internal configuration error detected."));
522 if ( !name.equals(DEFAULT_CN)) {
524 error.mergeInto(new GigiApiException("You may not change the name for this certificate type."));
526 verifiedCN = DEFAULT_CN;
530 if (nameTemp != null) {
531 if (name.equals("")) {
532 if (nameTemp.isRequired()) {
533 // nothing, but required
535 error.mergeInto(new GigiApiException("No name entered, but one was required."));
537 // nothing and not required
540 } else if (u.isValidName(name)) {
543 if (nameTemp.isRequired()) {
544 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 verified in your account, because a name is required for this certificate type."));
545 } else if (name.equals(DEFAULT_CN)) {
546 verifiedCN = DEFAULT_CN;
549 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 verified in your account or keep the default name."));
553 if ( !name.equals("")) {
555 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
565 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));