]> WPIA git - gigi.git/blob - src/org/cacert/gigi/pages/account/certs/CertificateRequest.java
add: check CAA entries
[gigi.git] / src / org / cacert / gigi / pages / account / certs / CertificateRequest.java
1 package org.cacert.gigi.pages.account.certs;
2
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;
14 import java.util.Set;
15 import java.util.TreeSet;
16
17 import javax.servlet.http.HttpServletRequest;
18
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;
38
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;
60
61 public class CertificateRequest {
62
63     public static final String DEFAULT_CN = "CAcert WoT User";
64
65     public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
66             1, 3, 6, 1, 5, 5, 7, 3, 1
67     });
68
69     public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
70             1, 3, 6, 1, 5, 5, 7, 3, 2
71     });
72
73     public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
74             1, 3, 6, 1, 5, 5, 7, 3, 3
75     });
76
77     public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
78             1, 3, 6, 1, 5, 5, 7, 3, 4
79     });
80
81     public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
82             1, 3, 6, 1, 5, 5, 7, 3, 8
83     });
84
85     public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
86             1, 3, 6, 1, 5, 5, 7, 3, 9
87     });
88
89     private CSRType csrType;
90
91     private final PublicKey pk;
92
93     private String csr;
94
95     public String name = DEFAULT_CN;
96
97     private Set<SubjectAlternateName> SANs;
98
99     private Digest selectedDigest = Digest.getDefault();
100
101     private CertificateProfile profile = CertificateProfile.getById(1);
102
103     private String ou = "";
104
105     private AuthorizationContext ctx;
106
107     private String pDNS, pMail;
108
109     public CertificateRequest(AuthorizationContext c, String csr) throws IOException, GeneralSecurityException, GigiApiException {
110         this(c, csr, (CertificateProfile) null);
111     }
112
113     public CertificateRequest(AuthorizationContext ctx, String csr, CertificateProfile cp) throws GeneralSecurityException, IOException, IOException {
114         this.ctx = ctx;
115         if (cp != null) {
116             profile = cp;
117         } else if (ctx.getActor().getAssurancePoints() > 50) {
118             profile = CertificateProfile.getByName("client-a");
119         }
120         byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
121         PKCS10 parsed = new PKCS10(data);
122         PKCS10Attributes atts = parsed.getAttributes();
123
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));
133                     } else {
134                         name = value;
135                     }
136                 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
137                     // TODO? parse invalid SANs
138                 }
139             }
140         }
141
142         for (PKCS10Attribute b : atts.getAttributes()) {
143
144             if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
145                 // unknown attrib
146                 continue;
147             }
148
149             for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
150                 if (c instanceof SubjectAlternativeNameExtension) {
151
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()));
161                         }
162                     }
163                 } else if (c instanceof ExtendedKeyUsageExtension) {
164                     ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
165                     String appendix = "";
166                     if (ctx.getActor().getAssurancePoints() >= 50) {
167                         appendix = "-a";
168                     }
169                     for (String s : ekue.getExtendedKeyUsage()) {
170                         if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
171                             // server
172                             profile = CertificateProfile.getByName("server" + appendix);
173                         } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
174                             // client
175                             profile = CertificateProfile.getByName("client" + appendix);
176                         } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
177                             // code sign
178                         } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
179                             // emailProtection
180                             profile = CertificateProfile.getByName("mail" + appendix);
181                         } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
182                             // timestamp
183                         } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
184                             // OCSP
185                         }
186                     }
187                 } else {
188                     // Unknown requested extension
189                 }
190             }
191
192         }
193         this.SANs = SANs;
194         pk = parsed.getSubjectPublicKeyInfo();
195         String sign = getSignatureAlgorithm(data);
196         guessDigest(sign);
197
198         this.csr = csr;
199         this.csrType = CSRType.CSR;
200     }
201
202     public CertificateRequest(AuthorizationContext ctx, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
203         this.ctx = ctx;
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");
209         }
210         pk = parsed.getPubkey();
211         String sign = getSignatureAlgorithm(data);
212         guessDigest(sign);
213         this.SANs = new HashSet<>();
214         this.csr = "SPKAC=" + cleanedSPKAC;
215         this.csrType = CSRType.SPKAC;
216
217     }
218
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();
223     }
224
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;
230         }
231     }
232
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());
247         }
248     }
249
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("")) {
257                     continue;
258                 }
259                 if (parts[0].contains("@")) {
260                     parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
261                 } else {
262                     parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
263                 }
264                 continue;
265             }
266             try {
267                 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase().trim());
268                 if (t == null) {
269                     continue;
270                 }
271                 parsedNames.add(new SubjectAlternateName(t, parts[1].trim()));
272             } catch (IllegalArgumentException e) {
273                 // invalid enum type
274                 continue;
275             }
276         }
277         return parsedNames;
278     }
279
280     public Set<SubjectAlternateName> getSANs() {
281         return SANs;
282     }
283
284     public String getName() {
285         return name;
286     }
287
288     public synchronized String getOu() {
289         if (ctx.getTarget() instanceof Organisation) {
290             return ou;
291         }
292         throw new IllegalStateException();
293     }
294
295     public Digest getSelectedDigest() {
296         return selectedDigest;
297     }
298
299     public CertificateProfile getProfile() {
300         return profile;
301     }
302
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();
305         this.name = nameIn;
306         if (hashAlg != null) {
307             selectedDigest = Digest.valueOf(hashAlg);
308         }
309         this.profile = CertificateProfile.getByName(profileStr);
310         if (ctx.getTarget() instanceof Organisation) {
311             this.ou = ou;
312         }
313
314         if ( !this.profile.canBeIssuedBy(ctx.getTarget(), ctx.getActor())) {
315             this.profile = CertificateProfile.getById(1);
316             error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
317             throw error;
318         }
319
320         verifySANs(error, profile, parseSANBox(SANsStr), ctx.getTarget(), ctx.getActor());
321
322         if ( !error.isEmpty()) {
323             throw error;
324         }
325         return true;
326     }
327
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");
332         pDNS = null;
333         pMail = null;
334         for (SubjectAlternateName san : sANs2) {
335             if (san.getType() == SANType.DNS) {
336                 if (domainTemp != null && owner.isValidDomain(san.getName())) {
337                     boolean valid;
338                     try {
339                         DomainAssessment.checkCertifiableDomain(san.getName(), user.isInGroup(Group.CODESIGNING), false);
340                         valid = true;
341                     } catch (GigiApiException e) {
342                         valid = false;
343                     }
344                     if ( !valid || !CAA.verifyDomainAccess(owner, p, san.getName()) || (pDNS != null && !domainTemp.isMultiple())) {
345                         // remove
346                     } else {
347                         if (pDNS == null) {
348                             pDNS = san.getName();
349                         }
350                         filteredSANs.add(san);
351                         continue;
352                     }
353                 }
354             } else if (san.getType() == SANType.EMAIL) {
355                 if (emailTemp != null && owner.isValidEmail(san.getName())) {
356                     if (pMail != null && !emailTemp.isMultiple()) {
357                         // remove
358                     } else {
359                         if (pMail == null) {
360                             pMail = san.getName();
361                         }
362                         filteredSANs.add(san);
363                         continue;
364                     }
365                 }
366             }
367             error.mergeInto(new GigiApiException(SprintfCommand.createSimple(//
368                     "The requested Subject alternate name \"{0}\" has been removed.", san.getType().toString().toLowerCase() + ":" + san.getName())));
369         }
370         SANs = filteredSANs;
371     }
372
373     // domain email name name=WoTUser orga
374     public synchronized Certificate draft() throws GigiApiException {
375
376         GigiApiException error = new GigiApiException();
377
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());
384
385         // Ok, let's determine the CN
386         // the CN is
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
389
390         // 2. the user's "primary domain", iff "1." doesn't match and there is a
391         // primary domain. (domainTemp != null)
392
393         String verifiedCN = null;
394         if (ctx.getTarget() instanceof Organisation) {
395             if ( !name.equals("")) {
396                 verifiedCN = name;
397             }
398         } else {
399             verifiedCN = verifyName(error, nameTemp, wotUserTemp, verifiedCN);
400         }
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
405             verifiedCN = pDNS;
406         }
407         if (verifiedCN != null) {
408             subject.put("CN", verifiedCN);
409         }
410
411         if (pMail != null) {
412             if (emailTemp != null) {
413                 subject.put("EMAIL", pMail);
414             } else {
415                 // verify SANs should prevent this
416                 pMail = null;
417                 error.mergeInto(new GigiApiException("You may not include an email in this certificate."));
418             }
419         } else {
420             if (emailTemp != null && emailTemp.isRequired()) {
421                 error.mergeInto(new GigiApiException("You need to include an email in this certificate."));
422             }
423         }
424
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());
431             if (ou != null) {
432                 subject.put("OU", ou);
433             }
434         }
435         System.out.println(subject);
436         if ( !error.isEmpty()) {
437             throw error;
438         }
439         try {
440             if (RATE_LIMIT.isLimitExceeded(Integer.toString(ctx.getActor().getId()))) {
441                 throw new GigiApiException("Rate Limit Exceeded");
442             }
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) {
446             e.printStackTrace();
447         }
448         return null;
449     }
450
451     // 100 per 10 minutes
452     public static final RateLimit RATE_LIMIT = new RateLimit(100, 10 * 60 * 1000);
453
454     private String verifyName(GigiApiException error, PropertyTemplate nameTemp, PropertyTemplate wotUserTemp, String verifiedCN) {
455         // real names,
456         // possible configurations: name {y,null,?}, name=WoTUser {y,null}
457         // semantics:
458         // y * -> real
459         // null y -> default
460         // null null -> 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."));
468         }
469         if (nameTemp != null && nameTemp.isRequired() && !nameTemp.isMultiple()) {
470             realIsOK = true;
471         } else if (nameTemp == null) {
472             defaultIsOK = wotUserTemp != null;
473             nullIsOK = !defaultIsOK;
474         } else if (nameTemp != null && !nameTemp.isRequired() && !nameTemp.isMultiple()) {
475             realIsOK = true;
476             defaultIsOK = true;
477             nullIsOK = wotUserTemp == null;
478         } else {
479             error.mergeInto(new GigiApiException("Internal configuration error detected."));
480         }
481         if (ctx.getTarget() instanceof User) {
482             User u = (User) ctx.getTarget();
483             if (name != null && u.isValidName(name)) {
484                 if (realIsOK) {
485                     verifiedCN = name;
486                 } else {
487                     error.mergeInto(new GigiApiException("Your real name is not allowed in this certificate."));
488                     if (defaultIsOK) {
489                         name = DEFAULT_CN;
490                     } else if (nullIsOK) {
491                         name = "";
492                     }
493                 }
494             } else if (name != null && name.equals(DEFAULT_CN)) {
495                 if (defaultIsOK) {
496                     verifiedCN = name;
497                 } else {
498                     error.mergeInto(new GigiApiException("The default name is not allowed in this certificate."));
499                     if (nullIsOK) {
500                         name = "";
501                     } else if (realIsOK) {
502                         name = u.getName().toString();
503                     }
504                 }
505             } else if (name == null || name.equals("")) {
506                 if (nullIsOK) {
507                     verifiedCN = "";
508                 } else {
509                     error.mergeInto(new GigiApiException("A name is required in this certificate."));
510                     if (defaultIsOK) {
511                         name = DEFAULT_CN;
512                     } else if (realIsOK) {
513                         name = u.getName().toString();
514                     }
515                 }
516             } else {
517                 error.mergeInto(new GigiApiException("The name you entered was invalid."));
518
519             }
520             if (wotUserTemp != null) {
521                 if ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple()) {
522                     error.mergeInto(new GigiApiException("Internal configuration error detected."));
523                 }
524                 if ( !name.equals(DEFAULT_CN)) {
525                     name = DEFAULT_CN;
526                     error.mergeInto(new GigiApiException("You may not change the name for this certificate type."));
527                 } else {
528                     verifiedCN = DEFAULT_CN;
529                 }
530
531             } else {
532                 if (nameTemp != null) {
533                     if (name.equals("")) {
534                         if (nameTemp.isRequired()) {
535                             // nothing, but required
536                             name = DEFAULT_CN;
537                             error.mergeInto(new GigiApiException("No name entered, but one was required."));
538                         } else {
539                             // nothing and not required
540
541                         }
542                     } else if (u.isValidName(name)) {
543                         verifiedCN = name;
544                     } else {
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;
549                         } else {
550                             name = 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."));
552                         }
553                     }
554                 } else {
555                     if ( !name.equals("")) {
556                         name = "";
557                         error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
558                     }
559                 }
560             }
561         } else {
562             if (realIsOK) {
563                 verifiedCN = name;
564             } else {
565                 verifiedCN = "";
566                 name = "";
567                 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
568             }
569         }
570
571         return verifiedCN;
572     }
573 }