1 package org.cacert.gigi.pages.account;
3 import static org.hamcrest.CoreMatchers.*;
4 import static org.junit.Assert.*;
6 import java.io.ByteArrayInputStream;
7 import java.io.IOException;
8 import java.io.InputStreamReader;
9 import java.io.OutputStream;
10 import java.io.UnsupportedEncodingException;
11 import java.net.HttpURLConnection;
12 import java.net.MalformedURLException;
14 import java.net.URLConnection;
15 import java.net.URLEncoder;
16 import java.security.GeneralSecurityException;
17 import java.security.KeyPair;
18 import java.security.Signature;
19 import java.security.cert.CertificateException;
20 import java.security.cert.CertificateFactory;
21 import java.security.cert.X509Certificate;
22 import java.text.SimpleDateFormat;
23 import java.util.Arrays;
24 import java.util.Base64;
25 import java.util.Calendar;
26 import java.util.Date;
27 import java.util.TimeZone;
28 import java.util.Vector;
29 import java.util.regex.Matcher;
30 import java.util.regex.Pattern;
32 import org.cacert.gigi.crypto.SPKAC;
33 import org.cacert.gigi.dbObjects.Digest;
34 import org.cacert.gigi.pages.account.certs.CertificateAdd;
35 import org.cacert.gigi.pages.account.certs.CertificateRequest;
36 import org.cacert.gigi.testUtils.ClientTest;
37 import org.cacert.gigi.testUtils.IOUtils;
38 import org.cacert.gigi.util.PEM;
39 import org.junit.Test;
41 import sun.security.pkcs.PKCS9Attribute;
42 import sun.security.pkcs10.PKCS10Attribute;
43 import sun.security.pkcs10.PKCS10Attributes;
44 import sun.security.util.ObjectIdentifier;
45 import sun.security.x509.CertificateExtensions;
46 import sun.security.x509.DNSName;
47 import sun.security.x509.ExtendedKeyUsageExtension;
48 import sun.security.x509.GeneralName;
49 import sun.security.x509.GeneralNameInterface;
50 import sun.security.x509.GeneralNames;
51 import sun.security.x509.RFC822Name;
52 import sun.security.x509.SubjectAlternativeNameExtension;
53 import sun.security.x509.X509Key;
55 public class TestCertificateAdd extends ClientTest {
57 KeyPair kp = generateKeypair();
61 public TestCertificateAdd() throws GeneralSecurityException, IOException {
62 TestDomain.addDomain(cookie, uniq + ".tld");
67 public void testSimpleServer() throws IOException, GeneralSecurityException {
68 PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
69 CertificateRequest.OID_KEY_USAGE_SSL_SERVER
70 }, new DNSName(uniq + ".tld"));
72 String pem = generatePEMCSR(kp, "CN=a." + uniq + ".tld", atts);
74 String[] res = fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
75 assertArrayEquals(new String[] {
76 "server", "CAcert WoT User", "dns:a." + uniq + ".tld\ndns:" + uniq + ".tld\n", Digest.SHA256.toString()
81 public void testSimpleMail() throws IOException, GeneralSecurityException {
82 PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
83 CertificateRequest.OID_KEY_USAGE_EMAIL_PROTECTION
84 }, new DNSName("a." + uniq + ".tld"), new DNSName("b." + uniq + ".tld"), new RFC822Name(email));
86 String pem = generatePEMCSR(kp, "CN=a b", atts, "SHA384WithRSA");
88 String[] res = fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
89 assertArrayEquals(new String[] {
90 "mail", "a b", "email:" + email + "\ndns:a." + uniq + ".tld\ndns:b." + uniq + ".tld\n", Digest.SHA384.toString()
95 public void testSimpleClient() throws IOException, GeneralSecurityException {
96 PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
97 CertificateRequest.OID_KEY_USAGE_SSL_CLIENT
98 }, new RFC822Name(email));
100 String pem = generatePEMCSR(kp, "CN=a b,email=" + email, atts, "SHA512WithRSA");
102 String[] res = fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
103 assertArrayEquals(new String[] {
104 "client", "a b", "email:" + email + "\n", Digest.SHA512.toString()
109 public void testSPKAC() throws GeneralSecurityException, IOException {
115 public void testIssue() throws IOException, GeneralSecurityException {
116 PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
117 CertificateRequest.OID_KEY_USAGE_SSL_CLIENT
118 }, new RFC822Name(email));
120 String pem = generatePEMCSR(kp, "CN=a b,email=" + email, atts, "SHA512WithRSA");
122 String[] res = fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
123 assertArrayEquals(new String[] {
124 "client", "a b", "email:" + email + "\n", Digest.SHA512.toString()
127 HttpURLConnection huc = (HttpURLConnection) ncert.openConnection();
128 huc.setRequestProperty("Cookie", cookie);
129 huc.setDoOutput(true);
130 OutputStream out = huc.getOutputStream();
131 out.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8")).getBytes("UTF-8"));
132 out.write(("&profile=client&CN=a+b&SANs=" + URLEncoder.encode("email:" + email + "\n", "UTF-8")).getBytes("UTF-8"));
133 out.write(("&hash_alg=SHA512&CCA=y").getBytes("UTF-8"));
134 URLConnection uc = authenticate(new URL(huc.getHeaderField("Location") + ".crt"));
135 String crt = IOUtils.readURL(new InputStreamReader(uc.getInputStream(), "UTF-8"));
137 uc = authenticate(new URL(huc.getHeaderField("Location") + ".cer"));
138 byte[] cer = IOUtils.readURL(uc.getInputStream());
139 assertArrayEquals(cer, PEM.decode("CERTIFICATE", crt));
141 uc = authenticate(new URL(huc.getHeaderField("Location") + ".cer?install"));
142 byte[] cer2 = IOUtils.readURL(uc.getInputStream());
143 assertArrayEquals(cer, cer2);
144 assertEquals("application/x-x509-user-cert", uc.getHeaderField("Content-type"));
146 uc = authenticate(new URL(huc.getHeaderField("Location")));
147 String gui = IOUtils.readURL(uc);
148 assertThat(gui, containsString("clientAuth"));
149 assertThat(gui, containsString("CN=a b"));
150 assertThat(gui, containsString("SHA512withRSA"));
151 assertThat(gui, containsString("RFC822Name: " + email));
156 public void testValidityPeriodCalendar() throws IOException, GeneralSecurityException {
157 testCertificateValidityRelative(Calendar.YEAR, 2, "2y", true);
158 testCertificateValidityRelative(Calendar.YEAR, 1, "1y", true);
159 testCertificateValidityRelative(Calendar.MONTH, 3, "3m", true);
160 testCertificateValidityRelative(Calendar.MONTH, 7, "7m", true);
161 testCertificateValidityRelative(Calendar.MONTH, 13, "13m", true);
163 testCertificateValidityRelative(Calendar.MONTH, 13, "-1m", false);
167 public void testValidityPeriodWhishStart() throws IOException, GeneralSecurityException {
168 long now = System.currentTimeMillis();
169 final long MS_PER_DAY = 24 * 60 * 60 * 1000;
170 now -= now % MS_PER_DAY;
172 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
173 sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
175 Date start = new Date(now);
176 Date end = new Date(now + MS_PER_DAY * 10);
177 X509Certificate res = createCertWithValidity("&validFrom=" + sdf.format(start) + "&validity=" + sdf.format(end));
178 assertEquals(start, res.getNotBefore());
179 assertEquals(end, res.getNotAfter());
182 private void testCertificateValidityRelative(int field, int amount, String length, boolean shouldsucceed) throws IOException, GeneralSecurityException, UnsupportedEncodingException, MalformedURLException, CertificateException {
183 X509Certificate parsed = createCertWithValidity("&validFrom=now&validity=" + length);
184 if (parsed == null) {
185 assertTrue( !shouldsucceed);
188 assertTrue(shouldsucceed);
191 long now = System.currentTimeMillis();
192 Date start = parsed.getNotBefore();
193 Date end = parsed.getNotAfter();
194 Calendar c = Calendar.getInstance();
195 c.setTimeZone(TimeZone.getTimeZone("UTC"));
197 c.add(field, amount);
198 assertTrue(Math.abs(start.getTime() - now) < 10000);
199 assertEquals(c.getTime(), end);
202 private X509Certificate createCertWithValidity(String validity) throws IOException, GeneralSecurityException, UnsupportedEncodingException, MalformedURLException, CertificateException {
203 PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
204 CertificateRequest.OID_KEY_USAGE_SSL_CLIENT
205 }, new RFC822Name(email));
207 String pem = generatePEMCSR(kp, "CN=a b", atts, "SHA512WithRSA");
208 fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
210 HttpURLConnection huc = (HttpURLConnection) ncert.openConnection();
211 huc.setRequestProperty("Cookie", cookie);
212 huc.setDoOutput(true);
213 OutputStream out = huc.getOutputStream();
214 out.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8")).getBytes("UTF-8"));
215 out.write(("&profile=client&CN=a+b&SANs=" + URLEncoder.encode("email:" + email + "\n", "UTF-8")).getBytes("UTF-8"));
216 out.write(("&hash_alg=SHA512&CCA=y&").getBytes("UTF-8"));
217 out.write(validity.getBytes("UTF-8"));
219 String certurl = huc.getHeaderField("Location");
220 if (certurl == null) {
223 URLConnection uc = authenticate(new URL(certurl + ".crt"));
224 String crt = IOUtils.readURL(new InputStreamReader(uc.getInputStream(), "UTF-8"));
226 CertificateFactory cf = CertificateFactory.getInstance("X.509");
227 X509Certificate parsed = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(crt.getBytes("UTF-8")));
231 private URLConnection authenticate(URL url) throws IOException {
232 URLConnection uc = url.openConnection();
233 uc.setRequestProperty("Cookie", cookie);
237 protected String testSPKAC(boolean correctChallange) throws GeneralSecurityException, IOException {
238 HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
239 uc.setRequestProperty("Cookie", cookie);
240 String s = IOUtils.readURL(uc);
242 csrf = extractPattern(s, Pattern.compile("<input [^>]*name='csrf' [^>]*value='([^']*)'>"));
243 String challenge = extractPattern(s, Pattern.compile("<keygen [^>]*name=\"SPKAC\" [^>]*challenge=\"([^\"]*)\"/>"));
245 SPKAC spk = new SPKAC((X509Key) kp.getPublic(), challenge + (correctChallange ? "" : "b"));
246 Signature sign = Signature.getInstance("SHA512WithRSA");
247 sign.initSign(kp.getPrivate());
249 String[] res = fillOutFormDirect("SPKAC=" + URLEncoder.encode(Base64.getEncoder().encodeToString(spk.getEncoded(sign)), "UTF-8"));
250 if ( !correctChallange) {
251 fail("Should not succeed with wrong challange.");
253 assertArrayEquals(new String[] {
254 "client", CertificateRequest.DEFAULT_CN, "", Digest.SHA512.toString()
257 assertTrue(e.getMessage().startsWith("<div>Challenge mismatch"));
262 private PKCS10Attributes buildAtts(ObjectIdentifier[] ekuOIDs, GeneralNameInterface... SANs) throws IOException {
263 CertificateExtensions attributeValue = new CertificateExtensions();
264 GeneralNames names = new GeneralNames();
266 for (GeneralNameInterface name : SANs) {
267 names.add(new GeneralName(name));
269 attributeValue.set("SANs", new SubjectAlternativeNameExtension(names));
270 PKCS10Attributes atts = new PKCS10Attributes(new PKCS10Attribute[] {
271 new PKCS10Attribute(PKCS9Attribute.EXTENSION_REQUEST_OID, attributeValue)
273 ExtendedKeyUsageExtension eku = new ExtendedKeyUsageExtension(//
274 new Vector<>(Arrays.<ObjectIdentifier>asList(ekuOIDs)));
275 attributeValue.set("eku", eku);
279 private final URL ncert = new URL("https://" + getServerName() + CertificateAdd.PATH);
281 private String[] fillOutForm(String pem) throws IOException {
282 HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
283 uc.setRequestProperty("Cookie", cookie);
285 return fillOutFormDirect(pem);
289 private String[] fillOutFormDirect(String pem) throws IOException {
291 HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
292 uc.setRequestProperty("Cookie", cookie);
293 uc.setDoOutput(true);
294 uc.getOutputStream().write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" + pem).getBytes("UTF-8"));
295 uc.getOutputStream().flush();
297 return extractFormData(uc);
300 private String[] extractFormData(HttpURLConnection uc) throws IOException, Error {
301 String result = IOUtils.readURL(uc);
302 if (result.contains("<div class='formError'>")) {
303 String s = fetchStartErrorMessage(result);
307 String profileKey = extractPattern(result, Pattern.compile("<option value=\"([^\"]*)\" selected>"));
308 String resultingCN = extractPattern(result, Pattern.compile("<input [^>]*name='CN' [^>]*value='([^']*)'/>"));
309 String txt = extractPattern(result, Pattern.compile("<textarea [^>]*name='SANs' [^>]*>([^<]*)</textarea>"));
310 String md = extractPattern(result, Pattern.compile("<input type=\"radio\" [^>]*name=\"hash_alg\" value=\"([^\"]*)\" checked='checked'/>"));
311 return new String[] {
312 profileKey, resultingCN, txt, md
316 private String extractPattern(String result, Pattern p) {
317 Matcher m = p.matcher(result);
318 assertTrue(m.find());
319 String resultingCN = m.group(1);