]> WPIA git - gigi.git/blob - src/club/wpia/gigi/pages/account/certs/CertificateRequest.java
Merge "add: show more certificates on the "roots" page"
[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 sun.security.pkcs.PKCS9Attribute;
39 import sun.security.pkcs10.PKCS10;
40 import sun.security.pkcs10.PKCS10Attribute;
41 import sun.security.pkcs10.PKCS10Attributes;
42 import sun.security.util.DerInputStream;
43 import sun.security.util.DerValue;
44 import sun.security.util.ObjectIdentifier;
45 import sun.security.x509.AVA;
46 import sun.security.x509.AlgorithmId;
47 import sun.security.x509.CertificateExtensions;
48 import sun.security.x509.DNSName;
49 import sun.security.x509.ExtendedKeyUsageExtension;
50 import sun.security.x509.Extension;
51 import sun.security.x509.GeneralName;
52 import sun.security.x509.GeneralNameInterface;
53 import sun.security.x509.GeneralNames;
54 import sun.security.x509.PKIXExtensions;
55 import sun.security.x509.RDN;
56 import sun.security.x509.RFC822Name;
57 import sun.security.x509.SubjectAlternativeNameExtension;
58 import sun.security.x509.X500Name;
59
60 public class CertificateRequest {
61
62     public static final String DEFAULT_CN = ServerConstants.getAppName() + " User";
63
64     public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
65             1, 3, 6, 1, 5, 5, 7, 3, 1
66     });
67
68     public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
69             1, 3, 6, 1, 5, 5, 7, 3, 2
70     });
71
72     public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
73             1, 3, 6, 1, 5, 5, 7, 3, 3
74     });
75
76     public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
77             1, 3, 6, 1, 5, 5, 7, 3, 4
78     });
79
80     public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
81             1, 3, 6, 1, 5, 5, 7, 3, 8
82     });
83
84     public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
85             1, 3, 6, 1, 5, 5, 7, 3, 9
86     });
87
88     private CSRType csrType;
89
90     private final PublicKey pk;
91
92     private String csr;
93
94     public String name = DEFAULT_CN;
95
96     private Set<SubjectAlternateName> SANs;
97
98     private Digest selectedDigest = Digest.getDefault();
99
100     private CertificateProfile profile = CertificateProfile.getById(1);
101
102     private String ou = "";
103
104     private AuthorizationContext ctx;
105
106     private String pDNS, pMail;
107
108     public CertificateRequest(AuthorizationContext c, String csr) throws IOException, GeneralSecurityException, GigiApiException {
109         this(c, csr, (CertificateProfile) null);
110     }
111
112     public CertificateRequest(AuthorizationContext ctx, String csr, CertificateProfile cp) throws GeneralSecurityException, IOException, IOException, GigiApiException {
113         this.ctx = ctx;
114         if (cp != null) {
115             profile = cp;
116         } else if (ctx.getActor().getVerificationPoints() > 50) {
117             profile = CertificateProfile.getByName("client-a");
118         }
119         byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
120         PKCS10 parsed = new PKCS10(data);
121         PKCS10Attributes atts = parsed.getAttributes();
122
123         TreeSet<SubjectAlternateName> SANs = new TreeSet<>();
124         for (RDN r : parsed.getSubjectName().rdns()) {
125             for (AVA a : r.avas()) {
126                 if (a.getObjectIdentifier().equals((Object) PKCS9Attribute.EMAIL_ADDRESS_OID)) {
127                     SANs.add(new SubjectAlternateName(SANType.EMAIL, a.getValueString()));
128                 } else if (a.getObjectIdentifier().equals((Object) X500Name.commonName_oid)) {
129                     String value = a.getValueString();
130                     if (value.contains(".") && !value.contains(" ")) {
131                         SANs.add(new SubjectAlternateName(SANType.DNS, value));
132                     } else {
133                         name = value;
134                     }
135                 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
136                     // TODO? parse invalid SANs
137                 }
138             }
139         }
140
141         for (PKCS10Attribute b : atts.getAttributes()) {
142
143             if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
144                 // unknown attrib
145                 continue;
146             }
147
148             for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
149                 if (c instanceof SubjectAlternativeNameExtension) {
150
151                     SubjectAlternativeNameExtension san = (SubjectAlternativeNameExtension) c;
152                     GeneralNames obj = san.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
153                     for (int i = 0; i < obj.size(); i++) {
154                         GeneralName generalName = obj.get(i);
155                         GeneralNameInterface peeled = generalName.getName();
156                         if (peeled instanceof DNSName) {
157                             SANs.add(new SubjectAlternateName(SANType.DNS, ((DNSName) peeled).getName()));
158                         } else if (peeled instanceof RFC822Name) {
159                             SANs.add(new SubjectAlternateName(SANType.EMAIL, ((RFC822Name) peeled).getName()));
160                         }
161                     }
162                 } else if (c instanceof ExtendedKeyUsageExtension) {
163                     ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
164                     String appendix = "";
165                     if (ctx.getActor().getVerificationPoints() >= 50) {
166                         appendix = "-a";
167                     }
168                     for (String s : ekue.getExtendedKeyUsage()) {
169                         if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
170                             // server
171                             profile = CertificateProfile.getByName("server" + appendix);
172                         } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
173                             // client
174                             profile = CertificateProfile.getByName("client" + appendix);
175                         } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
176                             // code sign
177                         } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
178                             // emailProtection
179                             profile = CertificateProfile.getByName("mail" + appendix);
180                         } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
181                             // timestamp
182                         } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
183                             // OCSP
184                         }
185                     }
186                 } else {
187                     // Unknown requested extension
188                 }
189             }
190
191         }
192         this.SANs = SANs;
193         pk = parsed.getSubjectPublicKeyInfo();
194         KeyCheck.checkKey(pk);
195
196         String sign = getSignatureAlgorithm(data);
197         guessDigest(sign);
198
199         this.csr = csr;
200         this.csrType = CSRType.CSR;
201     }
202
203     public CertificateRequest(AuthorizationContext ctx, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
204         this.ctx = ctx;
205         String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
206         byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
207         SPKAC parsed = new SPKAC(data);
208         if ( !parsed.getChallenge().equals(spkacChallenge)) {
209             throw new GigiApiException("Challenge mismatch");
210         }
211         pk = parsed.getPubkey();
212         KeyCheck.checkKey(pk);
213
214         String sign = getSignatureAlgorithm(data);
215         guessDigest(sign);
216         this.SANs = new HashSet<>();
217         this.csr = "SPKAC=" + cleanedSPKAC;
218         this.csrType = CSRType.SPKAC;
219     }
220
221     private static String getSignatureAlgorithm(byte[] data) throws IOException {
222         DerInputStream in = new DerInputStream(data);
223         DerValue[] seq = in.getSequence(3);
224         return AlgorithmId.parse(seq[1]).getName();
225     }
226
227     private void guessDigest(String sign) {
228         if (sign.toLowerCase().startsWith("sha512")) {
229             selectedDigest = Digest.SHA512;
230         } else if (sign.toLowerCase().startsWith("sha384")) {
231             selectedDigest = Digest.SHA384;
232         } else if (sign.toLowerCase().startsWith("sha256")) {
233             selectedDigest = Digest.SHA256;
234         }
235     }
236
237     public void checkKeyStrength(PrintWriter out) {
238         out.println("Type: " + pk.getAlgorithm() + "<br/>");
239         if (pk instanceof RSAPublicKey) {
240             out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
241             out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
242         } else if (pk instanceof DSAPublicKey) {
243             DSAPublicKey dpk = (DSAPublicKey) pk;
244             out.println("Length: " + dpk.getY().bitLength() + "<br/>");
245             out.println(dpk.getParams());
246         } else if (pk instanceof ECPublicKey) {
247             ECPublicKey epk = (ECPublicKey) pk;
248             out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
249             out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
250             out.println(epk.getParams().getCurve());
251         }
252     }
253
254     private Set<SubjectAlternateName> parseSANBox(String SANs) {
255         String[] SANparts = SANs.split("[\r\n]+|, *");
256         Set<SubjectAlternateName> parsedNames = new LinkedHashSet<>();
257         for (String SANline : SANparts) {
258             String[] parts = SANline.split(":", 2);
259             if (parts.length == 1) {
260                 if (parts[0].trim().equals("")) {
261                     continue;
262                 }
263                 if (parts[0].contains("@")) {
264                     parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
265                 } else {
266                     parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
267                 }
268                 continue;
269             }
270             try {
271                 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase().trim());
272                 if (t == null) {
273                     continue;
274                 }
275                 parsedNames.add(new SubjectAlternateName(t, parts[1].trim()));
276             } catch (IllegalArgumentException e) {
277                 // invalid enum type
278                 continue;
279             }
280         }
281         return parsedNames;
282     }
283
284     public Set<SubjectAlternateName> getSANs() {
285         return SANs;
286     }
287
288     public String getName() {
289         return name;
290     }
291
292     public synchronized String getOu() {
293         if (ctx.getTarget() instanceof Organisation) {
294             return ou;
295         }
296         throw new IllegalStateException();
297     }
298
299     public Digest getSelectedDigest() {
300         return selectedDigest;
301     }
302
303     public CertificateProfile getProfile() {
304         return profile;
305     }
306
307     public synchronized boolean update(String nameIn, String hashAlg, String profileStr, String newOrgStr, String ou, String SANsStr) throws GigiApiException {
308         GigiApiException error = new GigiApiException();
309         this.name = nameIn;
310         if (hashAlg != null) {
311             selectedDigest = Digest.valueOf(hashAlg);
312         }
313         this.profile = CertificateProfile.getByName(profileStr);
314         if (ctx.getTarget() instanceof Organisation) {
315             this.ou = ou;
316         }
317
318         if ( !this.profile.canBeIssuedBy(ctx.getTarget(), ctx.getActor())) {
319             this.profile = CertificateProfile.getById(1);
320             error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
321             throw error;
322         }
323
324         verifySANs(error, profile, parseSANBox(SANsStr), ctx.getTarget(), ctx.getActor());
325
326         if ( !error.isEmpty()) {
327             throw error;
328         }
329         return true;
330     }
331
332     private void verifySANs(GigiApiException error, CertificateProfile p, Set<SubjectAlternateName> sANs2, CertificateOwner owner, User user) {
333         Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
334         PropertyTemplate domainTemp = p.getTemplates().get("domain");
335         PropertyTemplate emailTemp = p.getTemplates().get("email");
336         pDNS = null;
337         pMail = null;
338         for (SubjectAlternateName san : sANs2) {
339             if (san.getType() == SANType.DNS) {
340                 if (domainTemp != null && owner.isValidDomain(san.getName())) {
341                     boolean valid;
342                     try {
343                         DomainAssessment.checkCertifiableDomain(san.getName(), user.isInGroup(Group.CODESIGNING), false);
344                         valid = true;
345                         if ( !valid || !CAA.verifyDomainAccess(owner, p, san.getName()) || (pDNS != null && !domainTemp.isMultiple())) {
346                             // remove
347                         } else {
348                             if (pDNS == null) {
349                                 pDNS = san.getName();
350                             }
351                             filteredSANs.add(san);
352                             continue;
353                         }
354                     } catch (GigiApiException e) {
355                         error.mergeInto(e);
356                         valid = false;
357                     }
358                 }
359             } else if (san.getType() == SANType.EMAIL) {
360                 if (emailTemp != null && owner.isValidEmail(san.getName())) {
361                     if (pMail != null && !emailTemp.isMultiple()) {
362                         // remove
363                     } else {
364                         if (pMail == null) {
365                             pMail = san.getName();
366                         }
367                         filteredSANs.add(san);
368                         continue;
369                     }
370                 }
371             }
372             error.mergeInto(new GigiApiException(SprintfCommand.createSimple(//
373                     "The requested subject alternate name (SAN) \"{0}\" has been removed.", san.getType().toString().toLowerCase() + ":" + san.getName())));
374         }
375         SANs = filteredSANs;
376     }
377
378     // domain email name name=WoTUser orga
379     public synchronized Certificate draft() throws GigiApiException {
380
381         GigiApiException error = new GigiApiException();
382
383         HashMap<String, String> subject = new HashMap<>();
384         PropertyTemplate domainTemp = profile.getTemplates().get("domain");
385         PropertyTemplate emailTemp = profile.getTemplates().get("email");
386         PropertyTemplate nameTemp = profile.getTemplates().get("name");
387         PropertyTemplate wotUserTemp = profile.getTemplates().get("name=WoTUser");
388         verifySANs(error, profile, SANs, ctx.getTarget(), ctx.getActor());
389
390         // Ok, let's determine the CN
391         // the CN is
392         // 1. the user's "real name", iff the real name is to be included i.e.
393         // not empty (name), or to be forced to WOTUser
394
395         // 2. the user's "primary domain", iff "1." doesn't match and there is a
396         // primary domain. (domainTemp != null)
397
398         String verifiedCN = null;
399         if (ctx.getTarget() instanceof Organisation) {
400             if ( !name.equals("")) {
401                 verifiedCN = name;
402             }
403         } else {
404             verifiedCN = verifyName(error, nameTemp, wotUserTemp, verifiedCN);
405         }
406         if (pDNS == null && domainTemp != null && domainTemp.isRequired()) {
407             error.mergeInto(new GigiApiException("Server Certificates require a DNS name."));
408         } else if (domainTemp != null && verifiedCN == null) {
409             // user may add domains
410             verifiedCN = pDNS;
411         }
412         if (verifiedCN != null) {
413             subject.put("CN", verifiedCN);
414         }
415
416         if (pMail != null) {
417             if (emailTemp != null) {
418                 subject.put("EMAIL", pMail);
419             } else {
420                 // verify SANs should prevent this
421                 pMail = null;
422                 error.mergeInto(new GigiApiException("You may not include an email in this certificate."));
423             }
424         } else {
425             if (emailTemp != null && emailTemp.isRequired()) {
426                 error.mergeInto(new GigiApiException("You need to include an email in this certificate."));
427             }
428         }
429
430         if (ctx.getTarget() instanceof Organisation) {
431             Organisation org = (Organisation) ctx.getTarget();
432             subject.put("O", org.getName());
433             subject.put("C", org.getCountry().getCode());
434             subject.put("ST", org.getProvince());
435             subject.put("L", org.getCity());
436             if (ou != null) {
437                 subject.put("OU", ou);
438             }
439         }
440         System.out.println(subject);
441         if ( !error.isEmpty()) {
442             throw error;
443         }
444         try {
445             if (RATE_LIMIT.isLimitExceeded(Integer.toString(ctx.getActor().getId()))) {
446                 throw new GigiApiException("Rate Limit Exceeded");
447             }
448             return new Certificate(ctx.getTarget(), ctx.getActor(), subject, selectedDigest, //
449                     this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
450         } catch (IOException e) {
451             e.printStackTrace();
452         }
453         return null;
454     }
455
456     // 100 per 10 minutes
457     public static final RateLimit RATE_LIMIT = new RateLimit(100, 10 * 60 * 1000);
458
459     private String verifyName(GigiApiException error, PropertyTemplate nameTemp, PropertyTemplate wotUserTemp, String verifiedCN) {
460         // real names,
461         // possible configurations: name {y,null,?}, name=WoTUser {y,null}
462         // semantics:
463         // y * -> real
464         // null y -> default
465         // null null -> null
466         // ? y -> real, default
467         // ? null -> real, default, null
468         boolean realIsOK = false;
469         boolean nullIsOK = false;
470         boolean defaultIsOK = false;
471         if (wotUserTemp != null && ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple())) {
472             error.mergeInto(new GigiApiException("Internal configuration error detected."));
473         }
474         if (nameTemp != null && nameTemp.isRequired() && !nameTemp.isMultiple()) {
475             realIsOK = true;
476         } else if (nameTemp == null) {
477             defaultIsOK = wotUserTemp != null;
478             nullIsOK = !defaultIsOK;
479         } else if (nameTemp != null && !nameTemp.isRequired() && !nameTemp.isMultiple()) {
480             realIsOK = true;
481             defaultIsOK = true;
482             nullIsOK = wotUserTemp == null;
483         } else {
484             error.mergeInto(new GigiApiException("Internal configuration error detected."));
485         }
486         if (ctx.getTarget() instanceof User) {
487             User u = (User) ctx.getTarget();
488             if (name != null && u.isValidName(name)) {
489                 if (realIsOK) {
490                     verifiedCN = name;
491                 } else {
492                     error.mergeInto(new GigiApiException("Your real name is not allowed in this certificate."));
493                     if (defaultIsOK) {
494                         name = DEFAULT_CN;
495                     } else if (nullIsOK) {
496                         name = "";
497                     }
498                 }
499             } else if (name != null && name.equals(DEFAULT_CN)) {
500                 if (defaultIsOK) {
501                     verifiedCN = name;
502                 } else {
503                     error.mergeInto(new GigiApiException("The default name is not allowed in this certificate."));
504                     if (nullIsOK) {
505                         name = "";
506                     } else if (realIsOK) {
507                         name = u.getPreferredName().toString();
508                     }
509                 }
510             } else if (name == null || name.equals("")) {
511                 if (nullIsOK) {
512                     verifiedCN = "";
513                 } else {
514                     error.mergeInto(new GigiApiException("A name is required in this certificate."));
515                     if (defaultIsOK) {
516                         name = DEFAULT_CN;
517                     } else if (realIsOK) {
518                         name = u.getPreferredName().toString();
519                     }
520                 }
521             } else {
522                 error.mergeInto(new GigiApiException("The name you entered was invalid."));
523
524             }
525             if (wotUserTemp != null) {
526                 if ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple()) {
527                     error.mergeInto(new GigiApiException("Internal configuration error detected."));
528                 }
529                 if ( !name.equals(DEFAULT_CN)) {
530                     name = DEFAULT_CN;
531                     error.mergeInto(new GigiApiException("You may not change the name for this certificate type."));
532                 } else {
533                     verifiedCN = DEFAULT_CN;
534                 }
535
536             } else {
537                 if (nameTemp != null) {
538                     if (name.equals("")) {
539                         if (nameTemp.isRequired()) {
540                             // nothing, but required
541                             name = DEFAULT_CN;
542                             error.mergeInto(new GigiApiException("No name entered, but one was required."));
543                         } else {
544                             // nothing and not required
545
546                         }
547                     } else if (u.isValidName(name)) {
548                         verifiedCN = name;
549                     } else {
550                         if (nameTemp.isRequired()) {
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, because a name is required for this certificate type."));
552                         } else if (name.equals(DEFAULT_CN)) {
553                             verifiedCN = DEFAULT_CN;
554                         } else {
555                             name = DEFAULT_CN;
556                             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."));
557                         }
558                     }
559                 } else {
560                     if ( !name.equals("")) {
561                         name = "";
562                         error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
563                     }
564                 }
565             }
566         } else {
567             if (realIsOK) {
568                 verifiedCN = name;
569             } else {
570                 verifiedCN = "";
571                 name = "";
572                 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
573             }
574         }
575
576         return verifiedCN;
577     }
578 }