]> WPIA git - gigi.git/blobdiff - tests/org/cacert/gigi/pages/account/TestCertificateAdd.java
Move email/certs/mail to their own packages
[gigi.git] / tests / org / cacert / gigi / pages / account / TestCertificateAdd.java
index 9888b6a057f0c0517295d9022c3cb268eaa92aa3..9adf7e73fdfa6e7289615c925fc1d4df6f1740ba 100644 (file)
@@ -1,25 +1,42 @@
 package org.cacert.gigi.pages.account;
 
 import static org.junit.Assert.*;
+import static org.hamcrest.CoreMatchers.*;
 
+import java.io.ByteArrayInputStream;
 import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
 import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
 import java.net.URL;
+import java.net.URLConnection;
 import java.net.URLEncoder;
 import java.security.GeneralSecurityException;
 import java.security.KeyPair;
 import java.security.Signature;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.text.SimpleDateFormat;
 import java.util.Arrays;
 import java.util.Base64;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.TimeZone;
 import java.util.Vector;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
-import org.cacert.gigi.Digest;
-import org.cacert.gigi.User;
 import org.cacert.gigi.crypto.SPKAC;
+import org.cacert.gigi.dbObjects.Digest;
+import org.cacert.gigi.dbObjects.User;
+import org.cacert.gigi.pages.account.certs.CertificateAdd;
+import org.cacert.gigi.pages.account.certs.CertificateIssueForm;
 import org.cacert.gigi.testUtils.IOUtils;
 import org.cacert.gigi.testUtils.ManagedTest;
+import org.cacert.gigi.util.PEM;
 import org.junit.Test;
 
 import sun.security.pkcs.PKCS9Attribute;
