chg: enforce email address for certificate was pinged within 6 months
[gigi.git] / src / club / wpia / gigi / pages / account / certs / CertificateRequest.java
1 package club.wpia.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 club.wpia.gigi.GigiApiException;
18 import club.wpia.gigi.crypto.SPKAC;
19 import club.wpia.gigi.crypto.key.KeyCheck;
20 import club.wpia.gigi.dbObjects.Certificate;
21 import club.wpia.gigi.dbObjects.Certificate.CSRType;
22 import club.wpia.gigi.dbObjects.Certificate.SANType;
23 import club.wpia.gigi.dbObjects.Certificate.SubjectAlternateName;
24 import club.wpia.gigi.dbObjects.CertificateOwner;
25 import club.wpia.gigi.dbObjects.CertificateProfile;
26 import club.wpia.gigi.dbObjects.CertificateProfile.PropertyTemplate;
27 import club.wpia.gigi.dbObjects.Digest;
28 import club.wpia.gigi.dbObjects.Group;
29 import club.wpia.gigi.dbObjects.Organisation;
30 import club.wpia.gigi.dbObjects.User;
31 import club.wpia.gigi.output.template.SprintfCommand;
32 import club.wpia.gigi.util.AuthorizationContext;
33 import club.wpia.gigi.util.CAA;
34 import club.wpia.gigi.util.DomainAssessment;
35 import club.wpia.gigi.util.PEM;
36 import club.wpia.gigi.util.RateLimit;
37 import club.wpia.gigi.util.ServerConstants;
38 import club.wpia.gigi.util.TimeConditions;
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 = ServerConstants.getAppName() + " 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, GigiApiException {
114         this.ctx = ctx;
115         if (cp != null) {
116             profile = cp;
117         } else if (ctx.getActor().getVerificationPoints() > 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().getVerificationPoints() >= 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         KeyCheck.checkKey(pk);
196
197         String sign = getSignatureAlgorithm(data);
198         guessDigest(sign);
199
200         this.csr = csr;
201         this.csrType = CSRType.CSR;
202     }
203
204     public CertificateRequest(AuthorizationContext ctx, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
205         this.ctx = ctx;
206         String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
207         byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
208         SPKAC parsed = new SPKAC(data);
209         if ( !parsed.getChallenge().equals(spkacChallenge)) {
210             throw new GigiApiException("Challenge mismatch");
211         }
212         pk = parsed.getPubkey();
213         KeyCheck.checkKey(pk);
214
215         String sign = getSignatureAlgorithm(data);
216         guessDigest(sign);
217         this.SANs = new HashSet<>();
218         this.csr = "SPKAC=" + cleanedSPKAC;
219         this.csrType = CSRType.SPKAC;
220     }
221
222     private static String getSignatureAlgorithm(byte[] data) throws IOException {
223         DerInputStream in = new DerInputStream(data);
224         DerValue[] seq = in.getSequence(3);
225         return AlgorithmId.parse(seq[1]).getName();
226     }
227
228     private void guessDigest(String sign) {
229         if (sign.toLowerCase().startsWith("sha512")) {
230             selectedDigest = Digest.SHA512;
231         } else if (sign.toLowerCase().startsWith("sha384")) {
232             selectedDigest = Digest.SHA384;
233         } else if (sign.toLowerCase().startsWith("sha256")) {
234             selectedDigest = Digest.SHA256;
235         }
236     }
237
238     public void checkKeyStrength(PrintWriter out) {
239         out.println("Type: " + pk.getAlgorithm() + "<br/>");
240         if (pk instanceof RSAPublicKey) {
241             out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
242             out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
243         } else if (pk instanceof DSAPublicKey) {
244             DSAPublicKey dpk = (DSAPublicKey) pk;
245             out.println("Length: " + dpk.getY().bitLength() + "<br/>");
246             out.println(dpk.getParams());
247         } else if (pk instanceof ECPublicKey) {
248             ECPublicKey epk = (ECPublicKey) pk;
249             out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
250             out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
251             out.println(epk.getParams().getCurve());
252         }
253     }
254
255     private Set<SubjectAlternateName> parseSANBox(String SANs) {
256         String[] SANparts = SANs.split("[\r\n]+|, *");
257         Set<SubjectAlternateName> parsedNames = new LinkedHashSet<>();
258         for (String SANline : SANparts) {
259             String[] parts = SANline.split(":", 2);
260             if (parts.length == 1) {
261                 if (parts[0].trim().equals("")) {
262                     continue;
263                 }
264                 if (parts[0].contains("@")) {
265                     parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
266                 } else {
267                     parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
268                 }
269                 continue;
270             }
271             try {
272                 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase().trim());
273                 if (t == null) {
274                     continue;
275                 }
276                 parsedNames.add(new SubjectAlternateName(t, parts[1].trim()));
277             } catch (IllegalArgumentException e) {
278                 // invalid enum type
279                 continue;
280             }
281         }
282         return parsedNames;
283     }
284
285     public Set<SubjectAlternateName> getSANs() {
286         return SANs;
287     }
288
289     public String getName() {
290         return name;
291     }
292
293     public synchronized String getOu() {
294         if (ctx.getTarget() instanceof Organisation) {
295             return ou;
296         }
297         throw new IllegalStateException();
298     }
299
300     public Digest getSelectedDigest() {
301         return selectedDigest;
302     }
303
304     public CertificateProfile getProfile() {
305         return profile;
306     }
307
308     public synchronized boolean update(String nameIn, String hashAlg, String profileStr, String newOrgStr, String ou, String SANsStr) throws GigiApiException {
309         GigiApiException error = new GigiApiException();
310         this.name = nameIn;
311         if (hashAlg != null) {
312             selectedDigest = Digest.valueOf(hashAlg);
313         }
314         this.profile = CertificateProfile.getByName(profileStr);
315         if (ctx.getTarget() instanceof Organisation) {
316             this.ou = ou;
317         }
318
319         if ( !this.profile.canBeIssuedBy(ctx.getTarget(), ctx.getActor())) {
320             this.profile = CertificateProfile.getById(1);
321             error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
322             throw error;
323         }
324
325         verifySANs(error, profile, parseSANBox(SANsStr), ctx.getTarget(), ctx.getActor());
326
327         if ( !error.isEmpty()) {
328             throw error;
329         }
330         return true;
331     }
332
333     private void verifySANs(GigiApiException error, CertificateProfile p, Set<SubjectAlternateName> sANs2, CertificateOwner owner, User user) {
334         Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
335         PropertyTemplate domainTemp = p.getTemplates().get("domain");
336         PropertyTemplate emailTemp = p.getTemplates().get("email");
337         pDNS = null;
338         pMail = null;
339         for (SubjectAlternateName san : sANs2) {
340             if (san.getType() == SANType.DNS) {
341                 if (domainTemp != null && owner.isValidDomain(san.getName())) {
342                     boolean valid;
343                     try {
344                         DomainAssessment.checkCertifiableDomain(san.getName(), user.isInGroup(Group.CODESIGNING), false);
345                         valid = true;
346                         if ( !valid || !CAA.verifyDomainAccess(owner, p, san.getName()) || (pDNS != null && !domainTemp.isMultiple())) {
347                             // remove
348                         } else {
349                             if (pDNS == null) {
350                                 pDNS = san.getName();
351                             }
352                             filteredSANs.add(san);
353                             continue;
354                         }
355                     } catch (GigiApiException e) {
356                         error.mergeInto(e);
357                         valid = false;
358                     }
359                 }
360             } else if (san.getType() == SANType.EMAIL && emailTemp != null) {
361                 if (owner.isValidEmail(san.getName())) {
362                     if (pMail != null && !emailTemp.isMultiple()) {
363                         // remove
364                     } else {
365                         if (pMail == null) {
366                             pMail = san.getName();
367                         }
368                         filteredSANs.add(san);
369                         continue;
370                     }
371                 } else {
372                     // remove
373                     error.mergeInto(new GigiApiException(SprintfCommand.createSimple(//
374                             "The requested subject alternate name email address \"{0}\" needs an email ping within the past {1} months.", san.getType().toString().toLowerCase() + ":" + san.getName(), TimeConditions.getInstance().getEmailPingMonths())));
375                     break;
376                 }
377             }
378             error.mergeInto(new GigiApiException(SprintfCommand.createSimple(//
379                     "The requested subject alternate name (SAN) \"{0}\" has been removed.", san.getType().toString().toLowerCase() + ":" + san.getName())));
380         }
381         SANs = filteredSANs;
382     }
383
384     // domain email name name=WoTUser orga
385     public synchronized Certificate draft() throws GigiApiException {
386
387         GigiApiException error = new GigiApiException();
388
389         HashMap<String, String> subject = new HashMap<>();
390         PropertyTemplate domainTemp = profile.getTemplates().get("domain");
391         PropertyTemplate emailTemp = profile.getTemplates().get("email");
392         PropertyTemplate nameTemp = profile.getTemplates().get("name");
393         PropertyTemplate wotUserTemp = profile.getTemplates().get("name=WoTUser");
394         verifySANs(error, profile, SANs, ctx.getTarget(), ctx.getActor());
395
396         // Ok, let's determine the CN
397         // the CN is
398         // 1. the user's "real name", iff the real name is to be included i.e.
399         // not empty (name), or to be forced to WOTUser
400
401         // 2. the user's "primary domain", iff "1." doesn't match and there is a
402         // primary domain. (domainTemp != null)
403
404         String verifiedCN = null;
405         if (ctx.getTarget() instanceof Organisation) {
406             if ( !name.equals("")) {
407                 verifiedCN = name;
408             }
409         } else {
410             verifiedCN = verifyName(error, nameTemp, wotUserTemp, verifiedCN);
411         }
412         if (pDNS == null && domainTemp != null && domainTemp.isRequired()) {
413             error.mergeInto(new GigiApiException("Server Certificates require a DNS name."));
414         } else if (domainTemp != null && verifiedCN == null) {
415             // user may add domains
416             verifiedCN = pDNS;
417         }
418         if (verifiedCN != null) {
419             subject.put("CN", verifiedCN);
420         }
421
422         if (pMail != null) {
423             if (emailTemp != null) {
424                 subject.put("EMAIL", pMail);
425             } else {
426                 // verify SANs should prevent this
427                 pMail = null;
428                 error.mergeInto(new GigiApiException("You may not include an email in this certificate."));
429             }
430         } else {
431             if (emailTemp != null && emailTemp.isRequired()) {
432                 error.mergeInto(new GigiApiException("You need to include an email in this certificate."));
433             }
434         }
435
436         if (ctx.getTarget() instanceof Organisation) {
437             Organisation org = (Organisation) ctx.getTarget();
438             subject.put("O", org.getName());
439             subject.put("C", org.getCountry().getCode());
440             subject.put("ST", org.getProvince());
441             subject.put("L", org.getCity());
442             if (ou != null) {
443                 subject.put("OU", ou);
444             }
445         }
446         System.out.println(subject);
447         if ( !error.isEmpty()) {
448             throw error;
449         }
450         try {
451             if (RATE_LIMIT.isLimitExceeded(Integer.toString(ctx.getActor().getId()))) {
452                 throw new GigiApiException("Rate Limit Exceeded");
453             }
454             return new Certificate(ctx.getTarget(), ctx.getActor(), subject, selectedDigest, //
455                     this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
456         } catch (IOException e) {
457             e.printStackTrace();
458         }
459         return null;
460     }
461
462     // 100 per 10 minutes
463     public static final RateLimit RATE_LIMIT = new RateLimit(100, 10 * 60 * 1000);
464
465     private String verifyName(GigiApiException error, PropertyTemplate nameTemp, PropertyTemplate wotUserTemp, String verifiedCN) {
466         // real names,
467         // possible configurations: name {y,null,?}, name=WoTUser {y,null}
468         // semantics:
469         // y * -> real
470         // null y -> default
471         // null null -> null
472         // ? y -> real, default
473         // ? null -> real, default, null
474         boolean realIsOK = false;
475         boolean nullIsOK = false;
476         boolean defaultIsOK = false;
477         if (wotUserTemp != null && ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple())) {
478             error.mergeInto(new GigiApiException("Internal configuration error detected."));
479         }
480         if (nameTemp != null && nameTemp.isRequired() && !nameTemp.isMultiple()) {
481             realIsOK = true;
482         } else if (nameTemp == null) {
483             defaultIsOK = wotUserTemp != null;
484             nullIsOK = !defaultIsOK;
485         } else if (nameTemp != null && !nameTemp.isRequired() && !nameTemp.isMultiple()) {
486             realIsOK = true;
487             defaultIsOK = true;
488             nullIsOK = wotUserTemp == null;
489         } else {
490             error.mergeInto(new GigiApiException("Internal configuration error detected."));
491         }
492         if (ctx.getTarget() instanceof User) {
493             User u = (User) ctx.getTarget();
494             if (name != null && u.isValidName(name)) {
495                 if (realIsOK) {
496                     verifiedCN = name;
497                 } else {
498                     error.mergeInto(new GigiApiException("Your real name is not allowed in this certificate."));
499                     if (defaultIsOK) {
500                         name = DEFAULT_CN;
501                     } else if (nullIsOK) {
502                         name = "";
503                     }
504                 }
505             } else if (name != null && name.equals(DEFAULT_CN)) {
506                 if (defaultIsOK) {
507                     verifiedCN = name;
508                 } else {
509                     error.mergeInto(new GigiApiException("The default name is not allowed in this certificate."));
510                     if (nullIsOK) {
511                         name = "";
512                     } else if (realIsOK) {
513                         name = u.getPreferredName().toString();
514                     }
515                 }
516             } else if (name == null || name.equals("")) {
517                 if (nullIsOK) {
518                     verifiedCN = "";
519                 } else {
520                     error.mergeInto(new GigiApiException("A name is required in this certificate."));
521                     if (defaultIsOK) {
522                         name = DEFAULT_CN;
523                     } else if (realIsOK) {
524                         name = u.getPreferredName().toString();
525                     }
526                 }
527             } else {
528                 error.mergeInto(new GigiApiException("The name you entered was invalid."));
529
530             }
531             if (wotUserTemp != null) {
532                 if ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple()) {
533                     error.mergeInto(new GigiApiException("Internal configuration error detected."));
534                 }
535                 if ( !name.equals(DEFAULT_CN)) {
536                     name = DEFAULT_CN;
537                     error.mergeInto(new GigiApiException("You may not change the name for this certificate type."));
538                 } else {
539                     verifiedCN = DEFAULT_CN;
540                 }
541
542             } else {
543                 if (nameTemp != null) {
544                     if (name.equals("")) {
545                         if (nameTemp.isRequired()) {
546                             // nothing, but required
547                             name = DEFAULT_CN;
548                             error.mergeInto(new GigiApiException("No name entered, but one was required."));
549                         } else {
550                             // nothing and not required
551
552                         }
553                     } else if (u.isValidName(name)) {
554                         verifiedCN = name;
555                     } else {
556                         if (nameTemp.isRequired()) {
557                             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."));
558                         } else if (name.equals(DEFAULT_CN)) {
559                             verifiedCN = DEFAULT_CN;
560                         } else {
561                             name = DEFAULT_CN;
562                             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."));
563                         }
564                     }
565                 } else {
566                     if ( !name.equals("")) {
567                         name = "";
568                         error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
569                     }
570                 }
571             }
572         } else {
573             if (realIsOK) {
574                 verifiedCN = name;
575             } else {
576                 verifiedCN = "";
577                 name = "";
578                 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
579             }
580         }
581
582         return verifiedCN;
583     }
584 }