]> WPIA git - gigi.git/blob - tests/org/cacert/gigi/ping/TestSSL.java
add: Allow specific self-signed certs for ssl-tests
[gigi.git] / tests / org / cacert / gigi / ping / TestSSL.java
1 package org.cacert.gigi.ping;
2
3 import static org.junit.Assert.*;
4 import static org.junit.Assume.*;
5
6 import java.io.ByteArrayInputStream;
7 import java.io.IOException;
8 import java.net.Socket;
9 import java.net.URL;
10 import java.net.URLEncoder;
11 import java.security.GeneralSecurityException;
12 import java.security.KeyManagementException;
13 import java.security.KeyPair;
14 import java.security.NoSuchAlgorithmException;
15 import java.security.Principal;
16 import java.security.PrivateKey;
17 import java.security.SecureRandom;
18 import java.security.cert.CertificateException;
19 import java.security.cert.CertificateFactory;
20 import java.security.cert.X509Certificate;
21 import java.sql.SQLException;
22 import java.util.Arrays;
23 import java.util.Date;
24 import java.util.HashMap;
25 import java.util.LinkedList;
26 import java.util.List;
27 import java.util.regex.Matcher;
28 import java.util.regex.Pattern;
29
30 import javax.net.ssl.KeyManager;
31 import javax.net.ssl.SSLContext;
32 import javax.net.ssl.SSLServerSocket;
33 import javax.net.ssl.SSLServerSocketFactory;
34 import javax.net.ssl.TrustManager;
35 import javax.net.ssl.X509KeyManager;
36 import javax.net.ssl.X509TrustManager;
37 import javax.security.auth.x500.X500Principal;
38
39 import org.cacert.gigi.GigiApiException;
40 import org.cacert.gigi.dbObjects.Certificate;
41 import org.cacert.gigi.dbObjects.Certificate.CSRType;
42 import org.cacert.gigi.dbObjects.CertificateProfile;
43 import org.cacert.gigi.dbObjects.Digest;
44 import org.cacert.gigi.dbObjects.User;
45 import org.cacert.gigi.pages.account.domain.DomainOverview;
46 import org.cacert.gigi.testUtils.IOUtils;
47 import org.cacert.gigi.testUtils.PingTest;
48 import org.cacert.gigi.testUtils.TestEmailReceiver.TestMail;
49 import org.cacert.gigi.util.SimpleSigner;
50 import org.junit.Test;
51 import org.junit.runner.RunWith;
52 import org.junit.runners.Parameterized;
53 import org.junit.runners.Parameterized.Parameter;
54 import org.junit.runners.Parameterized.Parameters;
55
56 @RunWith(Parameterized.class)
57 public class TestSSL extends PingTest {
58
59     @Parameters(name = "self-signed = {0}")
60     public static Iterable<Object[]> genParams() throws IOException {
61         return Arrays.asList(new Object[] {
62             true
63         }, new Object[] {
64             false
65         });
66
67     }
68
69     @Parameter
70     public Boolean self = false;
71
72     public abstract static class AsyncTask<T> {
73
74         T res;
75
76         Thread runner;
77
78         Exception ex;
79
80         public T join() throws InterruptedException {
81             runner.join();
82             if (ex != null) {
83                 throw new Error(ex);
84             }
85             return res;
86         }
87
88         public void start() {
89             runner = new Thread() {
90
91                 @Override
92                 public void run() {
93                     try {
94                         res = AsyncTask.this.run();
95                     } catch (Exception e) {
96                         ex = e;
97                     }
98                 }
99             };
100             runner.start();
101         }
102
103         public abstract T run() throws Exception;
104
105     }
106
107     private KeyPair kp;
108
109     private X509Certificate c;
110
111     @Test(timeout = 70000)
112     public void sslAndMailSuccess() throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
113         testEmailAndSSL(0, 0, true);
114     }
115
116     @Test(timeout = 70000)
117     public void sslWongTypeAndMailSuccess() throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
118         testEmailAndSSL(1, 0, true);
119     }
120
121     @Test(timeout = 70000)
122     public void sslOneMissingAndMailSuccess() throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
123         testEmailAndSSL(2, 0, true);
124     }
125
126     @Test(timeout = 70000)
127     public void sslBothMissingAndMailSuccess() throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
128         testEmailAndSSL(3, 0, true);
129     }
130
131     @Test(timeout = 70000)
132     public void sslWrongTypeAndMailFail() throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
133         testEmailAndSSL(1, 1, false);
134     }
135
136     /**
137      * @param sslVariant
138      *            <ul>
139      *            <li>0= all valid</li>
140      *            <li>1= wrong type</li>
141      *            <li>2= one server missing</li>
142      *            <li>3= both servers missing</li>
143      *            </ul>
144      * @param emailVariant
145      * @param successSSL
146      * @param successMail
147      * @throws IOException
148      * @throws InterruptedException
149      * @throws SQLException
150      * @throws GeneralSecurityException
151      * @throws GigiApiException
152      */
153
154     private void testEmailAndSSL(int sslVariant, int emailVariant, boolean successMail) throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
155         String test = getTestProps().getProperty("domain.local");
156         assumeNotNull(test);
157         URL u = new URL("https://" + getServerName() + DomainOverview.PATH);
158
159         Matcher m = initailizeDomainForm(u);
160         String value = m.group(2);
161
162         if (self) {
163             createCertificateSelf(test, sslVariant == 1 ? "clientAuth" : "serverAuth", value);
164         } else {
165             createCertificate(test, CertificateProfile.getByName(sslVariant == 1 ? "client" : "server"));
166         }
167
168         final SSLServerSocket sss = createSSLServer(kp.getPrivate(), c);
169         int port = sss.getLocalPort();
170         final SSLServerSocket sss2 = createSSLServer(kp.getPrivate(), c);
171         int port2 = sss2.getLocalPort();
172         if (sslVariant == 3 || sslVariant == 2) {
173             sss2.close();
174             if (sslVariant == 3) {
175                 sss.close();
176             }
177         }
178         String content = "adddomain&newdomain=" + URLEncoder.encode(test, "UTF-8") + //
179                 "&emailType=y&email=2&SSLType=y" + //
180                 "&ssl-type-0=direct&ssl-port-0=" + port + //
181                 "&ssl-type-1=direct&ssl-port-1=" + port2 + //
182                 "&ssl-type-2=direct&ssl-port-2=" + //
183                 "&ssl-type-3=direct&ssl-port-3=" + //
184                 "&adddomain&csrf=" + csrf;
185         URL u2 = sendDomainForm(u, content);
186         boolean firstSucceeds = sslVariant != 0 && sslVariant != 2;
187         AsyncTask<Boolean> ass = new AsyncTask<Boolean>() {
188
189             @Override
190             public Boolean run() throws Exception {
191                 return acceptSSLServer(sss);
192             }
193         };
194         ass.start();
195         System.out.println(port + " and " + port2 + " ready");
196         System.err.println(port + " and " + port2 + " ready");
197         boolean accept2 = acceptSSLServer(sss2);
198         boolean accept1 = ass.join();
199         // assertTrue(firstSucceeds ^ accept1);
200         boolean secondsSucceeds = sslVariant != 0;
201         // assertTrue(secondsSucceeds ^ accept2);
202
203         TestMail mail = getMailReciever().receive();
204         if (emailVariant == 0) {
205             mail.verify();
206         }
207         waitForPings(3);
208
209         String newcontent = IOUtils.readURL(cookie(u2.openConnection(), cookie));
210         Pattern pat = Pattern.compile("<td>ssl</td>\\s*<td>success</td>");
211         Matcher matcher = pat.matcher(newcontent);
212         assertTrue(newcontent, firstSucceeds ^ matcher.find());
213         assertTrue(newcontent, secondsSucceeds ^ matcher.find());
214         assertFalse(newcontent, matcher.find());
215         pat = Pattern.compile("<td>email</td>\\s*<td>success</td>");
216         assertTrue(newcontent, !successMail ^ pat.matcher(newcontent).find());
217     }
218
219     private void createCertificate(String test, CertificateProfile profile) throws GeneralSecurityException, IOException, SQLException, InterruptedException, GigiApiException {
220         kp = generateKeypair();
221         String csr = generatePEMCSR(kp, "CN=" + test);
222         User u = User.getById(id);
223         Certificate c = new Certificate(u, u, Certificate.buildDN("CN", test), Digest.SHA256, csr, CSRType.CSR, profile);
224         c.issue(null, "2y", u).waitFor(60000);
225         this.c = c.cert();
226     }
227
228     private void createCertificateSelf(String test, String eku, String tok) throws GeneralSecurityException, IOException, SQLException, InterruptedException, GigiApiException {
229         kp = generateKeypair();
230         HashMap<String, String> name = new HashMap<>();
231         name.put("CN", "");
232         name.put("OU", tok);
233
234         Date from = new Date();
235         Date to = new Date(from.getTime() + 1000 * 60 * 60 * 2);
236         List<Certificate.SubjectAlternateName> l = new LinkedList<>();
237
238         byte[] cert = SimpleSigner.generateCert(kp.getPublic(), kp.getPrivate(), name, new X500Principal(SimpleSigner.genX500Name(name).getEncoded()), l, from, to, Digest.SHA256, eku);
239         c = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(cert));
240     }
241
242     private boolean acceptSSLServer(SSLServerSocket sss) throws IOException {
243         try (Socket s = sss.accept()) {
244             s.getOutputStream().write('b');
245             s.getOutputStream().close();
246             return true;
247         } catch (IOException e) {
248             return false;
249         }
250     }
251
252     private SSLServerSocket createSSLServer(final PrivateKey priv, final X509Certificate cert) throws Error, IOException {
253         SSLContext sc;
254         try {
255             sc = SSLContext.getInstance("SSL");
256             sc.init(new KeyManager[] {
257                 new X509KeyManager() {
258
259                     @Override
260                     public String[] getServerAliases(String keyType, Principal[] issuers) {
261                         return new String[] {
262                             "server"
263                         };
264                     }
265
266                     @Override
267                     public PrivateKey getPrivateKey(String alias) {
268                         return priv;
269                     }
270
271                     @Override
272                     public String[] getClientAliases(String keyType, Principal[] issuers) {
273                         throw new Error();
274                     }
275
276                     @Override
277                     public X509Certificate[] getCertificateChain(String alias) {
278                         return new X509Certificate[] {
279                             cert
280                         };
281                     }
282
283                     @Override
284                     public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
285                         throw new Error();
286                     }
287
288                     @Override
289                     public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
290                         return "server";
291                     }
292
293                 }
294             }, new TrustManager[] {
295                 new X509TrustManager() {
296
297                     @Override
298                     public X509Certificate[] getAcceptedIssuers() {
299                         return null;
300                     }
301
302                     @Override
303                     public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
304
305                     @Override
306                     public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
307                 }
308             }, new SecureRandom());
309         } catch (NoSuchAlgorithmException e) {
310             e.printStackTrace();
311             throw new Error(e);
312         } catch (KeyManagementException e) {
313             e.printStackTrace();
314             throw new Error(e);
315         }
316
317         SSLServerSocketFactory sssf = sc.getServerSocketFactory();
318         return (SSLServerSocket) sssf.createServerSocket(0);
319     }
320
321     public static void main(String[] args) throws Exception {
322         initEnvironment();
323         TestSSL t1 = new TestSSL();
324         t1.sslAndMailSuccess();
325         tearDownServer();
326     }
327
328 }