@@ -44,6 +61,8 @@ public class TestCertificateAdd extends ManagedTest {
 
     String session = login(uniq + "@testdom.com", TEST_PASSWORD);
 
+    String csrf;
+
     public TestCertificateAdd() throws GeneralSecurityException, IOException {
         TestDomain.addDomain(session, uniq + ".tld");
 
@@ -97,19 +116,142 @@ public class TestCertificateAdd extends ManagedTest {
         testSPKAC(true);
     }
 
-    protected void testSPKAC(boolean correctChallange) throws GeneralSecurityException, IOException {
+    @Test
+    public void testIssue() throws IOException, GeneralSecurityException {
+        PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
+            CertificateIssueForm.OID_KEY_USAGE_SSL_CLIENT
+        }, new RFC822Name(uniq + "@testdom.com"));
+
+        String pem = generatePEMCSR(kp, "CN=testuser testname,email=" + uniq + "@testdom.com", atts, "SHA512WithRSA");
+
+        String[] res = fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
+        assertArrayEquals(new String[] {
+                "client", "testuser testname", "email:" + uniq + "@testdom.com\n", Digest.SHA512.toString()
+        }, res);
+
+        HttpURLConnection huc = (HttpURLConnection) ncert.openConnection();
+        huc.setRequestProperty("Cookie", session);
+        huc.setDoOutput(true);
+        OutputStream out = huc.getOutputStream();
+        out.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8")).getBytes());
+        out.write(("&profile=client&CN=testuser+testname&SANs=" + URLEncoder.encode("email:" + uniq + "@testdom.com\n", "UTF-8")).getBytes());
+        out.write(("&hash_alg=SHA512&CCA=y").getBytes());
+        URLConnection uc = authenticate(new URL(huc.getHeaderField("Location") + ".crt"));
+        String crt = IOUtils.readURL(new InputStreamReader(uc.getInputStream(), "UTF-8"));
+
+        uc = authenticate(new URL(huc.getHeaderField("Location") + ".cer"));
+        byte[] cer = IOUtils.readURL(uc.getInputStream());
+        assertArrayEquals(cer, PEM.decode("CERTIFICATE", crt));
+
+        uc = authenticate(new URL(huc.getHeaderField("Location") + ".cer?install"));
+        byte[] cer2 = IOUtils.readURL(uc.getInputStream());
+        assertArrayEquals(cer, cer2);
+        assertEquals("application/x-x509-user-cert", uc.getHeaderField("Content-type"));
+
+        uc = authenticate(new URL(huc.getHeaderField("Location")));
+        String gui = IOUtils.readURL(uc);
+        assertThat(gui, containsString("clientAuth"));
+        assertThat(gui, containsString("CN=testuser testname"));
+        assertThat(gui, containsString("SHA512withRSA"));
+        assertThat(gui, containsString("RFC822Name: " + uniq + "@testdom.com"));
+
+    }
+
+    @Test
+    public void testValidityPeriodCalendar() throws IOException, GeneralSecurityException {
+        testCertificateValidityRelative(Calendar.YEAR, 2, "2y", true);
+        testCertificateValidityRelative(Calendar.YEAR, 1, "1y", true);
+        testCertificateValidityRelative(Calendar.MONTH, 3, "3m", true);
+        testCertificateValidityRelative(Calendar.MONTH, 7, "7m", true);
+        testCertificateValidityRelative(Calendar.MONTH, 13, "13m", true);
+
+        testCertificateValidityRelative(Calendar.MONTH, 13, "-1m", false);
+    }
+
+    @Test
+    public void testValidityPeriodWhishStart() throws IOException, GeneralSecurityException {
+        long now = System.currentTimeMillis();
+        final long MS_PER_DAY = 24 * 60 * 60 * 1000;
+        now -= now % MS_PER_DAY;
+        now += MS_PER_DAY;
+        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
+        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
+
+        Date start = new Date(now);
+        Date end = new Date(now + MS_PER_DAY * 10);
+        X509Certificate res = createCertWithValidity("&validFrom=" + sdf.format(start) + "&validity=" + sdf.format(end));
+        assertEquals(start, res.getNotBefore());
+        assertEquals(end, res.getNotAfter());
+    }
+
+    private void testCertificateValidityRelative(int field, int amount, String length, boolean shouldsucceed) throws IOException, GeneralSecurityException, UnsupportedEncodingException, MalformedURLException, CertificateException {
+        X509Certificate parsed = createCertWithValidity("&validFrom=now&validity=" + length);
+        if (parsed == null) {
+            assertTrue( !shouldsucceed);
+            return;
+        } else {
+            assertTrue(shouldsucceed);
+        }
+
+        long now = System.currentTimeMillis();
+        Date start = parsed.getNotBefore();
+        Date end = parsed.getNotAfter();
+        Calendar c = Calendar.getInstance();
+        c.setTimeZone(TimeZone.getTimeZone("UTC"));
+        c.setTime(start);
+        c.add(field, amount);
+        assertTrue(Math.abs(start.getTime() - now) < 10000);
+        assertEquals(c.getTime(), end);
+    }
+
+    private X509Certificate createCertWithValidity(String validity) throws IOException, GeneralSecurityException, UnsupportedEncodingException, MalformedURLException, CertificateException {
+        PKCS10Attributes atts = buildAtts(new ObjectIdentifier[] {
+            CertificateIssueForm.OID_KEY_USAGE_SSL_CLIENT
+        }, new RFC822Name(uniq + "@testdom.com"));
+
+        String pem = generatePEMCSR(kp, "CN=testuser testname", atts, "SHA512WithRSA");
+        fillOutForm("CSR=" + URLEncoder.encode(pem, "UTF-8"));
+
+        HttpURLConnection huc = (HttpURLConnection) ncert.openConnection();
+        huc.setRequestProperty("Cookie", session);
+        huc.setDoOutput(true);
+        OutputStream out = huc.getOutputStream();
+        out.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8")).getBytes());
+        out.write(("&profile=client&CN=testuser+testname&SANs=" + URLEncoder.encode("email:" + uniq + "@testdom.com\n", "UTF-8")).getBytes());
+        out.write(("&hash_alg=SHA512&CCA=y&").getBytes());
+        out.write(validity.getBytes());
+
+        String certurl = huc.getHeaderField("Location");
+        if (certurl == null) {
+            return null;
+        }
+        URLConnection uc = authenticate(new URL(certurl + ".crt"));
+        String crt = IOUtils.readURL(new InputStreamReader(uc.getInputStream(), "UTF-8"));
+
+        CertificateFactory cf = CertificateFactory.getInstance("X.509");
+        X509Certificate parsed = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(crt.getBytes()));
+        return parsed;
+    }
+
+    private URLConnection authenticate(URL url) throws IOException {
+        URLConnection uc = url.openConnection();
+        uc.setRequestProperty("Cookie", session);
+        return uc;
+    }
+
+    protected String testSPKAC(boolean correctChallange) throws GeneralSecurityException, IOException {
         HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
         uc.setRequestProperty("Cookie", session);
         String s = IOUtils.readURL(uc);
 
-        String csrf = extractPattern(s, Pattern.compile("<input [^>]*name='csrf' [^>]*value='([^']*)'>"));
+        csrf = extractPattern(s, Pattern.compile("<input [^>]*name='csrf' [^>]*value='([^']*)'>"));
         String challenge = extractPattern(s, Pattern.compile("<keygen [^>]*name=\"SPKAC\" [^>]*challenge=\"([^\"]*)\"/>"));
 
         SPKAC spk = new SPKAC((X509Key) kp.getPublic(), challenge + (correctChallange ? "" : "b"));
         Signature sign = Signature.getInstance("SHA512WithRSA");
         sign.initSign(kp.getPrivate());
         try {
-            String[] res = fillOutForm(csrf, "SPKAC=" + URLEncoder.encode(Base64.getEncoder().encodeToString(spk.getEncoded(sign)), "UTF-8"));
+            String[] res = fillOutFormDirect("SPKAC=" + URLEncoder.encode(Base64.getEncoder().encodeToString(spk.getEncoded(sign)), "UTF-8"));
             if ( !correctChallange) {
                 fail("Should not succeed with wrong challange.");
             }
@@ -119,6 +261,7 @@ public class TestCertificateAdd extends ManagedTest {
         } catch (Error e) {
             assertTrue(e.getMessage().startsWith("<div>Challenge mismatch"));
         }
+        return csrf;
     }
 
     private PKCS10Attributes buildAtts(ObjectIdentifier[] ekuOIDs, GeneralNameInterface... SANs) throws IOException {
@@ -143,12 +286,12 @@ public class TestCertificateAdd extends ManagedTest {
     private String[] fillOutForm(String pem) throws IOException {
         HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
         uc.setRequestProperty("Cookie", session);
-        String csrf = getCSRF(uc);
-        return fillOutForm(csrf, pem);
+        csrf = getCSRF(uc);
+        return fillOutFormDirect(pem);
 
     }
 
-    private String[] fillOutForm(String csrf, String pem) throws IOException {
+    private String[] fillOutFormDirect(String pem) throws IOException {
 
         HttpURLConnection uc = (HttpURLConnection) ncert.openConnection();
         uc.setRequestProperty("Cookie", session);
@@ -156,6 +299,10 @@ public class TestCertificateAdd extends ManagedTest {
         uc.getOutputStream().write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" + pem).getBytes());
         uc.getOutputStream().flush();
 
+        return extractFormData(uc);
+    }
+
+    private String[] extractFormData(HttpURLConnection uc) throws IOException, Error {
         String result = IOUtils.readURL(uc);
         if (result.contains("<div class='formError'>")) {
             String s = fetchStartErrorMessage(result);