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.crypto.key.KeyCheck;
20 import club.wpia.gigi.dbObjects.Certificate;
21 import club.wpia.gigi.dbObjects.Certificate.CSRType;
22 import club.wpia.gigi.dbObjects.Certificate.SANType;
23 import club.wpia.gigi.dbObjects.Certificate.SubjectAlternateName;
24 import club.wpia.gigi.dbObjects.CertificateOwner;
25 import club.wpia.gigi.dbObjects.CertificateProfile;
26 import club.wpia.gigi.dbObjects.CertificateProfile.PropertyTemplate;
27 import club.wpia.gigi.dbObjects.Digest;
28 import club.wpia.gigi.dbObjects.Group;
29 import club.wpia.gigi.dbObjects.Organisation;
30 import club.wpia.gigi.dbObjects.User;
31 import club.wpia.gigi.output.template.SprintfCommand;
32 import club.wpia.gigi.util.AuthorizationContext;
33 import club.wpia.gigi.util.CAA;
34 import club.wpia.gigi.util.DomainAssessment;
35 import club.wpia.gigi.util.PEM;
36 import club.wpia.gigi.util.RateLimit;
37 import club.wpia.gigi.util.ServerConstants;
38 import club.wpia.gigi.util.TimeConditions;
39 import sun.security.pkcs.PKCS9Attribute;
40 import sun.security.pkcs10.PKCS10;
41 import sun.security.pkcs10.PKCS10Attribute;
42 import sun.security.pkcs10.PKCS10Attributes;
43 import sun.security.util.DerInputStream;
44 import sun.security.util.DerValue;
45 import sun.security.util.ObjectIdentifier;
46 import sun.security.x509.AVA;
47 import sun.security.x509.AlgorithmId;
48 import sun.security.x509.CertificateExtensions;
49 import sun.security.x509.DNSName;
50 import sun.security.x509.ExtendedKeyUsageExtension;
51 import sun.security.x509.Extension;
52 import sun.security.x509.GeneralName;
53 import sun.security.x509.GeneralNameInterface;
54 import sun.security.x509.GeneralNames;
55 import sun.security.x509.PKIXExtensions;
56 import sun.security.x509.RDN;
57 import sun.security.x509.RFC822Name;
58 import sun.security.x509.SubjectAlternativeNameExtension;
59 import sun.security.x509.X500Name;
61 public class CertificateRequest {
63 public static final String DEFAULT_CN = ServerConstants.getAppName() + " User";
65 public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
66 1, 3, 6, 1, 5, 5, 7, 3, 1
69 public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
70 1, 3, 6, 1, 5, 5, 7, 3, 2
73 public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
74 1, 3, 6, 1, 5, 5, 7, 3, 3
77 public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
78 1, 3, 6, 1, 5, 5, 7, 3, 4
81 public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
82 1, 3, 6, 1, 5, 5, 7, 3, 8
85 public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
86 1, 3, 6, 1, 5, 5, 7, 3, 9
89 private CSRType csrType;
91 private final PublicKey pk;
95 public String name = DEFAULT_CN;
97 private Set<SubjectAlternateName> SANs;
99 private Digest selectedDigest = Digest.getDefault();
101 private CertificateProfile profile = CertificateProfile.getById(1);
103 private String ou = "";
105 private AuthorizationContext ctx;
107 private String pDNS, pMail;
109 public CertificateRequest(AuthorizationContext c, String csr) throws IOException, GeneralSecurityException, GigiApiException {
110 this(c, csr, (CertificateProfile) null);
113 public CertificateRequest(AuthorizationContext ctx, String csr, CertificateProfile cp) throws GeneralSecurityException, IOException, IOException, GigiApiException {
117 } else if (ctx.getActor().getVerificationPoints() > 50) {
118 profile = CertificateProfile.getByName("client-a");
120 byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
121 PKCS10 parsed = new PKCS10(data);
122 PKCS10Attributes atts = parsed.getAttributes();
124 TreeSet<SubjectAlternateName> SANs = new TreeSet<>();
125 for (RDN r : parsed.getSubjectName().rdns()) {
126 for (AVA a : r.avas()) {
127 if (a.getObjectIdentifier().equals((Object) PKCS9Attribute.EMAIL_ADDRESS_OID)) {
128 SANs.add(new SubjectAlternateName(SANType.EMAIL, a.getValueString()));
129 } else if (a.getObjectIdentifier().equals((Object) X500Name.commonName_oid)) {
130 String value = a.getValueString();
131 if (value.contains(".") && !value.contains(" ")) {
132 SANs.add(new SubjectAlternateName(SANType.DNS, value));
136 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
137 // TODO? parse invalid SANs
142 for (PKCS10Attribute b : atts.getAttributes()) {
144 if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
149 for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
150 if (c instanceof SubjectAlternativeNameExtension) {
152 SubjectAlternativeNameExtension san = (SubjectAlternativeNameExtension) c;
153 GeneralNames obj = san.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
154 for (int i = 0; i < obj.size(); i++) {
155 GeneralName generalName = obj.get(i);
156 GeneralNameInterface peeled = generalName.getName();
157 if (peeled instanceof DNSName) {
158 SANs.add(new SubjectAlternateName(SANType.DNS, ((DNSName) peeled).getName()));
159 } else if (peeled instanceof RFC822Name) {
160 SANs.add(new SubjectAlternateName(SANType.EMAIL, ((RFC822Name) peeled).getName()));
163 } else if (c instanceof ExtendedKeyUsageExtension) {
164 ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
165 String appendix = "";
166 if (ctx.getActor().getVerificationPoints() >= 50) {
169 for (String s : ekue.getExtendedKeyUsage()) {
170 if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
172 profile = CertificateProfile.getByName("server" + appendix);
173 } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
175 profile = CertificateProfile.getByName("client" + appendix);
176 } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
178 } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
180 profile = CertificateProfile.getByName("mail" + appendix);
181 } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
183 } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
188 // Unknown requested extension
194 pk = parsed.getSubjectPublicKeyInfo();
195 KeyCheck.checkKey(pk);
197 String sign = getSignatureAlgorithm(data);
201 this.csrType = CSRType.CSR;
204 public CertificateRequest(AuthorizationContext ctx, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
206 String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
207 byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
208 SPKAC parsed = new SPKAC(data);
209 if ( !parsed.getChallenge().equals(spkacChallenge)) {
210 throw new GigiApiException("Challenge mismatch");
212 pk = parsed.getPubkey();
213 KeyCheck.checkKey(pk);
215 String sign = getSignatureAlgorithm(data);
217 this.SANs = new HashSet<>();
218 this.csr = "SPKAC=" + cleanedSPKAC;
219 this.csrType = CSRType.SPKAC;
222 private static String getSignatureAlgorithm(byte[] data) throws IOException {
223 DerInputStream in = new DerInputStream(data);
224 DerValue[] seq = in.getSequence(3);
225 return AlgorithmId.parse(seq[1]).getName();
228 private void guessDigest(String sign) {
229 if (sign.toLowerCase().startsWith("sha512")) {
230 selectedDigest = Digest.SHA512;
231 } else if (sign.toLowerCase().startsWith("sha384")) {
232 selectedDigest = Digest.SHA384;
233 } else if (sign.toLowerCase().startsWith("sha256")) {
234 selectedDigest = Digest.SHA256;
238 public void checkKeyStrength(PrintWriter out) {
239 out.println("Type: " + pk.getAlgorithm() + "<br/>");
240 if (pk instanceof RSAPublicKey) {
241 out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
242 out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
243 } else if (pk instanceof DSAPublicKey) {
244 DSAPublicKey dpk = (DSAPublicKey) pk;
245 out.println("Length: " + dpk.getY().bitLength() + "<br/>");
246 out.println(dpk.getParams());
247 } else if (pk instanceof ECPublicKey) {
248 ECPublicKey epk = (ECPublicKey) pk;
249 out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
250 out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
251 out.println(epk.getParams().getCurve());
255 private Set<SubjectAlternateName> parseSANBox(String SANs) {
256 String[] SANparts = SANs.split("[\r\n]+|, *");
257 Set<SubjectAlternateName> parsedNames = new LinkedHashSet<>();
258 for (String SANline : SANparts) {
259 String[] parts = SANline.split(":", 2);
260 if (parts.length == 1) {
261 if (parts[0].trim().equals("")) {
264 if (parts[0].contains("@")) {
265 parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
267 parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
272 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase().trim());
276 parsedNames.add(new SubjectAlternateName(t, parts[1].trim()));
277 } catch (IllegalArgumentException e) {
285 public Set<SubjectAlternateName> getSANs() {
289 public String getName() {
293 public synchronized String getOu() {
294 if (ctx.getTarget() instanceof Organisation) {
297 throw new IllegalStateException();
300 public Digest getSelectedDigest() {
301 return selectedDigest;
304 public CertificateProfile getProfile() {
308 public synchronized boolean update(String nameIn, String hashAlg, String profileStr, String newOrgStr, String ou, String SANsStr) throws GigiApiException {
309 GigiApiException error = new GigiApiException();
311 if (hashAlg != null) {
312 selectedDigest = Digest.valueOf(hashAlg);
314 this.profile = CertificateProfile.getByName(profileStr);
315 if (ctx.getTarget() instanceof Organisation) {
319 if ( !this.profile.canBeIssuedBy(ctx.getTarget(), ctx.getActor())) {
320 this.profile = CertificateProfile.getById(1);
321 error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
325 verifySANs(error, profile, parseSANBox(SANsStr), ctx.getTarget(), ctx.getActor());
327 if ( !error.isEmpty()) {
333 private void verifySANs(GigiApiException error, CertificateProfile p, Set<SubjectAlternateName> sANs2, CertificateOwner owner, User user) {
334 Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
335 PropertyTemplate domainTemp = p.getTemplates().get("domain");
336 PropertyTemplate emailTemp = p.getTemplates().get("email");
339 for (SubjectAlternateName san : sANs2) {
340 if (san.getType() == SANType.DNS) {
341 if (domainTemp != null && owner.isValidDomain(san.getName())) {
344 DomainAssessment.checkCertifiableDomain(san.getName(), user.isInGroup(Group.CODESIGNING), false);
346 if ( !valid || !CAA.verifyDomainAccess(owner, p, san.getName()) || (pDNS != null && !domainTemp.isMultiple())) {
350 pDNS = san.getName();
352 filteredSANs.add(san);
355 } catch (GigiApiException e) {
360 } else if (san.getType() == SANType.EMAIL && emailTemp != null) {
361 if (owner.isValidEmail(san.getName())) {
362 if (pMail != null && !emailTemp.isMultiple()) {
366 pMail = san.getName();
368 filteredSANs.add(san);
373 error.mergeInto(new GigiApiException(SprintfCommand.createSimple(//
374 "The requested subject alternate name email address \"{0}\" needs an email ping within the past {1} months.", san.getType().toString().toLowerCase() + ":" + san.getName(), TimeConditions.getInstance().getEmailPingMonths())));
378 error.mergeInto(new GigiApiException(SprintfCommand.createSimple(//
379 "The requested subject alternate name (SAN) \"{0}\" has been removed.", san.getType().toString().toLowerCase() + ":" + san.getName())));
384 // domain email name name=WoTUser orga
385 public synchronized Certificate draft() throws GigiApiException {
387 GigiApiException error = new GigiApiException();
389 HashMap<String, String> subject = new HashMap<>();
390 PropertyTemplate domainTemp = profile.getTemplates().get("domain");
391 PropertyTemplate emailTemp = profile.getTemplates().get("email");
392 PropertyTemplate nameTemp = profile.getTemplates().get("name");
393 PropertyTemplate wotUserTemp = profile.getTemplates().get("name=WoTUser");
394 verifySANs(error, profile, SANs, ctx.getTarget(), ctx.getActor());
396 // Ok, let's determine the CN
398 // 1. the user's "real name", iff the real name is to be included i.e.
399 // not empty (name), or to be forced to WOTUser
401 // 2. the user's "primary domain", iff "1." doesn't match and there is a
402 // primary domain. (domainTemp != null)
404 String verifiedCN = null;
405 if (ctx.getTarget() instanceof Organisation) {
406 if ( !name.equals("")) {
410 verifiedCN = verifyName(error, nameTemp, wotUserTemp, verifiedCN);
412 if (pDNS == null && domainTemp != null && domainTemp.isRequired()) {
413 error.mergeInto(new GigiApiException("Server Certificates require a DNS name."));
414 } else if (domainTemp != null && verifiedCN == null) {
415 // user may add domains
418 if (verifiedCN != null) {
419 subject.put("CN", verifiedCN);
423 if (emailTemp != null) {
424 subject.put("EMAIL", pMail);
426 // verify SANs should prevent this
428 error.mergeInto(new GigiApiException("You may not include an email in this certificate."));
431 if (emailTemp != null && emailTemp.isRequired()) {
432 error.mergeInto(new GigiApiException("You need to include an email in this certificate."));
436 if (ctx.getTarget() instanceof Organisation) {
437 Organisation org = (Organisation) ctx.getTarget();
438 subject.put("O", org.getName());
439 subject.put("C", org.getCountry().getCode());
440 subject.put("ST", org.getProvince());
441 subject.put("L", org.getCity());
443 subject.put("OU", ou);
446 System.out.println(subject);
447 if ( !error.isEmpty()) {
451 if (RATE_LIMIT.isLimitExceeded(Integer.toString(ctx.getActor().getId()))) {
452 throw new GigiApiException("Rate Limit Exceeded");
454 return new Certificate(ctx.getTarget(), ctx.getActor(), subject, selectedDigest, //
455 this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
456 } catch (IOException e) {
462 // 100 per 10 minutes
463 public static final RateLimit RATE_LIMIT = new RateLimit(100, 10 * 60 * 1000);
465 private String verifyName(GigiApiException error, PropertyTemplate nameTemp, PropertyTemplate wotUserTemp, String verifiedCN) {
467 // possible configurations: name {y,null,?}, name=WoTUser {y,null}
472 // ? y -> real, default
473 // ? null -> real, default, null
474 boolean realIsOK = false;
475 boolean nullIsOK = false;
476 boolean defaultIsOK = false;
477 if (wotUserTemp != null && ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple())) {
478 error.mergeInto(new GigiApiException("Internal configuration error detected."));
480 if (nameTemp != null && nameTemp.isRequired() && !nameTemp.isMultiple()) {
482 } else if (nameTemp == null) {
483 defaultIsOK = wotUserTemp != null;
484 nullIsOK = !defaultIsOK;
485 } else if (nameTemp != null && !nameTemp.isRequired() && !nameTemp.isMultiple()) {
488 nullIsOK = wotUserTemp == null;
490 error.mergeInto(new GigiApiException("Internal configuration error detected."));
492 if (ctx.getTarget() instanceof User) {
493 User u = (User) ctx.getTarget();
494 if (name != null && u.isValidName(name)) {
498 error.mergeInto(new GigiApiException("Your real name is not allowed in this certificate."));
501 } else if (nullIsOK) {
505 } else if (name != null && name.equals(DEFAULT_CN)) {
509 error.mergeInto(new GigiApiException("The default name is not allowed in this certificate."));
512 } else if (realIsOK) {
513 name = u.getPreferredName().toString();
516 } else if (name == null || name.equals("")) {
520 error.mergeInto(new GigiApiException("A name is required in this certificate."));
523 } else if (realIsOK) {
524 name = u.getPreferredName().toString();
528 error.mergeInto(new GigiApiException("The name you entered was invalid."));
531 if (wotUserTemp != null) {
532 if ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple()) {
533 error.mergeInto(new GigiApiException("Internal configuration error detected."));
535 if ( !name.equals(DEFAULT_CN)) {
537 error.mergeInto(new GigiApiException("You may not change the name for this certificate type."));
539 verifiedCN = DEFAULT_CN;
543 if (nameTemp != null) {
544 if (name.equals("")) {
545 if (nameTemp.isRequired()) {
546 // nothing, but required
548 error.mergeInto(new GigiApiException("No name entered, but one was required."));
550 // nothing and not required
553 } else if (u.isValidName(name)) {
556 if (nameTemp.isRequired()) {
557 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."));
558 } else if (name.equals(DEFAULT_CN)) {
559 verifiedCN = DEFAULT_CN;
562 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."));
566 if ( !name.equals("")) {
568 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
578 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));