Merge "Suggestions to enhance the SQL call pattern."
[gigi.git] / tests / org / cacert / gigi / ping / TestSSL.java
index a9aa73b1bb61e7fea945b94c579cc7fe90f5935b..ab41ca510a11014f5adaefb5dda3469c533cb4a1 100644 (file)
@@ -3,9 +3,9 @@ package org.cacert.gigi.ping;
 import static org.junit.Assert.*;
 import static org.junit.Assume.*;
 
+import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.net.Socket;
-import java.net.URL;
 import java.net.URLEncoder;
 import java.security.GeneralSecurityException;
 import java.security.KeyManagementException;
@@ -15,8 +15,14 @@ import java.security.Principal;
 import java.security.PrivateKey;
 import java.security.SecureRandom;
 import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
 import java.sql.SQLException;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -27,24 +33,80 @@ import javax.net.ssl.SSLServerSocketFactory;
 import javax.net.ssl.TrustManager;
 import javax.net.ssl.X509KeyManager;
 import javax.net.ssl.X509TrustManager;
+import javax.security.auth.x500.X500Principal;
 
 import org.cacert.gigi.GigiApiException;
+import org.cacert.gigi.database.DatabaseConnection;
+import org.cacert.gigi.database.DatabaseConnection.Link;
 import org.cacert.gigi.dbObjects.Certificate;
 import org.cacert.gigi.dbObjects.Certificate.CSRType;
 import org.cacert.gigi.dbObjects.CertificateProfile;
+import org.cacert.gigi.dbObjects.Digest;
 import org.cacert.gigi.dbObjects.User;
-import org.cacert.gigi.pages.account.domain.DomainOverview;
 import org.cacert.gigi.testUtils.IOUtils;
 import org.cacert.gigi.testUtils.PingTest;
-import org.cacert.gigi.testUtils.TestEmailReciever.TestMail;
-import org.junit.Assert;
+import org.cacert.gigi.testUtils.TestEmailReceiver.TestMail;
+import org.cacert.gigi.util.SimpleSigner;
 import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameter;
+import org.junit.runners.Parameterized.Parameters;
 
+@RunWith(Parameterized.class)
 public class TestSSL extends PingTest {
 
+    @Parameters(name = "self-signed = {0}")
+    public static Iterable<Object[]> genParams() throws IOException {
+        return Arrays.asList(new Object[] {
+            true
+        }, new Object[] {
+            false
+        });
+
+    }
+
+    @Parameter
+    public Boolean self = false;
+
+    public abstract static class AsyncTask<T> {
+
+        T res;
+
+        Thread runner;
+
+        Exception ex;
+
+        public T join() throws InterruptedException {
+            runner.join();
+            if (ex != null) {
+                throw new Error(ex);
+            }
+            return res;
+        }
+
+        public void start() {
+            runner = new Thread() {
+
+                @Override
+                public void run() {
+                    try {
+                        res = AsyncTask.this.run();
+                    } catch (Exception e) {
+                        ex = e;
+                    }
+                }
+            };
+            runner.start();
+        }
+
+        public abstract T run() throws Exception;
+
+    }
+
     private KeyPair kp;
 
-    private Certificate c;
+    private X509Certificate c;
 
     @Test(timeout = 70000)
     public void sslAndMailSuccess() throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
@@ -71,6 +133,12 @@ public class TestSSL extends PingTest {
         testEmailAndSSL(1, 1, false);
     }
 
+    private void testEmailAndSSL(int sslVariant, int emailVariant, boolean successMail) throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
+        try (Link link = DatabaseConnection.newLink(false)) {
+            testEmailAndSSLWithLink(sslVariant, emailVariant, successMail);
+        }
+    }
+
     /**
      * @param sslVariant
      *            <ul>
@@ -89,17 +157,21 @@ public class TestSSL extends PingTest {
      * @throws GigiApiException
      */
 
-    private void testEmailAndSSL(int sslVariant, int emailVariant, boolean successMail) throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
+    private void testEmailAndSSLWithLink(int sslVariant, int emailVariant, boolean successMail) throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
         String test = getTestProps().getProperty("domain.local");
         assumeNotNull(test);
-        URL u = new URL("https://" + getServerName() + DomainOverview.PATH);
+        Matcher m = initailizeDomainForm();
+        String value = m.group(2);
 
-        initailizeDomainForm(u);
+        if (self) {
+            createCertificateSelf(test, sslVariant == 1 ? "clientAuth" : "serverAuth", value);
+        } else {
+            createCertificate(test, CertificateProfile.getByName(sslVariant == 1 ? "client" : "server"));
+        }
 
