1 package org.cacert.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.Arrays;
11 import java.util.Base64;
12 import java.util.HashMap;
13 import java.util.LinkedHashSet;
15 import java.util.TreeSet;
17 import javax.servlet.http.HttpServletRequest;
19 import org.cacert.gigi.GigiApiException;
20 import org.cacert.gigi.crypto.SPKAC;
21 import org.cacert.gigi.dbObjects.Certificate;
22 import org.cacert.gigi.dbObjects.Certificate.CSRType;
23 import org.cacert.gigi.dbObjects.Certificate.SANType;
24 import org.cacert.gigi.dbObjects.Certificate.SubjectAlternateName;
25 import org.cacert.gigi.dbObjects.CertificateProfile;
26 import org.cacert.gigi.dbObjects.Digest;
27 import org.cacert.gigi.dbObjects.Organisation;
28 import org.cacert.gigi.dbObjects.User;
29 import org.cacert.gigi.output.template.Scope;
30 import org.cacert.gigi.output.template.SprintfCommand;
31 import org.cacert.gigi.util.PEM;
33 import sun.security.pkcs.PKCS9Attribute;
34 import sun.security.pkcs10.PKCS10;
35 import sun.security.pkcs10.PKCS10Attribute;
36 import sun.security.pkcs10.PKCS10Attributes;
37 import sun.security.util.DerInputStream;
38 import sun.security.util.DerValue;
39 import sun.security.util.ObjectIdentifier;
40 import sun.security.x509.AVA;
41 import sun.security.x509.AlgorithmId;
42 import sun.security.x509.CertificateExtensions;
43 import sun.security.x509.DNSName;
44 import sun.security.x509.ExtendedKeyUsageExtension;
45 import sun.security.x509.Extension;
46 import sun.security.x509.GeneralName;
47 import sun.security.x509.GeneralNameInterface;
48 import sun.security.x509.GeneralNames;
49 import sun.security.x509.PKIXExtensions;
50 import sun.security.x509.RDN;
51 import sun.security.x509.RFC822Name;
52 import sun.security.x509.SubjectAlternativeNameExtension;
53 import sun.security.x509.X500Name;
55 public class CertificateRequest {
57 public static final String DEFAULT_CN = "CAcert WoT User";
59 public static final ObjectIdentifier OID_KEY_USAGE_SSL_SERVER = ObjectIdentifier.newInternal(new int[] {
60 1, 3, 6, 1, 5, 5, 7, 3, 1
63 public static final ObjectIdentifier OID_KEY_USAGE_SSL_CLIENT = ObjectIdentifier.newInternal(new int[] {
64 1, 3, 6, 1, 5, 5, 7, 3, 2
67 public static final ObjectIdentifier OID_KEY_USAGE_CODESIGN = ObjectIdentifier.newInternal(new int[] {
68 1, 3, 6, 1, 5, 5, 7, 3, 3
71 public static final ObjectIdentifier OID_KEY_USAGE_EMAIL_PROTECTION = ObjectIdentifier.newInternal(new int[] {
72 1, 3, 6, 1, 5, 5, 7, 3, 4
75 public static final ObjectIdentifier OID_KEY_USAGE_TIMESTAMP = ObjectIdentifier.newInternal(new int[] {
76 1, 3, 6, 1, 5, 5, 7, 3, 8
79 public static final ObjectIdentifier OID_KEY_USAGE_OCSP = ObjectIdentifier.newInternal(new int[] {
80 1, 3, 6, 1, 5, 5, 7, 3, 9
83 private CSRType csrType;
85 private final PublicKey pk;
89 public String CN = DEFAULT_CN;
91 private Set<SubjectAlternateName> SANs;
93 private Digest selectedDigest = Digest.getDefault();
95 private CertificateProfile profile = CertificateProfile.getById(1);
97 private String ou = "";
99 private Organisation org = null;
103 private String pDNS, pMail;
105 public CertificateRequest(User issuer, String csr) throws IOException, GeneralSecurityException, GigiApiException {
107 byte[] data = PEM.decode("(NEW )?CERTIFICATE REQUEST", csr);
108 PKCS10 parsed = new PKCS10(data);
109 PKCS10Attributes atts = parsed.getAttributes();
111 TreeSet<SubjectAlternateName> SANs = new TreeSet<>();
112 for (RDN r : parsed.getSubjectName().rdns()) {
113 for (AVA a : r.avas()) {
114 if (a.getObjectIdentifier().equals((Object) PKCS9Attribute.EMAIL_ADDRESS_OID)) {
115 SANs.add(new SubjectAlternateName(SANType.EMAIL, a.getValueString()));
116 } else if (a.getObjectIdentifier().equals((Object) X500Name.commonName_oid)) {
117 String value = a.getValueString();
118 if (value.contains(".") && !value.contains(" ")) {
119 SANs.add(new SubjectAlternateName(SANType.DNS, value));
123 } else if (a.getObjectIdentifier().equals((Object) PKIXExtensions.SubjectAlternativeName_Id)) {
124 // TODO? parse invalid SANs
129 for (PKCS10Attribute b : atts.getAttributes()) {
131 if ( !b.getAttributeId().equals((Object) PKCS9Attribute.EXTENSION_REQUEST_OID)) {
136 for (Extension c : ((CertificateExtensions) b.getAttributeValue()).getAllExtensions()) {
137 if (c instanceof SubjectAlternativeNameExtension) {
139 SubjectAlternativeNameExtension san = (SubjectAlternativeNameExtension) c;
140 GeneralNames obj = san.get(SubjectAlternativeNameExtension.SUBJECT_NAME);
141 for (int i = 0; i < obj.size(); i++) {
142 GeneralName generalName = obj.get(i);
143 GeneralNameInterface peeled = generalName.getName();
144 if (peeled instanceof DNSName) {
145 SANs.add(new SubjectAlternateName(SANType.DNS, ((DNSName) peeled).getName()));
146 } else if (peeled instanceof RFC822Name) {
147 SANs.add(new SubjectAlternateName(SANType.EMAIL, ((RFC822Name) peeled).getName()));
150 } else if (c instanceof ExtendedKeyUsageExtension) {
151 ExtendedKeyUsageExtension ekue = (ExtendedKeyUsageExtension) c;
152 for (String s : ekue.getExtendedKeyUsage()) {
153 if (s.equals(OID_KEY_USAGE_SSL_SERVER.toString())) {
155 profile = CertificateProfile.getByName("server");
156 } else if (s.equals(OID_KEY_USAGE_SSL_CLIENT.toString())) {
158 profile = CertificateProfile.getByName("client");
159 } else if (s.equals(OID_KEY_USAGE_CODESIGN.toString())) {
161 } else if (s.equals(OID_KEY_USAGE_EMAIL_PROTECTION.toString())) {
163 profile = CertificateProfile.getByName("mail");
164 } else if (s.equals(OID_KEY_USAGE_TIMESTAMP.toString())) {
166 } else if (s.equals(OID_KEY_USAGE_OCSP.toString())) {
171 // Unknown requested extension
176 GigiApiException error = new GigiApiException();
177 this.SANs = verifySANs(error, false, SANs);
178 if ( !error.isEmpty()) {
181 pk = parsed.getSubjectPublicKeyInfo();
182 String sign = getSignatureAlgorithm(data);
186 this.csrType = CSRType.CSR;
189 public CertificateRequest(User issuer, String spkac, String spkacChallenge) throws IOException, GigiApiException, GeneralSecurityException {
191 String cleanedSPKAC = spkac.replaceAll("[\r\n]", "");
192 byte[] data = Base64.getDecoder().decode(cleanedSPKAC);
193 SPKAC parsed = new SPKAC(data);
194 if ( !parsed.getChallenge().equals(spkacChallenge)) {
195 throw new GigiApiException("Challenge mismatch");
197 pk = parsed.getPubkey();
198 String sign = getSignatureAlgorithm(data);
201 this.csr = "SPKAC=" + cleanedSPKAC;
202 this.csrType = CSRType.SPKAC;
206 private static String getSignatureAlgorithm(byte[] data) throws IOException {
207 DerInputStream in = new DerInputStream(data);
208 DerValue[] seq = in.getSequence(3);
209 return AlgorithmId.parse(seq[1]).getName();
212 private void guessDigest(String sign) {
213 if (sign.toLowerCase().startsWith("sha512")) {
214 selectedDigest = Digest.SHA512;
215 } else if (sign.toLowerCase().startsWith("sha384")) {
216 selectedDigest = Digest.SHA384;
220 public void checkKeyStrength(PrintWriter out) {
221 out.println("Type: " + pk.getAlgorithm() + "<br/>");
222 if (pk instanceof RSAPublicKey) {
223 out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "<br/>");
224 out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength());
225 } else if (pk instanceof DSAPublicKey) {
226 DSAPublicKey dpk = (DSAPublicKey) pk;
227 out.println("Length: " + dpk.getY().bitLength() + "<br/>");
228 out.println(dpk.getParams());
229 } else if (pk instanceof ECPublicKey) {
230 ECPublicKey epk = (ECPublicKey) pk;
231 out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "<br/>");
232 out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "<br/>");
233 out.println(epk.getParams().getCurve());
237 private TreeSet<SubjectAlternateName> parseSANBox(String SANs) {
238 String[] SANparts = SANs.split("[\r\n]+|, *");
239 TreeSet<SubjectAlternateName> parsedNames = new TreeSet<>();
240 for (String SANline : SANparts) {
241 String[] parts = SANline.split(":", 2);
242 if (parts.length == 1) {
243 if (parts[0].trim().equals("")) {
246 if (parts[0].contains("@")) {
247 parsedNames.add(new SubjectAlternateName(SANType.EMAIL, parts[0]));
249 parsedNames.add(new SubjectAlternateName(SANType.DNS, parts[0]));
254 SANType t = Certificate.SANType.valueOf(parts[0].toUpperCase());
258 parsedNames.add(new SubjectAlternateName(t, parts[1]));
259 } catch (IllegalArgumentException e) {
267 public Set<SubjectAlternateName> getSANs() {
271 public String getCN() {
275 public Organisation getOrg() {
279 public String getOu() {
283 public Digest getSelectedDigest() {
284 return selectedDigest;
287 public CertificateProfile getProfile() {
291 public boolean update(String CNin, String hashAlg, String profileStr, String newOrgStr, String ou, String SANsStr, PrintWriter out, HttpServletRequest req) throws GigiApiException {
292 GigiApiException error = new GigiApiException();
294 if (hashAlg != null) {
295 selectedDigest = Digest.valueOf(hashAlg);
297 this.profile = CertificateProfile.getByName(profileStr);
298 if (newOrgStr != null) {
299 Organisation neworg = Organisation.getById(Integer.parseInt(newOrgStr));
300 if (neworg == null || u.getOrganisations().contains(neworg)) {
303 error.mergeInto(new GigiApiException("Selected Organisation is not part of your account."));
308 boolean server = profile.getKeyName().equals("server");
309 SANs = verifySANs(error, server, parseSANBox(SANsStr));
311 if ( !error.isEmpty()) {
317 private Set<SubjectAlternateName> verifySANs(GigiApiException error, boolean server, TreeSet<SubjectAlternateName> parseSANBox) {
318 Set<SubjectAlternateName> filteredSANs = new LinkedHashSet<>();
319 for (SubjectAlternateName san : parseSANBox) {
320 if (san.getType() == SANType.DNS) {
321 if (u.isValidDomain(san.getName()) && server) {
323 pDNS = san.getName();
325 filteredSANs.add(san);
328 } else if (san.getType() == SANType.EMAIL) {
329 if (u.isValidEmail(san.getName()) && !server) {
331 pMail = san.getName();
333 filteredSANs.add(san);
337 HashMap<String, Object> vars = new HashMap<>();
338 vars.put("SAN", san.getType().toString().toLowerCase() + ":" + san.getName());
339 error.mergeInto(new GigiApiException(new Scope(new SprintfCommand(//
340 "The requested Subject alternate name \"%s\" has been removed.", Arrays.asList("$SAN")), vars)));
345 public Certificate draft() throws GigiApiException {
347 GigiApiException error = new GigiApiException();
348 if ( !u.canIssue(this.profile)) {
349 this.profile = CertificateProfile.getById(1);
350 error.mergeInto(new GigiApiException("Certificate Profile is invalid."));
354 boolean server = profile.getKeyName().equals("server");
355 if ( !u.isValidName(CN) && !server && !CN.equals(DEFAULT_CN)) {
356 this.CN = DEFAULT_CN;
357 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."));
360 HashMap<String, String> subject = new HashMap<>();
361 if (server && pDNS != null) {
362 subject.put("CN", pDNS);
364 error.mergeInto(new GigiApiException("No email is included in this certificate."));
368 error.mergeInto(new GigiApiException("No real name is included in this certificate. The real name, you entered will be ignored."));
372 subject.put("CN", CN);
374 subject.put("EMAIL", pMail);
378 subject.put("O", org.getName());
379 subject.put("C", org.getState());
380 subject.put("ST", org.getProvince());
381 subject.put("L", org.getCity());
382 subject.put("OU", ou);
385 if ( !error.isEmpty()) {
388 return new Certificate(u, subject, selectedDigest.toString(), //
389 this.csr, this.csrType, profile, SANs.toArray(new SubjectAlternateName[SANs.size()]));