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