-        createCertificate(test, CertificateProfile.getByName(sslVariant == 1 ? "client" : "server"));
-        SSLServerSocket sss = createSSLServer(kp.getPrivate(), c.cert());
+        final SSLServerSocket sss = createSSLServer(kp.getPrivate(), c);
         int port = sss.getLocalPort();
-        SSLServerSocket sss2 = createSSLServer(kp.getPrivate(), c.cert());
+        final SSLServerSocket sss2 = createSSLServer(kp.getPrivate(), c);
         int port2 = sss2.getLocalPort();
         if (sslVariant == 3 || sslVariant == 2) {
             sss2.close();
@@ -107,27 +179,38 @@ public class TestSSL extends PingTest {
                 sss.close();
             }
         }
-        String content = "newdomain=" + URLEncoder.encode(test, "UTF-8") + //
+        String content = "adddomain&newdomain=" + URLEncoder.encode(test, "UTF-8") + //
                 "&emailType=y&email=2&SSLType=y" + //
                 "&ssl-type-0=direct&ssl-port-0=" + port + //
                 "&ssl-type-1=direct&ssl-port-1=" + port2 + //
                 "&ssl-type-2=direct&ssl-port-2=" + //
                 "&ssl-type-3=direct&ssl-port-3=" + //
                 "&adddomain&csrf=" + csrf;
-        URL u2 = sendDomainForm(u, content);
+        String p2 = sendDomainForm(content);
         boolean firstSucceeds = sslVariant != 0 && sslVariant != 2;
-        assertTrue(firstSucceeds ^ acceptSSLServer(sss));
+        AsyncTask<Boolean> ass = new AsyncTask<Boolean>() {
+
+            @Override
+            public Boolean run() throws Exception {
+                return acceptSSLServer(sss);
+            }
+        };
+        ass.start();
+        System.out.println(port + " and " + port2 + " ready");
+        System.err.println(port + " and " + port2 + " ready");
+        boolean accept2 = acceptSSLServer(sss2);
+        boolean accept1 = ass.join();
+        // assertTrue(firstSucceeds ^ accept1);
         boolean secondsSucceeds = sslVariant != 0;
-        assertTrue(secondsSucceeds ^ acceptSSLServer(sss2));
+        // assertTrue(secondsSucceeds ^ accept2);
 
-        TestMail mail = getMailReciever().recieve();
+        TestMail mail = getMailReciever().receive();
         if (emailVariant == 0) {
-            Assert.assertNotNull(mail);
             mail.verify();
         }
         waitForPings(3);
 
-        String newcontent = IOUtils.readURL(cookie(u2.openConnection(), cookie));
+        String newcontent = IOUtils.readURL(get(p2));
         Pattern pat = Pattern.compile("<td>ssl</td>\\s*<td>success</td>");
         Matcher matcher = pat.matcher(newcontent);
         assertTrue(newcontent, firstSucceeds ^ matcher.find());
@@ -140,8 +223,24 @@ public class TestSSL extends PingTest {
     private void createCertificate(String test, CertificateProfile profile) throws GeneralSecurityException, IOException, SQLException, InterruptedException, GigiApiException {
         kp = generateKeypair();
         String csr = generatePEMCSR(kp, "CN=" + test);
-        c = new Certificate(User.getById(id), Certificate.buildDN("CN", test), "sha256", csr, CSRType.CSR, profile);
-        c.issue(null, "2y").waitFor(60000);
+        User u = User.getById(id);
+        Certificate c = new Certificate(u, u, Certificate.buildDN("CN", test), Digest.SHA256, csr, CSRType.CSR, profile);
+        c.issue(null, "2y", u).waitFor(60000);
+        this.c = c.cert();
+    }
+
+    private void createCertificateSelf(String test, String eku, String tok) throws GeneralSecurityException, IOException, SQLException, InterruptedException, GigiApiException {
+        kp = generateKeypair();
+        HashMap<String, String> name = new HashMap<>();
+        name.put("CN", "");
+        name.put("OU", tok);
+
+        Date from = new Date();
+        Date to = new Date(from.getTime() + 1000 * 60 * 60 * 2);
+        List<Certificate.SubjectAlternateName> l = new LinkedList<>();
+
+        byte[] cert = SimpleSigner.generateCert(kp.getPublic(), kp.getPrivate(), name, new X500Principal(SimpleSigner.genX500Name(name).getEncoded()), l, from, to, Digest.SHA256, eku);
+        c = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(cert));
     }
 
     private boolean acceptSSLServer(SSLServerSocket sss) throws IOException {
@@ -223,4 +322,11 @@ public class TestSSL extends PingTest {
         return (SSLServerSocket) sssf.createServerSocket(0);
     }
 
+    public static void main(String[] args) throws Exception {
+        initEnvironment();
+        TestSSL t1 = new TestSSL();
+        t1.sslAndMailSuccess();
+        tearDownServer();
+    }
+
 }