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