]> WPIA git - gigi.git/blob - src/club/wpia/gigi/pages/account/certs/CertificateRequest.java
Merge "fix: Somewhat sensibly split the wishlist document"
[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.Certificate.CSRType;
21 import club.wpia.gigi.dbObjects.Certificate.SANType;
22 import club.wpia.gigi.dbObjects.Certificate.SubjectAlternateName;
23 import club.wpia.gigi.dbObjects.CertificateOwner;
24 import club.wpia.gigi.dbObjects.CertificateProfile;
25 import club.wpia.gigi.dbObjects.CertificateProfile.PropertyTemplate;
26 import club.wpia.gigi.dbObjects.Digest;
27 import club.wpia.gigi.dbObjects.Group;
28 import club.wpia.gigi.dbObjects.Organisation;
29 import club.wpia.gigi.dbObjects.User;
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 club.wpia.gigi.util.ServerConstants;
37 import sun.security.pkcs.PKCS9Attribute;
38 import sun.security.pkcs10.PKCS10;
39 import sun.security.pkcs10.PKCS10Attribute;
40 import sun.security.pkcs10.PKCS10Attributes;
41 import sun.security.util.DerInputStream;
42 import sun.security.util.DerValue;
43 import sun.security.util.ObjectIdentifier;
44 import sun.security.x509.AVA;
45 import sun.security.x509.AlgorithmId;
46 import sun.security.x509.CertificateExtensions;
47 import sun.security.x509.DNSName;
48 import sun.security.x509.ExtendedKeyUsageExtension;
49 import sun.security.x509.Extension;
50 import sun.security.x509.GeneralName;
51 import sun.security.x509.GeneralNameInterface;
52 import sun.security.x509.GeneralNames;
53 import sun.security.x509.PKIXExtensions;
54 import sun.security.x509.RDN;
55 import sun.security.x509.RFC822Name;
56 import sun.security.x509.SubjectAlternativeNameExtension;
57 import sun.security.x509.X500Name;
58
59 public class CertificateRequest {
60
61     public static final String DEFAULT_CN = ServerConstants.getAppName() + " User";
62
63     public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
64             1, 3, 6, 1, 5, 5, 7, 3, 1
65     });
66
67     public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
68             1, 3, 6, 1, 5, 5, 7, 3, 2
69     });
70
71     public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
72             1, 3, 6, 1, 5, 5, 7, 3, 3
73     });
74
75     public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
76             1, 3, 6, 1, 5, 5, 7, 3, 4
77     });
78
79     public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
80             1, 3, 6, 1, 5, 5, 7, 3, 8
81     });
82
83     public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
84             1, 3, 6, 1, 5, 5, 7, 3, 9
85     });
86
87     private CSRType csrType;
88
89     private final PublicKey pk;
90
91     private String csr;
92
93     public String name = DEFAULT_CN;
94
95     private Set<SubjectAlternateName> SANs;
96
97     private Digest selectedDigest = Digest.getDefault();
98
99     private CertificateProfile profile = CertificateProfile.getById(1);
100
101     private String ou = "";
102
103     private AuthorizationContext ctx;
104
105     private String pDNS, pMail;
106
107     public CertificateRequest(AuthorizationContext c, String csr) throws IOException, GeneralSecurityException, GigiApiException {
108         this(c, csr, (CertificateProfile) null);
109     }
110
111     public CertificateRequest(AuthorizationContext ctx, String csr, CertificateProfile cp) throws GeneralSecurityException, IOException, IOException {
112         this.ctx = ctx;
113         if (cp != null) {
114             profile = cp;
115         } else if (ctx.getActor().getVerificationPoints() > 50) {
116             profile = CertificateProfile.getByName("client-a");
117         }
118         byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
119         PKCS10 parsed = new PKCS10(data);
120         PKCS10Attributes atts = parsed.getAttributes();
121
122         TreeSet<SubjectAlternateName> SANs = new TreeSet<>();
123         for (RDN r : parsed.getSubjectName().rdns()) {
124             for (AVA a : r.avas()) {
125                 if (a.getObjectIdentifier().equals((Object) PKCS9Attribute.EMAIL_ADDRESS_OID)) {
126                     SANs.add(new SubjectAlternateName(SANType.EMAIL, a.getValueString()));
127                 } else if (a.getObjectIdentifier().equals((Object) X500Name.commonName_oid)) {
128                     String value = a.getValueString();
129                     if (value.contains(".") && !value.contains(" ")) {
130                         SANs.add(new SubjectAlternateName(SANType.DNS, value));
131                     } else {
132                         name = value;
133                     }
134                 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
135                     // TODO? parse invalid SANs
136                 }
137             }
138         }
139
140         for (PKCS10Attribute b : atts.getAttributes()) {
141
142             if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
143                 // unknown attrib
144                 continue;
145             }
146
147             for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
148                 if (c instanceof SubjectAlternativeNameExtension) {
149
150                     SubjectAlternativeNameExtension san = (SubjectAlternativeNameExtension) c;
151                     GeneralNames obj = san.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
152                     for (int i = 0; i < obj.size(); i++) {
153                         GeneralName generalName = obj.get(i);
154                         GeneralNameInterface peeled = generalName.getName();
155                         if (peeled instanceof DNSName) {
156                             SANs.add(new SubjectAlternateName(SANType.DNS, ((DNSName) peeled).getName()));
157                         } else if (peeled instanceof RFC822Name) {
158                             SANs.add(new SubjectAlternateName(SANType.EMAIL, ((RFC822Name) peeled).getName()));
159                         }
160                     }
161                 } else if (c instanceof ExtendedKeyUsageExtension) {
162                     ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
163                     String appendix = "";
164                     if (ctx.getActor().getVerificationPoints() >= 50) {
165                         appendix = "-a";
166                     }
167                     for (String s : ekue.getExtendedKeyUsage()) {
168                         if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
169                             // server
170                             profile = CertificateProfile.getByName("server" + appendix);
171                         } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
172                             // client
173                             profile = CertificateProfile.getByName("client" + appendix);
174                         } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
175                             // code sign
176                         } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
177                             // emailProtection
178                             profile = CertificateProfile.getByName("mail" + appendix);
179                         } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
180                             // timestamp
181                         } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
182                             // OCSP
183                         }
184                     }
185                 } else {
186                     // Unknown requested extension
187                 }
188             }
189
190         }
191         this.SANs = SANs;
192         pk = parsed.getSubjectPublicKeyInfo();
193         String sign = getSignatureAlgorithm(data);
194         guessDigest(sign);
195
196         this.csr = csr;
197         this.csrType = CSRType.CSR;
198     }
199
200     public CertificateRequest(AuthorizationContext ctx, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
201         this.ctx = ctx;
202         String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
203         byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
204         SPKAC parsed = new SPKAC(data);
205         if ( !parsed.getChallenge().equals(spkacChallenge)) {
206             throw new GigiApiException("Challenge mismatch");
207         }
208         pk = parsed.getPubkey();
209         String sign = getSignatureAlgorithm(data);
210         guessDigest(sign);
211         this.SANs = new HashSet<>();
212         this.csr = "SPKAC=" + cleanedSPKAC;
213         this.csrType = CSRType.SPKAC;
214
215     }
216
217     private static String getSignatureAlgorithm(byte[] data) throws IOException {
218         DerInputStream in = new DerInputStream(data);
219         DerValue[] seq = in.getSequence(3);
220         return AlgorithmId.parse(seq[1]).getName();
221     }
222
223     private void guessDigest(String sign) {
224         if (sign.toLowerCase().startsWith("sha512")) {
225             selectedDigest = Digest.SHA512;
226         } else if (sign.toLowerCase().startsWith("sha384")) {
227             selectedDigest = Digest.SHA384;
228         } else if (sign.toLowerCase().startsWith("sha256")) {
229             selectedDigest = Digest.SHA256;
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) 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                         if ( !valid || !CAA.verifyDomainAccess(owner, p, san.getName()) || (pDNS != null && !domainTemp.isMultiple())) {
342                             // remove
343                         } else {
344                             if (pDNS == null) {
345                                 pDNS = san.getName();
346                             }
347                             filteredSANs.add(san);
348                             continue;
349                         }
350                     } catch (GigiApiException e) {
351                         error.mergeInto(e);
352                         valid = false;
353                     }
354                 }
355             } else if (san.getType() == SANType.EMAIL) {
356                 if (emailTemp != null && owner.isValidEmail(san.getName())) {
357                     if (pMail != null && !emailTemp.isMultiple()) {
358                         // remove
359                     } else {
360                         if (pMail == null) {
361                             pMail = san.getName();
362                         }
363                         filteredSANs.add(san);
364                         continue;
365                     }
366                 }
367             }
368             error.mergeInto(new GigiApiException(SprintfCommand.createSimple(//
369                     "The requested subject alternate name (SAN) \"{0}\" has been removed.", san.getType().toString().toLowerCase() + ":" + san.getName())));
370         }
371         SANs = filteredSANs;
372     }
373
374     // domain email name name=WoTUser orga
375     public synchronized Certificate draft() throws GigiApiException {
376
377         GigiApiException error = new GigiApiException();
378
379         HashMap<String, String> subject = new HashMap<>();
380         PropertyTemplate domainTemp = profile.getTemplates().get("domain");
381         PropertyTemplate emailTemp = profile.getTemplates().get("email");
382         PropertyTemplate nameTemp = profile.getTemplates().get("name");
383         PropertyTemplate wotUserTemp = profile.getTemplates().get("name=WoTUser");
384         verifySANs(error, profile, SANs, ctx.getTarget(), ctx.getActor());
385
386         // Ok, let's determine the CN
387         // the CN is
388         // 1. the user's "real name", iff the real name is to be included i.e.
389         // not empty (name), or to be forced to WOTUser
390
391         // 2. the user's "primary domain", iff "1." doesn't match and there is a
392         // primary domain. (domainTemp != null)
393
394         String verifiedCN = null;
395         if (ctx.getTarget() instanceof Organisation) {
396             if ( !name.equals("")) {
397                 verifiedCN = name;
398             }
399         } else {
400             verifiedCN = verifyName(error, nameTemp, wotUserTemp, verifiedCN);
401         }
402         if (pDNS == null && domainTemp != null && domainTemp.isRequired()) {
403             error.mergeInto(new GigiApiException("Server Certificates require a DNS name."));
404         } else if (domainTemp != null && verifiedCN == null) {
405             // user may add domains
406             verifiedCN = pDNS;
407         }
408         if (verifiedCN != null) {
409             subject.put("CN", verifiedCN);
410         }
411
412         if (pMail != null) {
413             if (emailTemp != null) {
414                 subject.put("EMAIL", pMail);
415             } else {
416                 // verify SANs should prevent this
417                 pMail = null;
418                 error.mergeInto(new GigiApiException("You may not include an email in this certificate."));
419             }
420         } else {
421             if (emailTemp != null && emailTemp.isRequired()) {
422                 error.mergeInto(new GigiApiException("You need to include an email in this certificate."));
423             }
424         }
425
426         if (ctx.getTarget() instanceof Organisation) {
427             Organisation org = (Organisation) ctx.getTarget();
428             subject.put("O", org.getName());
429             subject.put("C", org.getCountry().getCode());
430             subject.put("ST", org.getProvince());
431             subject.put("L", org.getCity());
432             if (ou != null) {
433                 subject.put("OU", ou);
434             }
435         }
436         System.out.println(subject);
437         if ( !error.isEmpty()) {
438             throw error;
439         }
440         try {
441             if (RATE_LIMIT.isLimitExceeded(Integer.toString(ctx.getActor().getId()))) {
442                 throw new GigiApiException("Rate Limit Exceeded");
443             }
444             return new Certificate(ctx.getTarget(), ctx.getActor(), subject, selectedDigest, //
445                     this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
446         } catch (IOException e) {
447             e.printStackTrace();
448         }
449         return null;
450     }
451
452     // 100 per 10 minutes
453     public static final RateLimit RATE_LIMIT = new RateLimit(100, 10 * 60 * 1000);
454
455     private String verifyName(GigiApiException error, PropertyTemplate nameTemp, PropertyTemplate wotUserTemp, String verifiedCN) {
456         // real names,
457         // possible configurations: name {y,null,?}, name=WoTUser {y,null}
458         // semantics:
459         // y * -> real
460         // null y -> default
461         // null null -> null
462         // ? y -> real, default
463         // ? null -> real, default, null
464         boolean realIsOK = false;
465         boolean nullIsOK = false;
466         boolean defaultIsOK = false;
467         if (wotUserTemp != null && ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple())) {
468             error.mergeInto(new GigiApiException("Internal configuration error detected."));
469         }
470         if (nameTemp != null && nameTemp.isRequired() && !nameTemp.isMultiple()) {
471             realIsOK = true;
472         } else if (nameTemp == null) {
473             defaultIsOK = wotUserTemp != null;
474             nullIsOK = !defaultIsOK;
475         } else if (nameTemp != null && !nameTemp.isRequired() && !nameTemp.isMultiple()) {
476             realIsOK = true;
477             defaultIsOK = true;
478             nullIsOK = wotUserTemp == null;
479         } else {
480             error.mergeInto(new GigiApiException("Internal configuration error detected."));
481         }
482         if (ctx.getTarget() instanceof User) {
483             User u = (User) ctx.getTarget();
484             if (name != null && u.isValidName(name)) {
485                 if (realIsOK) {
486                     verifiedCN = name;
487                 } else {
488                     error.mergeInto(new GigiApiException("Your real name is not allowed in this certificate."));
489                     if (defaultIsOK) {
490                         name = DEFAULT_CN;
491                     } else if (nullIsOK) {
492                         name = "";
493                     }
494                 }
495             } else if (name != null && name.equals(DEFAULT_CN)) {
496                 if (defaultIsOK) {
497                     verifiedCN = name;
498                 } else {
499                     error.mergeInto(new GigiApiException("The default name is not allowed in this certificate."));
500                     if (nullIsOK) {
501                         name = "";
502                     } else if (realIsOK) {
503                         name = u.getPreferredName().toString();
504                     }
505                 }
506             } else if (name == null || name.equals("")) {
507                 if (nullIsOK) {
508                     verifiedCN = "";
509                 } else {
510                     error.mergeInto(new GigiApiException("A name is required in this certificate."));
511                     if (defaultIsOK) {
512                         name = DEFAULT_CN;
513                     } else if (realIsOK) {
514                         name = u.getPreferredName().toString();
515                     }
516                 }
517             } else {
518                 error.mergeInto(new GigiApiException("The name you entered was invalid."));
519
520             }
521             if (wotUserTemp != null) {
522                 if ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple()) {
523                     error.mergeInto(new GigiApiException("Internal configuration error detected."));
524                 }
525                 if ( !name.equals(DEFAULT_CN)) {
526                     name = DEFAULT_CN;
527                     error.mergeInto(new GigiApiException("You may not change the name for this certificate type."));
528                 } else {
529                     verifiedCN = DEFAULT_CN;
530                 }
531
532             } else {
533                 if (nameTemp != null) {
534                     if (name.equals("")) {
535                         if (nameTemp.isRequired()) {
536                             // nothing, but required
537                             name = DEFAULT_CN;
538                             error.mergeInto(new GigiApiException("No name entered, but one was required."));
539                         } else {
540                             // nothing and not required
541
542                         }
543                     } else if (u.isValidName(name)) {
544                         verifiedCN = name;
545                     } else {
546                         if (nameTemp.isRequired()) {
547                             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."));
548                         } else if (name.equals(DEFAULT_CN)) {
549                             verifiedCN = DEFAULT_CN;
550                         } else {
551                             name = DEFAULT_CN;
552                             error.mergeInto(new GigiApiException("The name entered, does not match the details in your account. You cannot issue certificates with this name. Enter a name that matches the one that has been verified in your account or keep the default name."));
553                         }
554                     }
555                 } else {
556                     if ( !name.equals("")) {
557                         name = "";
558                         error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
559                     }
560                 }
561             }
562         } else {
563             if (realIsOK) {
564                 verifiedCN = name;
565             } else {
566                 verifiedCN = "";
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         return verifiedCN;
573     }
574 }