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