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