]> WPIA git - gigi.git/blob - tests/org/cacert/gigi/pages/account/TestCertificateAdd.java
aa118973862eb2a2c0821fa83e7deaa52ce09713
[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(("&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"));
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=a b"));
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         assertEquals(start, res.getNotBefore());
179         assertEquals(end, res.getNotAfter());
180     }
181
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);
186             return;
187         } else {
188             assertTrue(shouldsucceed);
189         }
190
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"));
196         c.setTime(start);
197         c.add(field, amount);
198         assertTrue(Math.abs(start.getTime() - now) < 10000);
199         assertEquals(c.getTime(), end);
200     }
201
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));
206
207         String pem = generatePEMCSR(kp, "CN=a b", atts, "SHA512WithRSA");
208         fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
209
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"));
218
219         String certurl = huc.getHeaderField("Location");
220         if (certurl == null) {
221             return null;
222         }
223         URLConnection uc = authenticate(new URL(certurl + ".crt"));
224         String crt = IOUtils.readURL(new InputStreamReader(uc.getInputStream(), "UTF-8"));
225
226         CertificateFactory cf = CertificateFactory.getInstance("X.509");
227         X509Certificate parsed = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(crt.getBytes("UTF-8")));
228         return parsed;
229     }
230
231     private URLConnection authenticate(URL url) throws IOException {
232         URLConnection uc = url.openConnection();
233         uc.setRequestProperty("Cookie", cookie);
234         return uc;
235     }
236
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);
241
242         csrf = extractPattern(s, Pattern.compile("<input [^>]*name='csrf' [^>]*value='([^']*)'>"));
243         String challenge = extractPattern(s, Pattern.compile("<keygen [^>]*name=\"SPKAC\" [^>]*challenge=\"([^\"]*)\"/>"));
244
245         SPKAC spk = new SPKAC((X509Key) kp.getPublic(), challenge + (correctChallange ? "" : "b"));
246         Signature sign = Signature.getInstance("SHA512WithRSA");
247         sign.initSign(kp.getPrivate());
248         try {
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.");
252             }
253             assertArrayEquals(new String[] {
254                     "client", CertificateRequest.DEFAULT_CN, "", Digest.SHA512.toString()
255             }, res);
256         } catch (Error e) {
257             assertTrue(e.getMessage().startsWith("<div>Challenge mismatch"));
258         }
259         return csrf;
260     }
261
262     private PKCS10Attributes buildAtts(ObjectIdentifier[] ekuOIDs, GeneralNameInterface... SANs) throws IOException {
263         CertificateExtensions attributeValue = new CertificateExtensions();
264         GeneralNames names = new GeneralNames();
265
266         for (GeneralNameInterface name : SANs) {
267             names.add(new GeneralName(name));
268         }
269         attributeValue.set("SANs", new SubjectAlternativeNameExtension(names));
270         PKCS10Attributes atts = new PKCS10Attributes(new PKCS10Attribute[] {
271             new PKCS10Attribute(PKCS9Attribute.EXTENSION_REQUEST_OID, attributeValue)
272         });
273         ExtendedKeyUsageExtension eku = new ExtendedKeyUsageExtension(//
274                 new Vector<>(Arrays.<ObjectIdentifier>asList(ekuOIDs)));
275         attributeValue.set("eku", eku);
276         return atts;
277     }
278
279     private final URL ncert = new URL("https://" + getServerName() + CertificateAdd.PATH);
280
281     private String[] fillOutForm(String pem) throws IOException {
282         HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
283         uc.setRequestProperty("Cookie", cookie);
284         csrf = getCSRF(uc);
285         return fillOutFormDirect(pem);
286
287     }
288
289     private String[] fillOutFormDirect(String pem) throws IOException {
290
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();
296
297         return extractFormData(uc);
298     }
299
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);
304             throw new Error(s);
305         }
306
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
313         };
314     }
315
316     private String extractPattern(String result, Pattern p) {
317         Matcher m = p.matcher(result);
318         assertTrue(m.find());
319         String resultingCN = m.group(1);
320         return resultingCN;
321     }
322 }