]> WPIA git - gigi.git/blob - src/org/cacert/gigi/pages/account/certs/CertificateRequest.java
aafd869c9b6274ab8261f47988e43a1f1952a6a6
[gigi.git] / src / org / cacert / gigi / pages / account / certs / CertificateRequest.java
1 package org.cacert.gigi.pages.account.certs;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.security.GeneralSecurityException;
6 import java.security.PublicKey;
7 import java.security.interfaces.DSAPublicKey;
8 import java.security.interfaces.ECPublicKey;
9 import java.security.interfaces.RSAPublicKey;
10 import java.util.Base64;
11 import java.util.HashMap;
12 import java.util.HashSet;
13 import java.util.LinkedHashSet;
14 import java.util.Set;
15 import java.util.TreeSet;
16
17 import javax.servlet.http.HttpServletRequest;
18
19 import org.cacert.gigi.GigiApiException;
20 import org.cacert.gigi.crypto.SPKAC;
21 import org.cacert.gigi.dbObjects.Certificate;
22 import org.cacert.gigi.dbObjects.Certificate.CSRType;
23 import org.cacert.gigi.dbObjects.Certificate.SANType;
24 import org.cacert.gigi.dbObjects.Certificate.SubjectAlternateName;
25 import org.cacert.gigi.dbObjects.CertificateOwner;
26 import org.cacert.gigi.dbObjects.CertificateProfile;
27 import org.cacert.gigi.dbObjects.CertificateProfile.PropertyTemplate;
28 import org.cacert.gigi.dbObjects.Digest;
29 import org.cacert.gigi.dbObjects.Organisation;
30 import org.cacert.gigi.dbObjects.User;
31 import org.cacert.gigi.output.template.SprintfCommand;
32 import org.cacert.gigi.util.AuthorizationContext;
33 import org.cacert.gigi.util.PEM;
34 import org.cacert.gigi.util.RateLimit;
35
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 = "CAcert WoT 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         }
228     }
229
230     public void checkKeyStrength(PrintWriter out) {
231         out.println("Type: " + pk.getAlgorithm() + "<br/>");
232         if (pk instanceof RSAPublicKey) {
233             out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
234             out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
235         } else if (pk instanceof DSAPublicKey) {
236             DSAPublicKey dpk = (DSAPublicKey) pk;
237             out.println("Length: " + dpk.getY().bitLength() + "<br/>");
238             out.println(dpk.getParams());
239         } else if (pk instanceof ECPublicKey) {
240             ECPublicKey epk = (ECPublicKey) pk;
241             out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
242             out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
243             out.println(epk.getParams().getCurve());
244         }
245     }
246
247     private Set<SubjectAlternateName> parseSANBox(String SANs) {
248         String[] SANparts = SANs.split("[\r\n]+|, *");
249         Set<SubjectAlternateName> parsedNames = new LinkedHashSet<>();
250         for (String SANline : SANparts) {
251             String[] parts = SANline.split(":", 2);
252             if (parts.length == 1) {
253                 if (parts[0].trim().equals("")) {
254                     continue;
255                 }
256                 if (parts[0].contains("@")) {
257                     parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
258                 } else {
259                     parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
260                 }
261                 continue;
262             }
263             try {
264                 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase().trim());
265                 if (t == null) {
266                     continue;
267                 }
268                 parsedNames.add(new SubjectAlternateName(t, parts[1].trim()));
269             } catch (IllegalArgumentException e) {
270                 // invalid enum type
271                 continue;
272             }
273         }
274         return parsedNames;
275     }
276
277     public Set<SubjectAlternateName> getSANs() {
278         return SANs;
279     }
280
281     public String getName() {
282         return name;
283     }
284
285     public synchronized String getOu() {
286         if (ctx.getTarget() instanceof Organisation) {
287             return ou;
288         }
289         throw new IllegalStateException();
290     }
291
292     public Digest getSelectedDigest() {
293         return selectedDigest;
294     }
295
296     public CertificateProfile getProfile() {
297         return profile;
298     }
299
300     public synchronized boolean update(String nameIn, String hashAlg, String profileStr, String newOrgStr, String ou, String SANsStr, PrintWriter out, HttpServletRequest req) throws GigiApiException {
301         GigiApiException error = new GigiApiException();
302         this.name = nameIn;
303         if (hashAlg != null) {
304             selectedDigest = Digest.valueOf(hashAlg);
305         }
306         this.profile = CertificateProfile.getByName(profileStr);
307         if (ctx.getTarget() instanceof Organisation) {
308             this.ou = ou;
309         }
310
311         if ( !this.profile.canBeIssuedBy(ctx.getTarget(), ctx.getActor())) {
312             this.profile = CertificateProfile.getById(1);
313             error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
314             throw error;
315         }
316
317         verifySANs(error, profile, parseSANBox(SANsStr), ctx.getTarget());
318
319         if ( !error.isEmpty()) {
320             throw error;
321         }
322         return true;
323     }
324
325     private void verifySANs(GigiApiException error, CertificateProfile p, Set<SubjectAlternateName> sANs2, CertificateOwner owner) {
326         Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
327         PropertyTemplate domainTemp = p.getTemplates().get("domain");
328         PropertyTemplate emailTemp = p.getTemplates().get("email");
329         pDNS = null;
330         pMail = null;
331         for (SubjectAlternateName san : sANs2) {
332             if (san.getType() == SANType.DNS) {
333                 if (domainTemp != null && owner.isValidDomain(san.getName())) {
334                     if (pDNS != null && !domainTemp.isMultiple()) {
335                         // remove
336                     } else {
337                         if (pDNS == null) {
338                             pDNS = san.getName();
339                         }
340                         filteredSANs.add(san);
341                         continue;
342                     }
343                 }
344             } else if (san.getType() == SANType.EMAIL) {
345                 if (emailTemp != null && owner.isValidEmail(san.getName())) {
346                     if (pMail != null && !emailTemp.isMultiple()) {
347                         // remove
348                     } else {
349                         if (pMail == null) {
350                             pMail = san.getName();
351                         }
352                         filteredSANs.add(san);
353                         continue;
354                     }
355                 }
356             }
357             error.mergeInto(new GigiApiException(SprintfCommand.createSimple(//
358                     "The requested Subject alternate name \"{0}\" has been removed.", san.getType().toString().toLowerCase() + ":" + san.getName())));
359         }
360         SANs = filteredSANs;
361     }
362
363     // domain email name name=WoTUser orga
364     public synchronized Certificate draft() throws GigiApiException {
365
366         GigiApiException error = new GigiApiException();
367
368         HashMap<String, String> subject = new HashMap<>();
369         PropertyTemplate domainTemp = profile.getTemplates().get("domain");
370         PropertyTemplate emailTemp = profile.getTemplates().get("email");
371         PropertyTemplate nameTemp = profile.getTemplates().get("name");
372         PropertyTemplate wotUserTemp = profile.getTemplates().get("name=WoTUser");
373         verifySANs(error, profile, SANs, ctx.getTarget());
374
375         // Ok, let's determine the CN
376         // the CN is
377         // 1. the user's "real name", iff the real name is to be included i.e.
378         // not empty (name), or to be forced to WOTUser
379
380         // 2. the user's "primary domain", iff "1." doesn't match and there is a
381         // primary domain. (domainTemp != null)
382
383         String verifiedCN = null;
384         if (ctx.getTarget() instanceof Organisation) {
385             if ( !name.equals("")) {
386                 verifiedCN = name;
387             }
388         } else {
389             verifiedCN = verifyName(error, nameTemp, wotUserTemp, verifiedCN);
390         }
391         if (pDNS == null && domainTemp != null && domainTemp.isRequired()) {
392             error.mergeInto(new GigiApiException("Server Certificates require a DNS name."));
393         } else if (domainTemp != null && verifiedCN == null) {
394             // user may add domains
395             verifiedCN = pDNS;
396         }
397         if (verifiedCN != null) {
398             subject.put("CN", verifiedCN);
399         }
400
401         if (pMail != null) {
402             if (emailTemp != null) {
403                 subject.put("EMAIL", pMail);
404             } else {
405                 // verify SANs should prevent this
406                 pMail = null;
407                 error.mergeInto(new GigiApiException("You may not include an email in this certificate."));
408             }
409         } else {
410             if (emailTemp != null && emailTemp.isRequired()) {
411                 error.mergeInto(new GigiApiException("You need to include an email in this certificate."));
412             }
413         }
414
415         if (ctx.getTarget() instanceof Organisation) {
416             Organisation org = (Organisation) ctx.getTarget();
417             subject.put("O", org.getName());
418             subject.put("C", org.getState());
419             subject.put("ST", org.getProvince());
420             subject.put("L", org.getCity());
421             if (ou != null) {
422                 subject.put("OU", ou);
423             }
424         }
425         System.out.println(subject);
426         if ( !error.isEmpty()) {
427             throw error;
428         }
429         try {
430             if (RATE_LIMIT.isLimitExceeded(Integer.toString(ctx.getActor().getId()))) {
431                 throw new GigiApiException("Rate Limit Exceeded");
432             }
433             return new Certificate(ctx.getTarget(), ctx.getActor(), subject, selectedDigest, //
434                     this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
435         } catch (IOException e) {
436             e.printStackTrace();
437         }
438         return null;
439     }
440
441     // 100 per 10 minutes
442     public static final RateLimit RATE_LIMIT = new RateLimit(100, 10 * 60 * 1000);
443
444     private String verifyName(GigiApiException error, PropertyTemplate nameTemp, PropertyTemplate wotUserTemp, String verifiedCN) {
445         // real names,
446         // possible configurations: name {y,null,?}, name=WoTUser {y,null}
447         // semantics:
448         // y * -> real
449         // null y -> default
450         // null null -> null
451         // ? y -> real, default
452         // ? null -> real, default, null
453         boolean realIsOK = false;
454         boolean nullIsOK = false;
455         boolean defaultIsOK = false;
456         if (wotUserTemp != null && ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple())) {
457             error.mergeInto(new GigiApiException("Internal configuration error detected."));
458         }
459         if (nameTemp != null && nameTemp.isRequired() && !nameTemp.isMultiple()) {
460             realIsOK = true;
461         } else if (nameTemp == null) {
462             defaultIsOK = wotUserTemp != null;
463             nullIsOK = !defaultIsOK;
464         } else if (nameTemp != null && !nameTemp.isRequired() && !nameTemp.isMultiple()) {
465             realIsOK = true;
466             defaultIsOK = true;
467             nullIsOK = wotUserTemp == null;
468         } else {
469             error.mergeInto(new GigiApiException("Internal configuration error detected."));
470         }
471         if (ctx.getTarget() instanceof User) {
472             User u = (User) ctx.getTarget();
473             if (name != null && u.isValidName(name)) {
474                 if (realIsOK) {
475                     verifiedCN = name;
476                 } else {
477                     error.mergeInto(new GigiApiException("Your real name is not allowed in this certificate."));
478                     if (defaultIsOK) {
479                         name = DEFAULT_CN;
480                     } else if (nullIsOK) {
481                         name = "";
482                     }
483                 }
484             } else if (name != null && name.equals(DEFAULT_CN)) {
485                 if (defaultIsOK) {
486                     verifiedCN = name;
487                 } else {
488                     error.mergeInto(new GigiApiException("The default name is not allowed in this certificate."));
489                     if (nullIsOK) {
490                         name = "";
491                     } else if (realIsOK) {
492                         name = u.getName().toString();
493                     }
494                 }
495             } else if (name == null || name.equals("")) {
496                 if (nullIsOK) {
497                     verifiedCN = "";
498                 } else {
499                     error.mergeInto(new GigiApiException("A name is required in this certificate."));
500                     if (defaultIsOK) {
501                         name = DEFAULT_CN;
502                     } else if (realIsOK) {
503                         name = u.getName().toString();
504                     }
505                 }
506             } else {
507                 error.mergeInto(new GigiApiException("The name you entered was invalid."));
508
509             }
510             if (wotUserTemp != null) {
511                 if ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple()) {
512                     error.mergeInto(new GigiApiException("Internal configuration error detected."));
513                 }
514                 if ( !name.equals(DEFAULT_CN)) {
515                     name = DEFAULT_CN;
516                     error.mergeInto(new GigiApiException("You may not change the name for this certificate type."));
517                 } else {
518                     verifiedCN = DEFAULT_CN;
519                 }
520
521             } else {
522                 if (nameTemp != null) {
523                     if (name.equals("")) {
524                         if (nameTemp.isRequired()) {
525                             // nothing, but required
526                             name = DEFAULT_CN;
527                             error.mergeInto(new GigiApiException("No name entered, but one was required."));
528                         } else {
529                             // nothing and not required
530
531                         }
532                     } else if (u.isValidName(name)) {
533                         verifiedCN = name;
534                     } else {
535                         if (nameTemp.isRequired()) {
536                             error.mergeInto(new GigiApiException("The name entered, does not match the details in your account. You cannot issue certificates with this name. Enter a name that matches the one that has been assured in your account, because a name is required for this certificate type."));
537                         } else if (name.equals(DEFAULT_CN)) {
538                             verifiedCN = DEFAULT_CN;
539                         } else {
540                             name = DEFAULT_CN;
541                             error.mergeInto(new GigiApiException("The name entered, does not match the details in your account. You cannot issue certificates with this name. Enter a name that matches the one that has been assured in your account or keep the default name."));
542                         }
543                     }
544                 } else {
545                     if ( !name.equals("")) {
546                         name = "";
547                         error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
548                     }
549                 }
550             }
551         } else {
552             if (realIsOK) {
553                 verifiedCN = name;
554             } else {
555                 verifiedCN = "";
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         return verifiedCN;
562     }
563 }