1 package club.wpia.gigi.pages.account.certs;
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;
15 import java.util.TreeSet;
17 import club.wpia.gigi.GigiApiException;
18 import club.wpia.gigi.crypto.SPKAC;
19 import club.wpia.gigi.dbObjects.Certificate;
20 import club.wpia.gigi.dbObjects.CertificateOwner;
21 import club.wpia.gigi.dbObjects.CertificateProfile;
22 import club.wpia.gigi.dbObjects.Digest;
23 import club.wpia.gigi.dbObjects.Group;
24 import club.wpia.gigi.dbObjects.Organisation;
25 import club.wpia.gigi.dbObjects.User;
26 import club.wpia.gigi.dbObjects.Certificate.CSRType;
27 import club.wpia.gigi.dbObjects.Certificate.SANType;
28 import club.wpia.gigi.dbObjects.Certificate.SubjectAlternateName;
29 import club.wpia.gigi.dbObjects.CertificateProfile.PropertyTemplate;
30 import club.wpia.gigi.output.template.SprintfCommand;
31 import club.wpia.gigi.util.AuthorizationContext;
32 import club.wpia.gigi.util.CAA;
33 import club.wpia.gigi.util.DomainAssessment;
34 import club.wpia.gigi.util.PEM;
35 import club.wpia.gigi.util.RateLimit;
36 import 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;
58 public class CertificateRequest {
60 public static final String DEFAULT_CN = "SomeCA User";
62 public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
63 1, 3, 6, 1, 5, 5, 7, 3, 1
66 public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
67 1, 3, 6, 1, 5, 5, 7, 3, 2
70 public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
71 1, 3, 6, 1, 5, 5, 7, 3, 3
74 public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
75 1, 3, 6, 1, 5, 5, 7, 3, 4
78 public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
79 1, 3, 6, 1, 5, 5, 7, 3, 8
82 public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
83 1, 3, 6, 1, 5, 5, 7, 3, 9
86 private CSRType csrType;
88 private final PublicKey pk;
92 public String name = DEFAULT_CN;
94 private Set<SubjectAlternateName> SANs;
96 private Digest selectedDigest = Digest.getDefault();
98 private CertificateProfile profile = CertificateProfile.getById(1);
100 private String ou = "";
102 private AuthorizationContext ctx;
104 private String pDNS, pMail;
106 public CertificateRequest(AuthorizationContext c, String csr) throws IOException, GeneralSecurityException, GigiApiException {
107 this(c, csr, (CertificateProfile) null);
110 public CertificateRequest(AuthorizationContext ctx, String csr, CertificateProfile cp) throws GeneralSecurityException, IOException, IOException {
114 } else if (ctx.getActor().getAssurancePoints() > 50) {
115 profile = CertificateProfile.getByName("client-a");
117 byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
118 PKCS10 parsed = new PKCS10(data);
119 PKCS10Attributes atts = parsed.getAttributes();
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));
133 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
134 // TODO? parse invalid SANs
139 for (PKCS10Attribute b : atts.getAttributes()) {
141 if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
146 for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
147 if (c instanceof SubjectAlternativeNameExtension) {
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()));
160 } else if (c instanceof ExtendedKeyUsageExtension) {
161 ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
162 String appendix = "";
163 if (ctx.getActor().getAssurancePoints() >= 50) {
166 for (String s : ekue.getExtendedKeyUsage()) {
167 if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
169 profile = CertificateProfile.getByName("server" + appendix);
170 } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
172 profile = CertificateProfile.getByName("client" + appendix);
173 } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
175 } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
177 profile = CertificateProfile.getByName("mail" + appendix);
178 } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
180 } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
185 // Unknown requested extension
191 pk = parsed.getSubjectPublicKeyInfo();
192 String sign = getSignatureAlgorithm(data);
196 this.csrType = CSRType.CSR;
199 public CertificateRequest(AuthorizationContext ctx, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
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");
207 pk = parsed.getPubkey();
208 String sign = getSignatureAlgorithm(data);
210 this.SANs = new HashSet<>();
211 this.csr = "SPKAC=" + cleanedSPKAC;
212 this.csrType = CSRType.SPKAC;
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();
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 } else if (sign.toLowerCase().startsWith("sha256")) {
228 selectedDigest = Digest.SHA256;
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());
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("")) {
258 if (parts[0].contains("@")) {
259 parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
261 parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
266 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase().trim());
270 parsedNames.add(new SubjectAlternateName(t, parts[1].trim()));
271 } catch (IllegalArgumentException e) {
279 public Set<SubjectAlternateName> getSANs() {
283 public String getName() {
287 public synchronized String getOu() {
288 if (ctx.getTarget() instanceof Organisation) {
291 throw new IllegalStateException();
294 public Digest getSelectedDigest() {
295 return selectedDigest;
298 public CertificateProfile getProfile() {
302 public synchronized boolean update(String nameIn, String hashAlg, String profileStr, String newOrgStr, String ou, String SANsStr) throws GigiApiException {
303 GigiApiException error = new GigiApiException();
305 if (hashAlg != null) {
306 selectedDigest = Digest.valueOf(hashAlg);
308 this.profile = CertificateProfile.getByName(profileStr);
309 if (ctx.getTarget() instanceof Organisation) {
313 if ( !this.profile.canBeIssuedBy(ctx.getTarget(), ctx.getActor())) {
314 this.profile = CertificateProfile.getById(1);
315 error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
319 verifySANs(error, profile, parseSANBox(SANsStr), ctx.getTarget(), ctx.getActor());
321 if ( !error.isEmpty()) {
327 private void verifySANs(GigiApiException error, CertificateProfile p, Set<SubjectAlternateName> sANs2, CertificateOwner owner, User user) {
328 Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
329 PropertyTemplate domainTemp = p.getTemplates().get("domain");
330 PropertyTemplate emailTemp = p.getTemplates().get("email");
333 for (SubjectAlternateName san : sANs2) {
334 if (san.getType() == SANType.DNS) {
335 if (domainTemp != null && owner.isValidDomain(san.getName())) {
338 DomainAssessment.checkCertifiableDomain(san.getName(), user.isInGroup(Group.CODESIGNING), false);
340 if ( !valid || !CAA.verifyDomainAccess(owner, p, san.getName()) || (pDNS != null && !domainTemp.isMultiple())) {
344 pDNS = san.getName();
346 filteredSANs.add(san);
349 } catch (GigiApiException e) {
354 } else if (san.getType() == SANType.EMAIL) {
355 if (emailTemp != null && owner.isValidEmail(san.getName())) {
356 if (pMail != null && !emailTemp.isMultiple()) {
360 pMail = san.getName();
362 filteredSANs.add(san);
367 error.mergeInto(new GigiApiException(SprintfCommand.createSimple(//
368 "The requested subject alternate name (SAN) \"{0}\" has been removed.", san.getType().toString().toLowerCase() + ":" + san.getName())));
373 // domain email name name=WoTUser orga
374 public synchronized Certificate draft() throws GigiApiException {
376 GigiApiException error = new GigiApiException();
378 HashMap<String, String> subject = new HashMap<>();
379 PropertyTemplate domainTemp = profile.getTemplates().get("domain");
380 PropertyTemplate emailTemp = profile.getTemplates().get("email");
381 PropertyTemplate nameTemp = profile.getTemplates().get("name");
382 PropertyTemplate wotUserTemp = profile.getTemplates().get("name=WoTUser");
383 verifySANs(error, profile, SANs, ctx.getTarget(), ctx.getActor());
385 // Ok, let's determine the CN
387 // 1. the user's "real name", iff the real name is to be included i.e.
388 // not empty (name), or to be forced to WOTUser
390 // 2. the user's "primary domain", iff "1." doesn't match and there is a
391 // primary domain. (domainTemp != null)
393 String verifiedCN = null;
394 if (ctx.getTarget() instanceof Organisation) {
395 if ( !name.equals("")) {
399 verifiedCN = verifyName(error, nameTemp, wotUserTemp, verifiedCN);
401 if (pDNS == null && domainTemp != null && domainTemp.isRequired()) {
402 error.mergeInto(new GigiApiException("Server Certificates require a DNS name."));
403 } else if (domainTemp != null && verifiedCN == null) {
404 // user may add domains
407 if (verifiedCN != null) {
408 subject.put("CN", verifiedCN);
412 if (emailTemp != null) {
413 subject.put("EMAIL", pMail);
415 // verify SANs should prevent this
417 error.mergeInto(new GigiApiException("You may not include an email in this certificate."));
420 if (emailTemp != null && emailTemp.isRequired()) {
421 error.mergeInto(new GigiApiException("You need to include an email in this certificate."));
425 if (ctx.getTarget() instanceof Organisation) {
426 Organisation org = (Organisation) ctx.getTarget();
427 subject.put("O", org.getName());
428 subject.put("C", org.getCountry().getCode());
429 subject.put("ST", org.getProvince());
430 subject.put("L", org.getCity());
432 subject.put("OU", ou);
435 System.out.println(subject);
436 if ( !error.isEmpty()) {
440 if (RATE_LIMIT.isLimitExceeded(Integer.toString(ctx.getActor().getId()))) {
441 throw new GigiApiException("Rate Limit Exceeded");
443 return new Certificate(ctx.getTarget(), ctx.getActor(), subject, selectedDigest, //
444 this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
445 } catch (IOException e) {
451 // 100 per 10 minutes
452 public static final RateLimit RATE_LIMIT = new RateLimit(100, 10 * 60 * 1000);
454 private String verifyName(GigiApiException error, PropertyTemplate nameTemp, PropertyTemplate wotUserTemp, String verifiedCN) {
456 // possible configurations: name {y,null,?}, name=WoTUser {y,null}
461 // ? y -> real, default
462 // ? null -> real, default, null
463 boolean realIsOK = false;
464 boolean nullIsOK = false;
465 boolean defaultIsOK = false;
466 if (wotUserTemp != null && ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple())) {
467 error.mergeInto(new GigiApiException("Internal configuration error detected."));
469 if (nameTemp != null && nameTemp.isRequired() && !nameTemp.isMultiple()) {
471 } else if (nameTemp == null) {
472 defaultIsOK = wotUserTemp != null;
473 nullIsOK = !defaultIsOK;
474 } else if (nameTemp != null && !nameTemp.isRequired() && !nameTemp.isMultiple()) {
477 nullIsOK = wotUserTemp == null;
479 error.mergeInto(new GigiApiException("Internal configuration error detected."));
481 if (ctx.getTarget() instanceof User) {
482 User u = (User) ctx.getTarget();
483 if (name != null && u.isValidName(name)) {
487 error.mergeInto(new GigiApiException("Your real name is not allowed in this certificate."));
490 } else if (nullIsOK) {
494 } else if (name != null && name.equals(DEFAULT_CN)) {
498 error.mergeInto(new GigiApiException("The default name is not allowed in this certificate."));
501 } else if (realIsOK) {
502 name = u.getPreferredName().toString();
505 } else if (name == null || name.equals("")) {
509 error.mergeInto(new GigiApiException("A name is required in this certificate."));
512 } else if (realIsOK) {
513 name = u.getPreferredName().toString();
517 error.mergeInto(new GigiApiException("The name you entered was invalid."));
520 if (wotUserTemp != null) {
521 if ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple()) {
522 error.mergeInto(new GigiApiException("Internal configuration error detected."));
524 if ( !name.equals(DEFAULT_CN)) {
526 error.mergeInto(new GigiApiException("You may not change the name for this certificate type."));
528 verifiedCN = DEFAULT_CN;
532 if (nameTemp != null) {
533 if (name.equals("")) {
534 if (nameTemp.isRequired()) {
535 // nothing, but required
537 error.mergeInto(new GigiApiException("No name entered, but one was required."));
539 // nothing and not required
542 } else if (u.isValidName(name)) {
545 if (nameTemp.isRequired()) {
546 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."));
547 } else if (name.equals(DEFAULT_CN)) {
548 verifiedCN = DEFAULT_CN;
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 or keep the default name."));
555 if ( !name.equals("")) {
557 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
567 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));