9b3a7638cd9125dbf6acea1fe6df0dbd69a01488
[gigi.git] / tests / club / wpia / gigi / pages / account / TestCertificateAdd.java
1 package club.wpia.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.Certificate;
20 import java.security.cert.CertificateException;
21 import java.security.cert.CertificateFactory;
22 import java.security.cert.X509Certificate;
23 import java.text.SimpleDateFormat;
24 import java.util.Arrays;
25 import java.util.Base64;
26 import java.util.Calendar;
27 import java.util.Date;
28 import java.util.TimeZone;
29 import java.util.Vector;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32
33 import org.junit.Test;
34
35 import club.wpia.gigi.crypto.SPKAC;
36 import club.wpia.gigi.dbObjects.CertificateOwner;
37 import club.wpia.gigi.dbObjects.Digest;
38 import club.wpia.gigi.pages.account.certs.CertificateAdd;
39 import club.wpia.gigi.pages.account.certs.CertificateRequest;
40 import club.wpia.gigi.testUtils.ClientTest;
41 import club.wpia.gigi.testUtils.IOUtils;
42 import club.wpia.gigi.util.PEM;
43 import sun.security.pkcs.PKCS7;
44 import sun.security.pkcs.PKCS9Attribute;
45 import sun.security.pkcs10.PKCS10Attribute;
46 import sun.security.pkcs10.PKCS10Attributes;
47 import sun.security.util.ObjectIdentifier;
48 import sun.security.x509.CertificateExtensions;
49 import sun.security.x509.DNSName;
50 import sun.security.x509.ExtendedKeyUsageExtension;
51 import sun.security.x509.GeneralName;
52 import sun.security.x509.GeneralNameInterface;
53 import sun.security.x509.GeneralNames;
54 import sun.security.x509.RFC822Name;
55 import sun.security.x509.SubjectAlternativeNameExtension;
56 import sun.security.x509.X509Key;
57
58 public class TestCertificateAdd extends ClientTest {
59
60     private static class OnPageError extends Error {
61
62         private static final long serialVersionUID = 1L;
63
64         public OnPageError(String page) {
65             super(page);
66         }
67     }
68
69     KeyPair kp = generateKeypair();
70
71     String csrf;
72
73     public TestCertificateAdd() throws GeneralSecurityException, IOException {
74         TestDomain.addDomain(cookie, uniq + ".tld");
75
76     }
77
78     @Test
79     public void testSimpleServer() throws IOException, GeneralSecurityException {
80         PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
81                 CertificateRequest.OID_KEY_USAGE_SSL_SERVER
82         }, new DNSName(uniq + ".tld"));
83
84         String pem = generatePEMCSR(kp, "CN=a." + uniq + ".tld", atts);
85
86         String[] res = fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
87         assertArrayEquals(new String[] {
88                 "server", CertificateRequest.DEFAULT_CN, "dns:a." + uniq + ".tld\ndns:" + uniq + ".tld\n", Digest.SHA512.toString()
89         }, res);
90     }
91
92     @Test
93     public void testSimpleMail() throws IOException, GeneralSecurityException {
94         PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
95                 CertificateRequest.OID_KEY_USAGE_EMAIL_PROTECTION
96         }, new DNSName("a." + uniq + ".tld"), new DNSName("b." + uniq + ".tld"), new RFC822Name(email));
97
98         String pem = generatePEMCSR(kp, "CN=a b", atts, "SHA384WithRSA");
99
100         String[] res = fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
101         assertArrayEquals(new String[] {
102                 "mail", "a b", "email:" + email + "\ndns:a." + uniq + ".tld\ndns:b." + uniq + ".tld\n", Digest.SHA384.toString()
103         }, res);
104     }
105
106     @Test
107     public void testSimpleClient() throws IOException, GeneralSecurityException {
108         PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
109                 CertificateRequest.OID_KEY_USAGE_SSL_CLIENT
110         }, new RFC822Name(email));
111
112         String pem = generatePEMCSR(kp, "CN=a b,email=" + email, atts, "SHA256WithRSA");
113
114         String[] res = fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
115         assertArrayEquals(new String[] {
116                 "client", "a b", "email:" + email + "\n", Digest.SHA256.toString()
117         }, res);
118     }
119
120     @Test
121     public void testSPKAC() throws GeneralSecurityException, IOException {
122         testSPKAC(false);
123         testSPKAC(true);
124     }
125
126     @Test
127     public void testIssue() throws IOException, GeneralSecurityException {
128         PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
129                 CertificateRequest.OID_KEY_USAGE_SSL_CLIENT
130         }, new RFC822Name(email));
131
132         String pem = generatePEMCSR(kp, "CN=a b,email=" + email, atts, "SHA512WithRSA");
133
134         String[] res = fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
135         assertArrayEquals(new String[] {
136                 "client", "a b", "email:" + email + "\n", Digest.SHA512.toString()
137         }, res);
138
139         HttpURLConnection huc = (HttpURLConnection) ncert.openConnection();
140         huc.setRequestProperty("Cookie", cookie);
141         huc.setDoOutput(true);
142         OutputStream out = huc.getOutputStream();
143         out.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8")).getBytes("UTF-8"));
144         out.write(("&CN=" + URLEncoder.encode(CertificateRequest.DEFAULT_CN, "UTF-8") + "&profile=client&SANs=" + URLEncoder.encode("email:" + email + "\n", "UTF-8")).getBytes("UTF-8"));
145         out.write(("&hash_alg=SHA512").getBytes("UTF-8"));
146         URLConnection uc = authenticate(new URL(huc.getHeaderField("Location") + ".crt"));
147         String crt = IOUtils.readURL(new InputStreamReader(uc.getInputStream(), "UTF-8"));
148
149         uc = authenticate(new URL(huc.getHeaderField("Location") + ".cer"));
150         byte[] cer = IOUtils.readURL(uc.getInputStream());
151         assertArrayEquals(cer, PEM.decode("CERTIFICATE", crt));
152
153         uc = authenticate(new URL(huc.getHeaderField("Location") + ".cer?install&chain"));
154         byte[] pkcs7 = IOUtils.readURL(uc.getInputStream());
155         PKCS7 p7 = new PKCS7(pkcs7);
156         byte[] sub = verifyChain(p7.getCertificates());
157         assertArrayEquals(cer, sub);
158         assertEquals("application/x-x509-user-cert", uc.getHeaderField("Content-type"));
159
160         uc = authenticate(new URL(huc.getHeaderField("Location")));
161         String gui = IOUtils.readURL(uc);
162         Pattern p = Pattern.compile("-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----");
163         Matcher m = p.matcher(gui);
164         assertTrue(m.find());
165         byte[] cert = PEM.decode("CERTIFICATE", m.group(0));
166         Certificate c = CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(cert));
167         gui = c.toString();
168         assertThat(gui, containsString("clientAuth"));
169         assertThat(gui, containsString("CN=" + CertificateRequest.DEFAULT_CN));
170         assertThat(gui, containsString("SHA512withRSA"));
171         assertThat(gui, containsString("RFC822Name: " + email));
172
173     }
174
175     private byte[] verifyChain(X509Certificate[] x509Certificates) throws GeneralSecurityException {
176         X509Certificate current = null;
177         nextCert:
178         while (true) {
179             for (int i = 0; i < x509Certificates.length; i++) {
180                 X509Certificate cert = x509Certificates[i];
181                 if (current == null) {
182                     if (cert.getSubjectX500Principal().equals(cert.getIssuerX500Principal())) {
183                         current = cert;
184                         continue nextCert;
185                     }
186                 } else {
187                     if (cert.getSubjectX500Principal().equals(cert.getIssuerX500Principal())) {
188                         continue;
189                     }
190                     if (current.getSubjectX500Principal().equals(cert.getIssuerX500Principal())) {
191                         Signature s = Signature.getInstance(cert.getSigAlgName());
192                         s.initVerify(current.getPublicKey());
193                         s.update(cert.getTBSCertificate());
194                         assertTrue(s.verify(cert.getSignature()));
195                         current = cert;
196                         continue nextCert;
197                     }
198                 }
199             }
200             assertNotNull(current);
201             return current.getEncoded();
202         }
203     }
204
205     @Test
206     public void testValidityPeriodCalendar() throws IOException, GeneralSecurityException {
207         testCertificateValidityRelative(Calendar.YEAR, 2, "2y", true);
208         testCertificateValidityRelative(Calendar.YEAR, 1, "1y", true);
209         testCertificateValidityRelative(Calendar.MONTH, 3, "3m", true);
210         testCertificateValidityRelative(Calendar.MONTH, 7, "7m", true);
211         testCertificateValidityRelative(Calendar.MONTH, 13, "13m", true);
212
213         testCertificateValidityRelative(Calendar.MONTH, 13, "-1m", false);
214     }
215
216     @Test
217     public void testValidityPeriodWhishStart() throws IOException, GeneralSecurityException {
218         long now = System.currentTimeMillis();
219         final long MS_PER_DAY = 24 * 60 * 60 * 1000;
220         now -= now % MS_PER_DAY;
221         now += MS_PER_DAY;
222         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
223         sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
224
225         Date start = new Date(now);
226         Date end = new Date(now + MS_PER_DAY * 10);
227         String validity = "&validFrom=" + sdf.format(start) + "&validity=" + sdf.format(end);
228         X509Certificate res = createCertWithValidity(validity, false);
229         assertNotNull(validity, res);
230         assertEquals(start, res.getNotBefore());
231         assertEquals(end, res.getNotAfter());
232     }
233
234     private void testCertificateValidityRelative(int field, int amount, String length, boolean shouldsucceed) throws IOException, GeneralSecurityException, UnsupportedEncodingException, MalformedURLException, CertificateException {
235         X509Certificate parsed = createCertWithValidity("&validFrom=now&validity=" + length, false);
236         if (parsed == null) {
237             assertTrue( !shouldsucceed);
238             return;
239         } else {
240             assertTrue(shouldsucceed);
241         }
242
243         long now = System.currentTimeMillis();
244         Date start = parsed.getNotBefore();
245         Date end = parsed.getNotAfter();
246         Calendar c = Calendar.getInstance();
247         c.setTimeZone(TimeZone.getTimeZone("UTC"));
248         c.setTime(start);
249         c.add(field, amount);
250         assertTrue(Math.abs(start.getTime() - now) < 10000);
251         assertEquals(c.getTime(), end);
252     }
253
254     private X509Certificate createCertWithValidity(String validity, boolean login) throws IOException, GeneralSecurityException, UnsupportedEncodingException, MalformedURLException, CertificateException {
255         PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
256                 CertificateRequest.OID_KEY_USAGE_SSL_CLIENT
257         }, new RFC822Name(email));
258
259         String pem = generatePEMCSR(kp, "CN=a b", atts, "SHA512WithRSA");
260         fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
261
262         HttpURLConnection huc = (HttpURLConnection) ncert.openConnection();
263         huc.setRequestProperty("Cookie", cookie);
264         huc.setDoOutput(true);
265         OutputStream out = huc.getOutputStream();
266         out.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8")).getBytes("UTF-8"));
267         out.write(("&profile=client&CN=" + CertificateRequest.DEFAULT_CN + "&SANs=" + URLEncoder.encode("email:" + email + "\n", "UTF-8")).getBytes("UTF-8"));
268         out.write(("&hash_alg=SHA512&").getBytes("UTF-8"));
269         if (login) {
270             out.write(("login=1&").getBytes("UTF-8"));
271         }
272         out.write(validity.getBytes("UTF-8"));
273
274         String certurl = huc.getHeaderField("Location");
275         if (certurl == null) {
276             return null;
277         }
278         URLConnection uc = authenticate(new URL(certurl + ".crt"));
279         String crt = IOUtils.readURL(new InputStreamReader(uc.getInputStream(), "UTF-8"));
280
281         CertificateFactory cf = CertificateFactory.getInstance("X.509");
282         X509Certificate parsed = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(crt.getBytes("UTF-8")));
283         return parsed;
284     }
285
286     private URLConnection authenticate(URL url) throws IOException {
287         URLConnection uc = url.openConnection();
288         uc.setRequestProperty("Cookie", cookie);
289         return uc;
290     }
291
292     protected String testSPKAC(boolean correctChallange) throws GeneralSecurityException, IOException {
293         HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
294         uc.setRequestProperty("Cookie", cookie);
295         String s = IOUtils.readURL(uc);
296
297         csrf = extractPattern(s, Pattern.compile("<input [^>]*name='csrf' [^>]*value='([^']*)'>"));
298         String challenge = extractPattern(s, Pattern.compile("<keygen [^>]*name=\"SPKAC\" [^>]*challenge=\"([^\"]*)\"/>"));
299
300         SPKAC spk = new SPKAC((X509Key) kp.getPublic(), challenge + (correctChallange ? "" : "b"));
301         Signature sign = Signature.getInstance("SHA512WithRSA");
302         sign.initSign(kp.getPrivate());
303         try {
304             String[] res = fillOutFormDirect("SPKAC=" + URLEncoder.encode(Base64.getEncoder().encodeToString(spk.getEncoded(sign)), "UTF-8"));
305             if ( !correctChallange) {
306                 fail("Should not succeed with wrong challange.");
307             }
308             assertArrayEquals(new String[] {
309                     "client", CertificateRequest.DEFAULT_CN, "", Digest.SHA512.toString()
310             }, res);
311         } catch (OnPageError e) {
312             String error = fetchStartErrorMessage(e.getMessage());
313             assertTrue(error, error.startsWith("<p>Challenge mismatch"));
314         }
315         return csrf;
316     }
317
318     private PKCS10Attributes buildAtts(ObjectIdentifier[] ekuOIDs, GeneralNameInterface... SANs) throws IOException {
319         CertificateExtensions attributeValue = new CertificateExtensions();
320         GeneralNames names = new GeneralNames();
321
322         for (GeneralNameInterface name : SANs) {
323             names.add(new GeneralName(name));
324         }
325         attributeValue.set("SANs", new SubjectAlternativeNameExtension(names));
326         PKCS10Attributes atts = new PKCS10Attributes(new PKCS10Attribute[] {
327                 new PKCS10Attribute(PKCS9Attribute.EXTENSION_REQUEST_OID, attributeValue)
328         });
329         ExtendedKeyUsageExtension eku = new ExtendedKeyUsageExtension(//
330                 new Vector<>(Arrays.<ObjectIdentifier>asList(ekuOIDs)));
331         attributeValue.set("eku", eku);
332         return atts;
333     }
334
335     private final URL ncert = new URL("https://" + getServerName() + CertificateAdd.PATH);
336
337     private String[] fillOutForm(String pem) throws IOException {
338         HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
339         uc.setRequestProperty("Cookie", cookie);
340         csrf = getCSRF(uc);
341         return fillOutFormDirect(pem);
342
343     }
344
345     private String[] fillOutFormDirect(String pem) throws IOException {
346
347         HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
348         uc.setRequestProperty("Cookie", cookie);
349         uc.setDoOutput(true);
350         uc.getOutputStream().write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" + pem).getBytes("UTF-8"));
351         uc.getOutputStream().flush();
352
353         return extractFormData(uc);
354     }
355
356     private String[] extractFormData(HttpURLConnection uc) throws IOException, Error {
357         String result = IOUtils.readURL(uc);
358         if (hasError().matches(result)) {
359             throw new OnPageError(result);
360         }
361
362         String profileKey = extractPattern(result, Pattern.compile("<option value=\"([^\"]*)\" selected>"));
363         String resultingCN = extractPattern(result, Pattern.compile("<input [^>]*name='CN' [^>]*value='([^']*)'/>"));
364         String txt = extractPattern(result, Pattern.compile("<textarea [^>]*name='SANs' [^>]*>([^<]*)</textarea>"));
365         String md = extractPattern(result, Pattern.compile("<input type=\"radio\" [^>]*name=\"hash_alg\" value=\"([^\"]*)\" checked='checked'/>"));
366         return new String[] {
367                 profileKey, resultingCN, txt, md
368         };
369     }
370
371     private String extractPattern(String result, Pattern p) {
372         Matcher m = p.matcher(result);
373         assertTrue(m.find());
374         String resultingCN = m.group(1);
375         return resultingCN;
376     }
377
378     @Test
379     public void testSetLoginEnabled() throws IOException, GeneralSecurityException {
380         X509Certificate parsedLoginNotEnabled = createCertWithValidity("&validFrom=now&validity=1m", false);
381         assertNull(CertificateOwner.getByEnabledSerial(parsedLoginNotEnabled.getSerialNumber().toString(16).toLowerCase()));
382
383         X509Certificate parsedLoginEnabled = createCertWithValidity("&validFrom=now&validity=1m", true);
384         assertEquals(u, CertificateOwner.getByEnabledSerial(parsedLoginEnabled.getSerialNumber().toString(16).toLowerCase()));
385     }
386 }