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 sun.security.pkcs.PKCS9Attribute;
39 import sun.security.pkcs10.PKCS10;
40 import sun.security.pkcs10.PKCS10Attribute;
41 import sun.security.pkcs10.PKCS10Attributes;
42 import sun.security.util.DerInputStream;
43 import sun.security.util.DerValue;
44 import sun.security.util.ObjectIdentifier;
45 import sun.security.x509.AVA;
46 import sun.security.x509.AlgorithmId;
47 import sun.security.x509.CertificateExtensions;
48 import sun.security.x509.DNSName;
49 import sun.security.x509.ExtendedKeyUsageExtension;
50 import sun.security.x509.Extension;
51 import sun.security.x509.GeneralName;
52 import sun.security.x509.GeneralNameInterface;
53 import sun.security.x509.GeneralNames;
54 import sun.security.x509.PKIXExtensions;
55 import sun.security.x509.RDN;
56 import sun.security.x509.RFC822Name;
57 import sun.security.x509.SubjectAlternativeNameExtension;
58 import sun.security.x509.X500Name;
60 public class CertificateRequest {
62 public static final String DEFAULT_CN = ServerConstants.getAppName() + " User";
64 public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
65 1, 3, 6, 1, 5, 5, 7, 3, 1
68 public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
69 1, 3, 6, 1, 5, 5, 7, 3, 2
72 public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
73 1, 3, 6, 1, 5, 5, 7, 3, 3
76 public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
77 1, 3, 6, 1, 5, 5, 7, 3, 4
80 public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
81 1, 3, 6, 1, 5, 5, 7, 3, 8
84 public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
85 1, 3, 6, 1, 5, 5, 7, 3, 9
88 private CSRType csrType;
90 private final PublicKey pk;
94 public String name = DEFAULT_CN;
96 private Set<SubjectAlternateName> SANs;
98 private Digest selectedDigest = Digest.getDefault();
100 private CertificateProfile profile = CertificateProfile.getById(1);
102 private String ou = "";
104 private AuthorizationContext ctx;
106 private String pDNS, pMail;
108 public CertificateRequest(AuthorizationContext c, String csr) throws IOException, GeneralSecurityException, GigiApiException {
109 this(c, csr, (CertificateProfile) null);
112 public CertificateRequest(AuthorizationContext ctx, String csr, CertificateProfile cp) throws GeneralSecurityException, IOException, IOException, GigiApiException {
116 } else if (ctx.getActor().getVerificationPoints() > 50) {
117 profile = CertificateProfile.getByName("client-a");
119 byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
120 PKCS10 parsed = new PKCS10(data);
121 PKCS10Attributes atts = parsed.getAttributes();
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));
135 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
136 // TODO? parse invalid SANs
141 for (PKCS10Attribute b : atts.getAttributes()) {
143 if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
148 for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
149 if (c instanceof SubjectAlternativeNameExtension) {
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()));
162 } else if (c instanceof ExtendedKeyUsageExtension) {
163 ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
164 String appendix = "";
165 if (ctx.getActor().getVerificationPoints() >= 50) {
168 for (String s : ekue.getExtendedKeyUsage()) {
169 if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
171 profile = CertificateProfile.getByName("server" + appendix);
172 } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
174 profile = CertificateProfile.getByName("client" + appendix);
175 } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
177 } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
179 profile = CertificateProfile.getByName("mail" + appendix);
180 } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
182 } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
187 // Unknown requested extension
193 pk = parsed.getSubjectPublicKeyInfo();
194 KeyCheck.checkKey(pk);
196 String sign = getSignatureAlgorithm(data);
200 this.csrType = CSRType.CSR;
203 public CertificateRequest(AuthorizationContext ctx, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
205 String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
206 byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
207 SPKAC parsed = new SPKAC(data);
208 if ( !parsed.getChallenge().equals(spkacChallenge)) {
209 throw new GigiApiException("Challenge mismatch");
211 pk = parsed.getPubkey();
212 KeyCheck.checkKey(pk);
214 String sign = getSignatureAlgorithm(data);
216 this.SANs = new HashSet<>();
217 this.csr = "SPKAC=" + cleanedSPKAC;
218 this.csrType = CSRType.SPKAC;
221 private static String getSignatureAlgorithm(byte[] data) throws IOException {
222 DerInputStream in = new DerInputStream(data);
223 DerValue[] seq = in.getSequence(3);
224 return AlgorithmId.parse(seq[1]).getName();
227 private void guessDigest(String sign) {
228 if (sign.toLowerCase().startsWith("sha512")) {
229 selectedDigest = Digest.SHA512;
230 } else if (sign.toLowerCase().startsWith("sha384")) {
231 selectedDigest = Digest.SHA384;
232 } else if (sign.toLowerCase().startsWith("sha256")) {
233 selectedDigest = Digest.SHA256;
237 public void checkKeyStrength(PrintWriter out) {
238 out.println("Type: " + pk.getAlgorithm() + "<br/>");
239 if (pk instanceof RSAPublicKey) {
240 out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
241 out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
242 } else if (pk instanceof DSAPublicKey) {
243 DSAPublicKey dpk = (DSAPublicKey) pk;
244 out.println("Length: " + dpk.getY().bitLength() + "<br/>");
245 out.println(dpk.getParams());
246 } else if (pk instanceof ECPublicKey) {
247 ECPublicKey epk = (ECPublicKey) pk;
248 out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
249 out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
250 out.println(epk.getParams().getCurve());
254 private Set<SubjectAlternateName> parseSANBox(String SANs) {
255 String[] SANparts = SANs.split("[\r\n]+|, *");
256 Set<SubjectAlternateName> parsedNames = new LinkedHashSet<>();
257 for (String SANline : SANparts) {
258 String[] parts = SANline.split(":", 2);
259 if (parts.length == 1) {
260 if (parts[0].trim().equals("")) {
263 if (parts[0].contains("@")) {
264 parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
266 parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
271 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase().trim());
275 parsedNames.add(new SubjectAlternateName(t, parts[1].trim()));
276 } catch (IllegalArgumentException e) {
284 public Set<SubjectAlternateName> getSANs() {
288 public String getName() {
292 public synchronized String getOu() {
293 if (ctx.getTarget() instanceof Organisation) {
296 throw new IllegalStateException();
299 public Digest getSelectedDigest() {
300 return selectedDigest;
303 public CertificateProfile getProfile() {
307 public synchronized boolean update(String nameIn, String hashAlg, String profileStr, String newOrgStr, String ou, String SANsStr) throws GigiApiException {
308 GigiApiException error = new GigiApiException();
310 if (hashAlg != null) {
311 selectedDigest = Digest.valueOf(hashAlg);
313 this.profile = CertificateProfile.getByName(profileStr);
314 if (ctx.getTarget() instanceof Organisation) {
318 if ( !this.profile.canBeIssuedBy(ctx.getTarget(), ctx.getActor())) {
319 this.profile = CertificateProfile.getById(1);
320 error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
324 verifySANs(error, profile, parseSANBox(SANsStr), ctx.getTarget(), ctx.getActor());
326 if ( !error.isEmpty()) {
332 private void verifySANs(GigiApiException error, CertificateProfile p, Set<SubjectAlternateName> sANs2, CertificateOwner owner, User user) {
333 Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
334 PropertyTemplate domainTemp = p.getTemplates().get("domain");
335 PropertyTemplate emailTemp = p.getTemplates().get("email");
338 for (SubjectAlternateName san : sANs2) {
339 if (san.getType() == SANType.DNS) {
340 if (domainTemp != null && owner.isValidDomain(san.getName())) {
343 DomainAssessment.checkCertifiableDomain(san.getName(), user.isInGroup(Group.CODESIGNING), false);
345 if ( !valid || !CAA.verifyDomainAccess(owner, p, san.getName()) || (pDNS != null && !domainTemp.isMultiple())) {
349 pDNS = san.getName();
351 filteredSANs.add(san);
354 } catch (GigiApiException e) {
359 } else if (san.getType() == SANType.EMAIL) {
360 if (emailTemp != null && owner.isValidEmail(san.getName())) {
361 if (pMail != null && !emailTemp.isMultiple()) {
365 pMail = san.getName();
367 filteredSANs.add(san);
372 error.mergeInto(new GigiApiException(SprintfCommand.createSimple(//
373 "The requested subject alternate name (SAN) \"{0}\" has been removed.", san.getType().toString().toLowerCase() + ":" + san.getName())));
378 // domain email name name=WoTUser orga
379 public synchronized Certificate draft() throws GigiApiException {
381 GigiApiException error = new GigiApiException();
383 HashMap<String, String> subject = new HashMap<>();
384 PropertyTemplate domainTemp = profile.getTemplates().get("domain");
385 PropertyTemplate emailTemp = profile.getTemplates().get("email");
386 PropertyTemplate nameTemp = profile.getTemplates().get("name");
387 PropertyTemplate wotUserTemp = profile.getTemplates().get("name=WoTUser");
388 verifySANs(error, profile, SANs, ctx.getTarget(), ctx.getActor());
390 // Ok, let's determine the CN
392 // 1. the user's "real name", iff the real name is to be included i.e.
393 // not empty (name), or to be forced to WOTUser
395 // 2. the user's "primary domain", iff "1." doesn't match and there is a
396 // primary domain. (domainTemp != null)
398 String verifiedCN = null;
399 if (ctx.getTarget() instanceof Organisation) {
400 if ( !name.equals("")) {
404 verifiedCN = verifyName(error, nameTemp, wotUserTemp, verifiedCN);
406 if (pDNS == null && domainTemp != null && domainTemp.isRequired()) {
407 error.mergeInto(new GigiApiException("Server Certificates require a DNS name."));
408 } else if (domainTemp != null && verifiedCN == null) {
409 // user may add domains
412 if (verifiedCN != null) {
413 subject.put("CN", verifiedCN);
417 if (emailTemp != null) {
418 subject.put("EMAIL", pMail);
420 // verify SANs should prevent this
422 error.mergeInto(new GigiApiException("You may not include an email in this certificate."));
425 if (emailTemp != null && emailTemp.isRequired()) {
426 error.mergeInto(new GigiApiException("You need to include an email in this certificate."));
430 if (ctx.getTarget() instanceof Organisation) {
431 Organisation org = (Organisation) ctx.getTarget();
432 subject.put("O", org.getName());
433 subject.put("C", org.getCountry().getCode());
434 subject.put("ST", org.getProvince());
435 subject.put("L", org.getCity());
437 subject.put("OU", ou);
440 System.out.println(subject);
441 if ( !error.isEmpty()) {
445 if (RATE_LIMIT.isLimitExceeded(Integer.toString(ctx.getActor().getId()))) {
446 throw new GigiApiException("Rate Limit Exceeded");
448 return new Certificate(ctx.getTarget(), ctx.getActor(), subject, selectedDigest, //
449 this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));
450 } catch (IOException e) {
456 // 100 per 10 minutes
457 public static final RateLimit RATE_LIMIT = new RateLimit(100, 10 * 60 * 1000);
459 private String verifyName(GigiApiException error, PropertyTemplate nameTemp, PropertyTemplate wotUserTemp, String verifiedCN) {
461 // possible configurations: name {y,null,?}, name=WoTUser {y,null}
466 // ? y -> real, default
467 // ? null -> real, default, null
468 boolean realIsOK = false;
469 boolean nullIsOK = false;
470 boolean defaultIsOK = false;
471 if (wotUserTemp != null && ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple())) {
472 error.mergeInto(new GigiApiException("Internal configuration error detected."));
474 if (nameTemp != null && nameTemp.isRequired() && !nameTemp.isMultiple()) {
476 } else if (nameTemp == null) {
477 defaultIsOK = wotUserTemp != null;
478 nullIsOK = !defaultIsOK;
479 } else if (nameTemp != null && !nameTemp.isRequired() && !nameTemp.isMultiple()) {
482 nullIsOK = wotUserTemp == null;
484 error.mergeInto(new GigiApiException("Internal configuration error detected."));
486 if (ctx.getTarget() instanceof User) {
487 User u = (User) ctx.getTarget();
488 if (name != null && u.isValidName(name)) {
492 error.mergeInto(new GigiApiException("Your real name is not allowed in this certificate."));
495 } else if (nullIsOK) {
499 } else if (name != null && name.equals(DEFAULT_CN)) {
503 error.mergeInto(new GigiApiException("The default name is not allowed in this certificate."));
506 } else if (realIsOK) {
507 name = u.getPreferredName().toString();
510 } else if (name == null || name.equals("")) {
514 error.mergeInto(new GigiApiException("A name is required in this certificate."));
517 } else if (realIsOK) {
518 name = u.getPreferredName().toString();
522 error.mergeInto(new GigiApiException("The name you entered was invalid."));
525 if (wotUserTemp != null) {
526 if ( !wotUserTemp.isRequired() || wotUserTemp.isMultiple()) {
527 error.mergeInto(new GigiApiException("Internal configuration error detected."));
529 if ( !name.equals(DEFAULT_CN)) {
531 error.mergeInto(new GigiApiException("You may not change the name for this certificate type."));
533 verifiedCN = DEFAULT_CN;
537 if (nameTemp != null) {
538 if (name.equals("")) {
539 if (nameTemp.isRequired()) {
540 // nothing, but required
542 error.mergeInto(new GigiApiException("No name entered, but one was required."));
544 // nothing and not required
547 } else if (u.isValidName(name)) {
550 if (nameTemp.isRequired()) {
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, because a name is required for this certificate type."));
552 } else if (name.equals(DEFAULT_CN)) {
553 verifiedCN = DEFAULT_CN;
556 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."));
560 if ( !name.equals("")) {
562 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
572 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));