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.Organisation;
30 import org.cacert.gigi.dbObjects.User;
31 import org.cacert.gigi.output.template.SprintfCommand;
32 import org.cacert.gigi.util.AuthorizationContext;
33 import org.cacert.gigi.util.PEM;
34 import org.cacert.gigi.util.RateLimit;
36 import sun.security.pkcs.PKCS9Attribute;
37 import sun.security.pkcs10.PKCS10;
38 import sun.security.pkcs10.PKCS10Attribute;
39 import sun.security.pkcs10.PKCS10Attributes;
40 import sun.security.util.DerInputStream;
41 import sun.security.util.DerValue;
42 import sun.security.util.ObjectIdentifier;
43 import sun.security.x509.AVA;
44 import sun.security.x509.AlgorithmId;
45 import sun.security.x509.CertificateExtensions;
46 import sun.security.x509.DNSName;
47 import sun.security.x509.ExtendedKeyUsageExtension;
48 import sun.security.x509.Extension;
49 import sun.security.x509.GeneralName;
50 import sun.security.x509.GeneralNameInterface;
51 import sun.security.x509.GeneralNames;
52 import sun.security.x509.PKIXExtensions;
53 import sun.security.x509.RDN;
54 import sun.security.x509.RFC822Name;
55 import sun.security.x509.SubjectAlternativeNameExtension;
56 import sun.security.x509.X500Name;
58 public class CertificateRequest {
60 public static final String DEFAULT_CN = "CAcert WoT User";
62 public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
63 1, 3, 6, 1, 5, 5, 7, 3, 1
66 public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
67 1, 3, 6, 1, 5, 5, 7, 3, 2
70 public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
71 1, 3, 6, 1, 5, 5, 7, 3, 3
74 public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
75 1, 3, 6, 1, 5, 5, 7, 3, 4
78 public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
79 1, 3, 6, 1, 5, 5, 7, 3, 8
82 public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
83 1, 3, 6, 1, 5, 5, 7, 3, 9
86 private CSRType csrType;
88 private final PublicKey pk;
92 public String name = DEFAULT_CN;
94 private Set<SubjectAlternateName> SANs;
96 private Digest selectedDigest = Digest.getDefault();
98 private CertificateProfile profile = CertificateProfile.getById(1);
100 private String ou = "";
102 private AuthorizationContext ctx;
104 private String pDNS, pMail;
106 public CertificateRequest(AuthorizationContext c, String csr) throws IOException, GeneralSecurityException, GigiApiException {
107 this(c, csr, (CertificateProfile) null);
110 public CertificateRequest(AuthorizationContext ctx, String csr, CertificateProfile cp) throws GeneralSecurityException, IOException, IOException {
114 } else if (ctx.getActor().getAssurancePoints() > 50) {
115 profile = CertificateProfile.getByName("client-a");
117 byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
118 PKCS10 parsed = new PKCS10(data);
119 PKCS10Attributes atts = parsed.getAttributes();
121 TreeSet<SubjectAlternateName> SANs = new TreeSet<>();
122 for (RDN r : parsed.getSubjectName().rdns()) {
123 for (AVA a : r.avas()) {
124 if (a.getObjectIdentifier().equals((Object) PKCS9Attribute.EMAIL_ADDRESS_OID)) {
125 SANs.add(new SubjectAlternateName(SANType.EMAIL, a.getValueString()));
126 } else if (a.getObjectIdentifier().equals((Object) X500Name.commonName_oid)) {
127 String value = a.getValueString();
128 if (value.contains(".") && !value.contains(" ")) {
129 SANs.add(new SubjectAlternateName(SANType.DNS, value));
133 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
134 // TODO? parse invalid SANs
139 for (PKCS10Attribute b : atts.getAttributes()) {
141 if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
146 for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
147 if (c instanceof SubjectAlternativeNameExtension) {
149 SubjectAlternativeNameExtension san = (SubjectAlternativeNameExtension) c;
150 GeneralNames obj = san.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
151 for (int i = 0; i < obj.size(); i++) {
152 GeneralName generalName = obj.get(i);
153 GeneralNameInterface peeled = generalName.getName();
154 if (peeled instanceof DNSName) {
155 SANs.add(new SubjectAlternateName(SANType.DNS, ((DNSName) peeled).getName()));
156 } else if (peeled instanceof RFC822Name) {
157 SANs.add(new SubjectAlternateName(SANType.EMAIL, ((RFC822Name) peeled).getName()));
160 } else if (c instanceof ExtendedKeyUsageExtension) {
161 ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
162 String appendix = "";
163 if (ctx.getActor().getAssurancePoints() >= 50) {
166 for (String s : ekue.getExtendedKeyUsage()) {
167 if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
169 profile = CertificateProfile.getByName("server" + appendix);
170 } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
172 profile = CertificateProfile.getByName("client" + appendix);
173 } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
175 } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
177 profile = CertificateProfile.getByName("mail" + appendix);
178 } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
180 } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
185 // Unknown requested extension
191 pk = parsed.getSubjectPublicKeyInfo();
192 String sign = getSignatureAlgorithm(data);
196 this.csrType = CSRType.CSR;
199 public CertificateRequest(AuthorizationContext ctx, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
201 String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
202 byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
203 SPKAC parsed = new SPKAC(data);
204 if ( !parsed.getChallenge().equals(spkacChallenge)) {
205 throw new GigiApiException("Challenge mismatch");
207 pk = parsed.getPubkey();
208 String sign = getSignatureAlgorithm(data);
210 this.SANs = new HashSet<>();
211 this.csr = "SPKAC=" + cleanedSPKAC;
212 this.csrType = CSRType.SPKAC;
216 private static String getSignatureAlgorithm(byte[] data) throws IOException {
217 DerInputStream in = new DerInputStream(data);
218 DerValue[] seq = in.getSequence(3);
219 return AlgorithmId.parse(seq[1]).getName();
222 private void guessDigest(String sign) {
223 if (sign.toLowerCase().startsWith("sha512")) {
224 selectedDigest = Digest.SHA512;
225 } else if (sign.toLowerCase().startsWith("sha384")) {
226 selectedDigest = Digest.SHA384;
230 public void checkKeyStrength(PrintWriter out) {
231 out.println("Type: " + pk.getAlgorithm() + "<br/>");
232 if (pk instanceof RSAPublicKey) {
233 out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
234 out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
235 } else if (pk instanceof DSAPublicKey) {
236 DSAPublicKey dpk = (DSAPublicKey) pk;
237 out.println("Length: " + dpk.getY().bitLength() + "<br/>");
238 out.println(dpk.getParams());
239 } else if (pk instanceof ECPublicKey) {
240 ECPublicKey epk = (ECPublicKey) pk;
241 out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
242 out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
243 out.println(epk.getParams().getCurve());
247 private Set<SubjectAlternateName> parseSANBox(String SANs) {
248 String[] SANparts = SANs.split("[\r\n]+|, *");
249 Set<SubjectAlternateName> parsedNames = new LinkedHashSet<>();
250 for (String SANline : SANparts) {
251 String[] parts = SANline.split(":", 2);
252 if (parts.length == 1) {
253 if (parts[0].trim().equals("")) {
256 if (parts[0].contains("@")) {
257 parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
259 parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
264 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase().trim());
268 parsedNames.add(new SubjectAlternateName(t, parts[1].trim()));
269 } catch (IllegalArgumentException e) {
277 public Set<SubjectAlternateName> getSANs() {
281 public String getName() {
285 public synchronized String getOu() {
286 if (ctx.getTarget() instanceof Organisation) {
289 throw new IllegalStateException();
292 public Digest getSelectedDigest() {
293 return selectedDigest;
296 public CertificateProfile getProfile() {
300 public synchronized boolean update(String nameIn, String hashAlg, String profileStr, String newOrgStr, String ou, String SANsStr, PrintWriter out, HttpServletRequest req) throws GigiApiException {
301 GigiApiException error = new GigiApiException();
303 if (hashAlg != null) {
304 selectedDigest = Digest.valueOf(hashAlg);
306 this.profile = CertificateProfile.getByName(profileStr);
307 if (ctx.getTarget() instanceof Organisation) {
311 if ( !this.profile.canBeIssuedBy(ctx.getTarget(), ctx.getActor())) {
312 this.profile = CertificateProfile.getById(1);
313 error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
317 verifySANs(error, profile, parseSANBox(SANsStr), ctx.getTarget());
319 if ( !error.isEmpty()) {
325 private void verifySANs(GigiApiException error, CertificateProfile p, Set<SubjectAlternateName> sANs2, CertificateOwner owner) {
326 Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
327 PropertyTemplate domainTemp = p.getTemplates().get("domain");
328 PropertyTemplate emailTemp = p.getTemplates().get("email");
331 for (SubjectAlternateName san : sANs2) {
332 if (san.getType() == SANType.DNS) {
333 if (domainTemp != null && owner.isValidDomain(san.getName())) {
334 if (pDNS != null && !domainTemp.isMultiple()) {
338 pDNS = san.getName();
340 filteredSANs.add(san);
344 } else if (san.getType() == SANType.EMAIL) {
345 if (emailTemp != null && owner.isValidEmail(san.getName())) {
346 if (pMail != null && !emailTemp.isMultiple()) {
350 pMail = san.getName();
352 filteredSANs.add(san);
357 error.mergeInto(new GigiApiException(SprintfCommand.createSimple(//
358 "The requested Subject alternate name \"{0}\" has been removed.", san.getType().toString().toLowerCase() + ":" + san.getName())));
363 // domain email name name=WoTUser orga
364 public synchronized Certificate draft() throws GigiApiException {
366 GigiApiException error = new GigiApiException();
368 HashMap<String, String> subject = new HashMap<>();
369 PropertyTemplate domainTemp = profile.getTemplates().get("domain");
370 PropertyTemplate emailTemp = profile.getTemplates().get("email");
371 PropertyTemplate nameTemp = profile.getTemplates().get("name");
372 PropertyTemplate wotUserTemp = profile.getTemplates().get("name=WoTUser");
373 verifySANs(error, profile, SANs, ctx.getTarget());
375 // Ok, let's determine the CN
377 // 1. the user's "real name", iff the real name is to be included i.e.
378 // not empty (name), or to be forced to WOTUser
380 // 2. the user's "primary domain", iff "1." doesn't match and there is a
381 // primary domain. (domainTemp != null)
383 String verifiedCN = null;
384 if (ctx.getTarget() instanceof Organisation) {
385 if ( !name.equals("")) {
389 verifiedCN = verifyName(error, nameTemp, wotUserTemp, verifiedCN);
391 if (pDNS == null && domainTemp != null && domainTemp.isRequired()) {
392 error.mergeInto(new GigiApiException("Server Certificates require a DNS name."));
393 } else if (domainTemp != null && verifiedCN == null) {
394 // user may add domains
397 if (verifiedCN != null) {
398 subject.put("CN", verifiedCN);
402 if (emailTemp != null) {
403 subject.put("EMAIL", pMail);
405 // verify SANs should prevent this
407 error.mergeInto(new GigiApiException("You may not include an email in this certificate."));
410 if (emailTemp != null && emailTemp.isRequired()) {
411 error.mergeInto(new GigiApiException("You need to include an email in this certificate."));
415 if (ctx.getTarget() instanceof Organisation) {
416 Organisation org = (Organisation) ctx.getTarget();
417 subject.put("O", org.getName());
418 subject.put("C", org.getState());
419 subject.put("ST", org.getProvince());
420 subject.put("L", org.getCity());
422 subject.put("OU", ou);
425 System.out.println(subject);
426 if ( !error.isEmpty()) {
430 if (RATE_LIMIT.isLimitExceeded(Integer.toString(ctx.getActor().getId()))) {
431 throw new GigiApiException("Rate Limit Exceeded");
433 return new Certificate(ctx.getTarget(), ctx.getActor(), subject, selectedDigest, //
434 this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
435 } catch (IOException e) {
441 // 100 per 10 minutes
442 public static final RateLimit RATE_LIMIT = new RateLimit(100, 10 * 60 * 1000);
444 private String verifyName(GigiApiException error, PropertyTemplate nameTemp, PropertyTemplate wotUserTemp, String verifiedCN) {
446 // possible configurations: name {y,null,?}, name=WoTUser {y,null}
451 // ? y -> real, default
452 // ? null -> real, default, null
453 boolean realIsOK = false;
454 boolean nullIsOK = false;
455 boolean defaultIsOK = false;
456 if (wotUserTemp != null && ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple())) {
457 error.mergeInto(new GigiApiException("Internal configuration error detected."));
459 if (nameTemp != null && nameTemp.isRequired() && !nameTemp.isMultiple()) {
461 } else if (nameTemp == null) {
462 defaultIsOK = wotUserTemp != null;
463 nullIsOK = !defaultIsOK;
464 } else if (nameTemp != null && !nameTemp.isRequired() && !nameTemp.isMultiple()) {
467 nullIsOK = wotUserTemp == null;
469 error.mergeInto(new GigiApiException("Internal configuration error detected."));
471 if (ctx.getTarget() instanceof User) {
472 User u = (User) ctx.getTarget();
473 if (name != null && u.isValidName(name)) {
477 error.mergeInto(new GigiApiException("Your real name is not allowed in this certificate."));
480 } else if (nullIsOK) {
484 } else if (name != null && name.equals(DEFAULT_CN)) {
488 error.mergeInto(new GigiApiException("The default name is not allowed in this certificate."));
491 } else if (realIsOK) {
492 name = u.getName().toString();
495 } else if (name == null || name.equals("")) {
499 error.mergeInto(new GigiApiException("A name is required in this certificate."));
502 } else if (realIsOK) {
503 name = u.getName().toString();
507 error.mergeInto(new GigiApiException("The name you entered was invalid."));
510 if (wotUserTemp != null) {
511 if ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple()) {
512 error.mergeInto(new GigiApiException("Internal configuration error detected."));
514 if ( !name.equals(DEFAULT_CN)) {
516 error.mergeInto(new GigiApiException("You may not change the name for this certificate type."));
518 verifiedCN = DEFAULT_CN;
522 if (nameTemp != null) {
523 if (name.equals("")) {
524 if (nameTemp.isRequired()) {
525 // nothing, but required
527 error.mergeInto(new GigiApiException("No name entered, but one was required."));
529 // nothing and not required
532 } else if (u.isValidName(name)) {
535 if (nameTemp.isRequired()) {
536 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."));
537 } else if (name.equals(DEFAULT_CN)) {
538 verifiedCN = DEFAULT_CN;
541 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."));
545 if ( !name.equals("")) {
547 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
557 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));