]> WPIA git - gigi.git/blob - src/org/cacert/gigi/pages/account/certs/CertificateRequest.java
eb547cd3a22c915e94bbfeb86bd2a52eb344cde3
[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.PEM;
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 Organisation org = null;
103
104     private User u;
105
106     private String pDNS, pMail;
107
108     public CertificateRequest(User issuer, String csr) throws IOException, GeneralSecurityException, GigiApiException {
109         this(issuer, csr, (CertificateProfile) null);
110     }
111
112     public CertificateRequest(User issuer, String csr, CertificateProfile cp) throws GeneralSecurityException, IOException, IOException {
113         u = issuer;
114         if (cp != null) {
115             profile = cp;
116         } else if (u.getAssurancePoints() > 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 (u.getAssurancePoints() >= 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         String sign = getSignatureAlgorithm(data);
195         guessDigest(sign);
196
197         this.csr = csr;
198         this.csrType = CSRType.CSR;
199     }
200
201     public CertificateRequest(User issuer, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
202         u = issuer;
203         String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
204         byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
205         SPKAC parsed = new SPKAC(data);
206         if ( !parsed.getChallenge().equals(spkacChallenge)) {
207             throw new GigiApiException("Challenge mismatch");
208         }
209         pk = parsed.getPubkey();
210         String sign = getSignatureAlgorithm(data);
211         guessDigest(sign);
212         this.SANs = new HashSet<>();
213         this.csr = "SPKAC=" + cleanedSPKAC;
214         this.csrType = CSRType.SPKAC;
215
216     }
217
218     private static String getSignatureAlgorithm(byte[] data) throws IOException {
219         DerInputStream in = new DerInputStream(data);
220         DerValue[] seq = in.getSequence(3);
221         return AlgorithmId.parse(seq[1]).getName();
222     }
223
224     private void guessDigest(String sign) {
225         if (sign.toLowerCase().startsWith("sha512")) {
226             selectedDigest = Digest.SHA512;
227         } else if (sign.toLowerCase().startsWith("sha384")) {
228             selectedDigest = Digest.SHA384;
229         }
230     }
231
232     public void checkKeyStrength(PrintWriter out) {
233         out.println("Type: " + pk.getAlgorithm() + "<br/>");
234         if (pk instanceof RSAPublicKey) {
235             out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
236             out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
237         } else if (pk instanceof DSAPublicKey) {
238             DSAPublicKey dpk = (DSAPublicKey) pk;
239             out.println("Length: " + dpk.getY().bitLength() + "<br/>");
240             out.println(dpk.getParams());
241         } else if (pk instanceof ECPublicKey) {
242             ECPublicKey epk = (ECPublicKey) pk;
243             out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
244             out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
245             out.println(epk.getParams().getCurve());
246         }
247     }
248
249     private Set<SubjectAlternateName> parseSANBox(String SANs) {
250         String[] SANparts = SANs.split("[\r\n]+|, *");
251         Set<SubjectAlternateName> parsedNames = new LinkedHashSet<>();
252         for (String SANline : SANparts) {
253             String[] parts = SANline.split(":", 2);
254             if (parts.length == 1) {
255                 if (parts[0].trim().equals("")) {
256                     continue;
257                 }
258                 if (parts[0].contains("@")) {
259                     parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
260                 } else {
261                     parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
262                 }
263                 continue;
264             }
265             try {
266                 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase().trim());
267                 if (t == null) {
268                     continue;
269                 }
270                 parsedNames.add(new SubjectAlternateName(t, parts[1].trim()));
271             } catch (IllegalArgumentException e) {
272                 // invalid enum type
273                 continue;
274             }
275         }
276         return parsedNames;
277     }
278
279     public Set<SubjectAlternateName> getSANs() {
280         return SANs;
281     }
282
283     public String getName() {
284         return name;
285     }
286
287     public Organisation getOrg() {
288         return org;
289     }
290
291     public String getOu() {
292         return ou;
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, PrintWriter out, HttpServletRequest req) 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 (newOrgStr != null) {
311             Organisation neworg = Organisation.getById(Integer.parseInt(newOrgStr));
312             if (neworg == null || u.getOrganisations().contains(neworg)) {
313                 PropertyTemplate orga = profile.getTemplates().get("orga");
314                 if (orga != null) {
315                     org = neworg;
316                 } else {
317                     org = null;
318                     error.mergeInto(new GigiApiException("No organisations for this certificate profile."));
319                 }
320             } else {
321                 error.mergeInto(new GigiApiException("Selected organisation is not part of your account."));
322             }
323         }
324
325         this.ou = ou;
326
327         if ( !this.profile.canBeIssuedBy(u)) {
328             this.profile = CertificateProfile.getById(1);
329             error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
330             throw error;
331         }
332
333         CertificateOwner owner = org != null ? org : u;
334
335         verifySANs(error, profile, parseSANBox(SANsStr), owner);
336
337         if ( !error.isEmpty()) {
338             throw error;
339         }
340         return true;
341     }
342
343     private void verifySANs(GigiApiException error, CertificateProfile p, Set<SubjectAlternateName> sANs2, CertificateOwner owner) {
344         Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
345         PropertyTemplate domainTemp = p.getTemplates().get("domain");
346         PropertyTemplate emailTemp = p.getTemplates().get("email");
347         pDNS = null;
348         pMail = null;
349         for (SubjectAlternateName san : sANs2) {
350             if (san.getType() == SANType.DNS) {
351                 if (domainTemp != null && owner.isValidDomain(san.getName())) {
352                     if (pDNS != null && !domainTemp.isMultiple()) {
353                         // remove
354                     } else {
355                         if (pDNS == null) {
356                             pDNS = san.getName();
357                         }
358                         filteredSANs.add(san);
359                         continue;
360                     }
361                 }
362             } else if (san.getType() == SANType.EMAIL) {
363                 if (emailTemp != null && owner.isValidEmail(san.getName())) {
364                     if (pMail != null && !emailTemp.isMultiple()) {
365                         // remove
366                     } else {
367                         if (pMail == null) {
368                             pMail = san.getName();
369                         }
370                         filteredSANs.add(san);
371                         continue;
372                     }
373                 }
374             }
375             HashMap<String, Object> vars = new HashMap<>();
376             vars.put("SAN", san.getType().toString().toLowerCase() + ":" + san.getName());
377             error.mergeInto(new GigiApiException(new Scope(new SprintfCommand(//
378                     "The requested Subject alternate name \"{0}\" has been removed.", Arrays.asList("${SAN}")), vars)));
379         }
380         SANs = filteredSANs;
381     }
382
383     // domain email name name=WoTUser orga
384     public synchronized Certificate draft() throws GigiApiException {
385
386         GigiApiException error = new GigiApiException();
387
388         HashMap<String, String> subject = new HashMap<>();
389         PropertyTemplate domainTemp = profile.getTemplates().get("domain");
390         PropertyTemplate emailTemp = profile.getTemplates().get("email");
391         PropertyTemplate nameTemp = profile.getTemplates().get("name");
392         PropertyTemplate wotUserTemp = profile.getTemplates().get("name=WoTUser");
393         verifySANs(error, profile, SANs, org != null ? org : u);
394
395         // Ok, let's determine the CN
396         // the CN is
397         // 1. the user's "real name", iff the real name is to be included i.e.
398         // not empty (name), or to be forced to WOTUser
399
400         // 2. the user's "primary domain", iff "1." doesn't match and there is a
401         // primary domain. (domainTemp != null)
402
403         String verifiedCN = null;
404         if (org == null) {
405             verifiedCN = verifyName(error, nameTemp, wotUserTemp, verifiedCN);
406         } else {
407             if ( !name.equals("")) {
408                 verifiedCN = name;
409             }
410         }
411         if (pDNS == null && domainTemp != null && domainTemp.isRequired()) {
412             error.mergeInto(new GigiApiException("Server Certificates require a DNS name."));
413         } else if (domainTemp != null && verifiedCN == null) {
414             // user may add domains
415             verifiedCN = pDNS;
416         }
417         if (verifiedCN != null) {
418             subject.put("CN", verifiedCN);
419         }
420
421         if (pMail != null) {
422             if (emailTemp != null) {
423                 subject.put("EMAIL", pMail);
424             } else {
425                 // verify SANs should prevent this
426                 pMail = null;
427                 error.mergeInto(new GigiApiException("You may not include an email in this certificate."));
428             }
429         } else {
430             if (emailTemp != null && emailTemp.isRequired()) {
431                 error.mergeInto(new GigiApiException("You need to include an email in this certificate."));
432             }
433         }
434
435         if (org != null) {
436             subject.put("O", org.getName());
437             subject.put("C", org.getState());
438             subject.put("ST", org.getProvince());
439             subject.put("L", org.getCity());
440             if (ou != null) {
441                 subject.put("OU", ou);
442             }
443         }
444         System.out.println(subject);
445         if ( !error.isEmpty()) {
446             throw error;
447         }
448         try {
449             return new Certificate(u, subject, selectedDigest.toString(), //
450                     this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
451         } catch (IOException e) {
452             e.printStackTrace();
453         }
454         return null;
455     }
456
457     private String verifyName(GigiApiException error, PropertyTemplate nameTemp, PropertyTemplate wotUserTemp, String verifiedCN) {
458         // real names,
459         // possible configurations: name {y,null,?}, name=WoTUser {y,null}
460         // semantics:
461         // y * -> real
462         // null y -> default
463         // null null -> null
464         // ? y -> real, default
465         // ? null -> real, default, null
466         boolean realIsOK = false;
467         boolean nullIsOK = false;
468         boolean defaultIsOK = false;
469         if (wotUserTemp != null && ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple())) {
470             error.mergeInto(new GigiApiException("Internal configuration error detected."));
471         }
472         if (nameTemp != null && nameTemp.isRequired() && !nameTemp.isMultiple()) {
473             realIsOK = true;
474         } else if (nameTemp == null) {
475             defaultIsOK = wotUserTemp != null;
476             nullIsOK = !defaultIsOK;
477         } else if (nameTemp != null && !nameTemp.isRequired() && !nameTemp.isMultiple()) {
478             realIsOK = true;
479             defaultIsOK = true;
480             nullIsOK = wotUserTemp == null;
481         } else {
482             error.mergeInto(new GigiApiException("Internal configuration error detected."));
483         }
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.getName().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.getName().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 assured 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 assured 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         return verifiedCN;
563     }
564 }