]> WPIA git - gigi.git/blob - tests/org/cacert/gigi/pages/account/TestCertificateAdd.java
fix: several testcases to the new configuration/structure
[gigi.git] / tests / org / cacert / gigi / pages / account / TestCertificateAdd.java
1 package org.cacert.gigi.pages.account;
2
3 import static org.hamcrest.CoreMatchers.*;
4 import static org.junit.Assert.*;
5
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;
13 import java.net.URL;
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;
31
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;
40
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;
54
55 public class TestCertificateAdd extends ClientTest {
56
57     KeyPair kp = generateKeypair();
58
59     String csrf;
60
61     public TestCertificateAdd() throws GeneralSecurityException, IOException {
62         TestDomain.addDomain(cookie, uniq + ".tld");
63
64     }
65
66     @Test
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"));
71
72         String pem = generatePEMCSR(kp, "CN=a." + uniq + ".tld", atts);
73
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()
77         }, res);
78     }
79
80     @Test
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));
85
86         String pem = generatePEMCSR(kp, "CN=a b", atts, "SHA384WithRSA");
87
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()
91         }, res);
92     }
93
94     @Test
95     public void testSimpleClient() throws IOException, GeneralSecurityException {
96         PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
97             CertificateRequest.OID_KEY_USAGE_SSL_CLIENT
98         }, new RFC822Name(email));
99
100         String pem = generatePEMCSR(kp, "CN=a b,email=" + email, atts, "SHA512WithRSA");
101
102         String[] res = fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
103         assertArrayEquals(new String[] {
104                 "client", "a b", "email:" + email + "\n", Digest.SHA512.toString()
105         }, res);
106     }
107
108     @Test
109     public void testSPKAC() throws GeneralSecurityException, IOException {
110         testSPKAC(false);
111         testSPKAC(true);
112     }
113
114     @Test
115     public void testIssue() throws IOException, GeneralSecurityException {
116         PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
117             CertificateRequest.OID_KEY_USAGE_SSL_CLIENT
118         }, new RFC822Name(email));
119
120         String pem = generatePEMCSR(kp, "CN=a b,email=" + email, atts, "SHA512WithRSA");
121
122         String[] res = fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
123         assertArrayEquals(new String[] {
124                 "client", "a b", "email:" + email + "\n", Digest.SHA512.toString()
125         }, res);
126
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(("&CN=CAcert+WoT+User&profile=client&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"));
136
137         uc = authenticate(new URL(huc.getHeaderField("Location") + ".cer"));
138         byte[] cer = IOUtils.readURL(uc.getInputStream());
139         assertArrayEquals(cer, PEM.decode("CERTIFICATE", crt));
140
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"));
145
146         uc = authenticate(new URL(huc.getHeaderField("Location")));
147         String gui = IOUtils.readURL(uc);
148         assertThat(gui, containsString("clientAuth"));
149         assertThat(gui, containsString("CN=CAcert WoT User"));
150         assertThat(gui, containsString("SHA512withRSA"));
151         assertThat(gui, containsString("RFC822Name: " + email));
152
153     }
154
155     @Test
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);
162
163         testCertificateValidityRelative(Calendar.MONTH, 13, "-1m", false);
164     }
165
166     @Test
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;
171         now += MS_PER_DAY;
172         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
173         sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
174
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         assertNotNull(res);
179         assertEquals(start, res.getNotBefore());
180         assertEquals(end, res.getNotAfter());
181     }
182
183     private void testCertificateValidityRelative(int field, int amount, String length, boolean shouldsucceed) throws IOException, GeneralSecurityException, UnsupportedEncodingException, MalformedURLException, CertificateException {
184         X509Certificate parsed = createCertWithValidity("&validFrom=now&validity=" + length);
185         if (parsed == null) {
186             assertTrue( !shouldsucceed);
187             return;
188         } else {
189             assertTrue(shouldsucceed);
190         }
191
192         long now = System.currentTimeMillis();
193         Date start = parsed.getNotBefore();
194         Date end = parsed.getNotAfter();
195         Calendar c = Calendar.getInstance();
196         c.setTimeZone(TimeZone.getTimeZone("UTC"));
197         c.setTime(start);
198         c.add(field, amount);
199         assertTrue(Math.abs(start.getTime() - now) < 10000);
200         assertEquals(c.getTime(), end);
201     }
202
203     private X509Certificate createCertWithValidity(String validity) throws IOException, GeneralSecurityException, UnsupportedEncodingException, MalformedURLException, CertificateException {
204         PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
205             CertificateRequest.OID_KEY_USAGE_SSL_CLIENT
206         }, new RFC822Name(email));
207
208         String pem = generatePEMCSR(kp, "CN=a b", atts, "SHA512WithRSA");
209         fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
210
211         HttpURLConnection huc = (HttpURLConnection) ncert.openConnection();
212         huc.setRequestProperty("Cookie", cookie);
213         huc.setDoOutput(true);
214         OutputStream out = huc.getOutputStream();
215         out.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8")).getBytes("UTF-8"));
216         out.write(("&profile=client&CN=" + CertificateRequest.DEFAULT_CN + "&SANs=" + URLEncoder.encode("email:" + email + "\n", "UTF-8")).getBytes("UTF-8"));
217         out.write(("&hash_alg=SHA512&CCA=y&").getBytes("UTF-8"));
218         out.write(validity.getBytes("UTF-8"));
219
220         String certurl = huc.getHeaderField("Location");
221         if (certurl == null) {
222             return null;
223         }
224         URLConnection uc = authenticate(new URL(certurl + ".crt"));
225         String crt = IOUtils.readURL(new InputStreamReader(uc.getInputStream(), "UTF-8"));
226
227         CertificateFactory cf = CertificateFactory.getInstance("X.509");
228         X509Certificate parsed = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(crt.getBytes("UTF-8")));
229         return parsed;
230     }
231
232     private URLConnection authenticate(URL url) throws IOException {
233         URLConnection uc = url.openConnection();
234         uc.setRequestProperty("Cookie", cookie);
235         return uc;
236     }
237
238     protected String testSPKAC(boolean correctChallange) throws GeneralSecurityException, IOException {
239         HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
240         uc.setRequestProperty("Cookie", cookie);
241         String s = IOUtils.readURL(uc);
242
243         csrf = extractPattern(s, Pattern.compile("<input [^>]*name='csrf' [^>]*value='([^']*)'>"));
244         String challenge = extractPattern(s, Pattern.compile("<keygen [^>]*name=\"SPKAC\" [^>]*challenge=\"([^\"]*)\"/>"));
245
246         SPKAC spk = new SPKAC((X509Key) kp.getPublic(), challenge + (correctChallange ? "" : "b"));
247         Signature sign = Signature.getInstance("SHA512WithRSA");
248         sign.initSign(kp.getPrivate());
249         try {
250             String[] res = fillOutFormDirect("SPKAC=" + URLEncoder.encode(Base64.getEncoder().encodeToString(spk.getEncoded(sign)), "UTF-8"));
251             if ( !correctChallange) {
252                 fail("Should not succeed with wrong challange.");
253             }
254             assertArrayEquals(new String[] {
255                     "client", CertificateRequest.DEFAULT_CN, "", Digest.SHA512.toString()
256             }, res);
257         } catch (Error e) {
258             assertTrue(e.getMessage().startsWith("<div>Challenge mismatch"));
259         }
260         return csrf;
261     }
262
263     private PKCS10Attributes buildAtts(ObjectIdentifier[] ekuOIDs, GeneralNameInterface... SANs) throws IOException {
264         CertificateExtensions attributeValue = new CertificateExtensions();
265         GeneralNames names = new GeneralNames();
266
267         for (GeneralNameInterface name : SANs) {
268             names.add(new GeneralName(name));
269         }
270         attributeValue.set("SANs", new SubjectAlternativeNameExtension(names));
271         PKCS10Attributes atts = new PKCS10Attributes(new PKCS10Attribute[] {
272             new PKCS10Attribute(PKCS9Attribute.EXTENSION_REQUEST_OID, attributeValue)
273         });
274         ExtendedKeyUsageExtension eku = new ExtendedKeyUsageExtension(//
275                 new Vector<>(Arrays.<ObjectIdentifier>asList(ekuOIDs)));
276         attributeValue.set("eku", eku);
277         return atts;
278     }
279
280     private final URL ncert = new URL("https://" + getServerName() + CertificateAdd.PATH);
281
282     private String[] fillOutForm(String pem) throws IOException {
283         HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
284         uc.setRequestProperty("Cookie", cookie);
285         csrf = getCSRF(uc);
286         return fillOutFormDirect(pem);
287
288     }
289
290     private String[] fillOutFormDirect(String pem) throws IOException {
291
292         HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
293         uc.setRequestProperty("Cookie", cookie);
294         uc.setDoOutput(true);
295         uc.getOutputStream().write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" + pem).getBytes("UTF-8"));
296         uc.getOutputStream().flush();
297
298         return extractFormData(uc);
299     }
300
301     private String[] extractFormData(HttpURLConnection uc) throws IOException, Error {
302         String result = IOUtils.readURL(uc);
303         if (result.contains("<div class='formError'>")) {
304             String s = fetchStartErrorMessage(result);
305             throw new Error(s);
306         }
307
308         String profileKey = extractPattern(result, Pattern.compile("<option value=\"([^\"]*)\" selected>"));
309         String resultingCN = extractPattern(result, Pattern.compile("<input [^>]*name='CN' [^>]*value='([^']*)'/>"));
310         String txt = extractPattern(result, Pattern.compile("<textarea [^>]*name='SANs' [^>]*>([^<]*)</textarea>"));
311         String md = extractPattern(result, Pattern.compile("<input type=\"radio\" [^>]*name=\"hash_alg\" value=\"([^\"]*)\" checked='checked'/>"));
312         return new String[] {
313                 profileKey, resultingCN, txt, md
314         };
315     }
316
317     private String extractPattern(String result, Pattern p) {
318         Matcher m = p.matcher(result);
319         assertTrue(m.find());
320         String resultingCN = m.group(1);
321         return resultingCN;
322     }
323 }