]> WPIA git - gigi.git/blob - src/club/wpia/gigi/pages/account/certs/CertificateRequest.java
2755b18f974870902e1bdde2b8286c03db883d12
[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.dbObjects.Certificate;
20 import club.wpia.gigi.dbObjects.CertificateOwner;
21 import club.wpia.gigi.dbObjects.CertificateProfile;
22 import club.wpia.gigi.dbObjects.Digest;
23 import club.wpia.gigi.dbObjects.Group;
24 import club.wpia.gigi.dbObjects.Organisation;
25 import club.wpia.gigi.dbObjects.User;
26 import club.wpia.gigi.dbObjects.Certificate.CSRType;
27 import club.wpia.gigi.dbObjects.Certificate.SANType;
28 import club.wpia.gigi.dbObjects.Certificate.SubjectAlternateName;
29 import club.wpia.gigi.dbObjects.CertificateProfile.PropertyTemplate;
30 import club.wpia.gigi.output.template.SprintfCommand;
31 import club.wpia.gigi.util.AuthorizationContext;
32 import club.wpia.gigi.util.CAA;
33 import club.wpia.gigi.util.DomainAssessment;
34 import club.wpia.gigi.util.PEM;
35 import club.wpia.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;
57
58 public class CertificateRequest {
59
60     public static final String DEFAULT_CN = "SomeCA User";
61
62     public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
63             1, 3, 6, 1, 5, 5, 7, 3, 1
64     });
65
66     public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
67             1, 3, 6, 1, 5, 5, 7, 3, 2
68     });
69
70     public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
71             1, 3, 6, 1, 5, 5, 7, 3, 3
72     });
73
74     public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
75             1, 3, 6, 1, 5, 5, 7, 3, 4
76     });
77
78     public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
79             1, 3, 6, 1, 5, 5, 7, 3, 8
80     });
81
82     public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
83             1, 3, 6, 1, 5, 5, 7, 3, 9
84     });
85
86     private CSRType csrType;
87
88     private final PublicKey pk;
89
90     private String csr;
91
92     public String name = DEFAULT_CN;
93
94     private Set<SubjectAlternateName> SANs;
95
96     private Digest selectedDigest = Digest.getDefault();
97
98     private CertificateProfile profile = CertificateProfile.getById(1);
99
100     private String ou = "";
101
102     private AuthorizationContext ctx;
103
104     private String pDNS, pMail;
105
106     public CertificateRequest(AuthorizationContext c, String csr) throws IOException, GeneralSecurityException, GigiApiException {
107         this(c, csr, (CertificateProfile) null);
108     }
109
110     public CertificateRequest(AuthorizationContext ctx, String csr, CertificateProfile cp) throws GeneralSecurityException, IOException, IOException {
111         this.ctx = ctx;
112         if (cp != null) {
113             profile = cp;
114         } else if (ctx.getActor().getAssurancePoints() > 50) {
115             profile = CertificateProfile.getByName("client-a");
116         }
117         byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
118         PKCS10 parsed = new PKCS10(data);
119         PKCS10Attributes atts = parsed.getAttributes();
120
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));
130                     } else {
131                         name = value;
132                     }
133                 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
134                     // TODO? parse invalid SANs
135                 }
136             }
137         }
138
139         for (PKCS10Attribute b : atts.getAttributes()) {
140
141             if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
142                 // unknown attrib
143                 continue;
144             }
145
146             for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
147                 if (c instanceof SubjectAlternativeNameExtension) {
148
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()));
158                         }
159                     }
160                 } else if (c instanceof ExtendedKeyUsageExtension) {
161                     ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
162                     String appendix = "";
163                     if (ctx.getActor().getAssurancePoints() >= 50) {
164                         appendix = "-a";
165                     }
166                     for (String s : ekue.getExtendedKeyUsage()) {
167                         if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
168                             // server
169                             profile = CertificateProfile.getByName("server" + appendix);
170                         } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
171                             // client
172                             profile = CertificateProfile.getByName("client" + appendix);
173                         } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
174                             // code sign
175                         } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
176                             // emailProtection
177                             profile = CertificateProfile.getByName("mail" + appendix);
178                         } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
179                             // timestamp
180                         } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
181                             // OCSP
182                         }
183                     }
184                 } else {
185                     // Unknown requested extension
186                 }
187             }
188
189         }
190         this.SANs = SANs;
191         pk = parsed.getSubjectPublicKeyInfo();
192         String sign = getSignatureAlgorithm(data);
193         guessDigest(sign);
194
195         this.csr = csr;
196         this.csrType = CSRType.CSR;
197     }
198
199     public CertificateRequest(AuthorizationContext ctx, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
200         this.ctx = ctx;
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");
206         }
207         pk = parsed.getPubkey();
208         String sign = getSignatureAlgorithm(data);
209         guessDigest(sign);
210         this.SANs = new HashSet<>();
211         this.csr = "SPKAC=" + cleanedSPKAC;
212         this.csrType = CSRType.SPKAC;
213
214     }
215
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();
220     }
221
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;
227         } else if (sign.toLowerCase().startsWith("sha256")) {
228             selectedDigest = Digest.SHA256;
229         }
230     }
231
232     public void checkKeyStrength(PrintWriter out) {
233         out.println("Type: " + pk.getAlgorithm() + "<br/>");
234         if (pk instanceof RSAPublicKey) {
235             out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
236             out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
237         } else if (pk instanceof DSAPublicKey) {
238             DSAPublicKey dpk = (DSAPublicKey) pk;
239             out.println("Length: " + dpk.getY().bitLength() + "<br/>");
240             out.println(dpk.getParams());
241         } else if (pk instanceof ECPublicKey) {
242             ECPublicKey epk = (ECPublicKey) pk;
243             out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
244             out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
245             out.println(epk.getParams().getCurve());
246         }
247     }
248
249     private Set<SubjectAlternateName> parseSANBox(String SANs) {
250         String[] SANparts = SANs.split("[\r\n]+|, *");
251         Set<SubjectAlternateName> parsedNames = new LinkedHashSet<>();
252         for (String SANline : SANparts) {
253             String[] parts = SANline.split(":", 2);
254             if (parts.length == 1) {
255                 if (parts[0].trim().equals("")) {
256                     continue;
257                 }
258                 if (parts[0].contains("@")) {
259                     parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
260                 } else {
261                     parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
262                 }
263                 continue;
264             }
265             try {
266                 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase().trim());
267                 if (t == null) {
268                     continue;
269                 }
270                 parsedNames.add(new SubjectAlternateName(t, parts[1].trim()));
271             } catch (IllegalArgumentException e) {
272                 // invalid enum type
273                 continue;
274             }
275         }
276         return parsedNames;
277     }
278
279     public Set<SubjectAlternateName> getSANs() {
280         return SANs;
281     }
282
283     public String getName() {
284         return name;
285     }
286
287     public synchronized String getOu() {
288         if (ctx.getTarget() instanceof Organisation) {
289             return ou;
290         }
291         throw new IllegalStateException();
292     }
293
294     public Digest getSelectedDigest() {
295         return selectedDigest;
296     }
297
298     public CertificateProfile getProfile() {
299         return profile;
300     }
301
302     public synchronized boolean update(String nameIn, String hashAlg, String profileStr, String newOrgStr, String ou, String SANsStr) throws GigiApiException {
303         GigiApiException error = new GigiApiException();
304         this.name = nameIn;
305         if (hashAlg != null) {
306             selectedDigest = Digest.valueOf(hashAlg);
307         }
308         this.profile = CertificateProfile.getByName(profileStr);
309         if (ctx.getTarget() instanceof Organisation) {
310             this.ou = ou;
311         }
312
313         if ( !this.profile.canBeIssuedBy(ctx.getTarget(), ctx.getActor())) {
314             this.profile = CertificateProfile.getById(1);
315             error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
316             throw error;
317         }
318
319         verifySANs(error, profile, parseSANBox(SANsStr), ctx.getTarget(), ctx.getActor());
320
321         if ( !error.isEmpty()) {
322             throw error;
323         }
324         return true;
325     }
326
327     private void verifySANs(GigiApiException error, CertificateProfile p, Set<SubjectAlternateName> sANs2, CertificateOwner owner, User user) {
328         Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
329         PropertyTemplate domainTemp = p.getTemplates().get("domain");
330         PropertyTemplate emailTemp = p.getTemplates().get("email");
331         pDNS = null;
332         pMail = null;
333         for (SubjectAlternateName san : sANs2) {
334             if (san.getType() == SANType.DNS) {
335                 if (domainTemp != null && owner.isValidDomain(san.getName())) {
336                     boolean valid;
337                     try {
338                         DomainAssessment.checkCertifiableDomain(san.getName(), user.isInGroup(Group.CODESIGNING), false);
339                         valid = true;
340                         if ( !valid || !CAA.verifyDomainAccess(owner, p, san.getName()) || (pDNS != null && !domainTemp.isMultiple())) {
341                             // remove
342                         } else {
343                             if (pDNS == null) {
344                                 pDNS = san.getName();
345                             }
346                             filteredSANs.add(san);
347                             continue;
348                         }
349                     } catch (GigiApiException e) {
350                         error.mergeInto(e);
351                         valid = false;
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 (SAN) \"{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.getCountry().getCode());
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.getPreferredName().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.getPreferredName().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 verified 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 verified 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 }