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