1 package org.cacert.gigi.ping;
3 import static org.junit.Assert.*;
4 import static org.junit.Assume.*;
6 import java.io.ByteArrayInputStream;
7 import java.io.IOException;
8 import java.net.Socket;
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;
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;
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;
56 @RunWith(Parameterized.class)
57 public class TestSSL extends PingTest {
59 @Parameters(name = "self-signed = {0}")
60 public static Iterable<Object[]> genParams() throws IOException {
61 return Arrays.asList(new Object[] {
70 public Boolean self = false;
72 public abstract static class AsyncTask<T> {
80 public T join() throws InterruptedException {
89 runner = new Thread() {
94 res = AsyncTask.this.run();
95 } catch (Exception e) {
103 public abstract T run() throws Exception;
109 private X509Certificate c;
111 @Test(timeout = 70000)
112 public void sslAndMailSuccess() throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
113 testEmailAndSSL(0, 0, true);
116 @Test(timeout = 70000)
117 public void sslWongTypeAndMailSuccess() throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
118 testEmailAndSSL(1, 0, true);
121 @Test(timeout = 70000)
122 public void sslOneMissingAndMailSuccess() throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
123 testEmailAndSSL(2, 0, true);
126 @Test(timeout = 70000)
127 public void sslBothMissingAndMailSuccess() throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
128 testEmailAndSSL(3, 0, true);
131 @Test(timeout = 70000)
132 public void sslWrongTypeAndMailFail() throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
133 testEmailAndSSL(1, 1, false);
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>
144 * @param emailVariant
147 * @throws IOException
148 * @throws InterruptedException
149 * @throws SQLException
150 * @throws GeneralSecurityException
151 * @throws GigiApiException
154 private void testEmailAndSSL(int sslVariant, int emailVariant, boolean successMail) throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
155 String test = getTestProps().getProperty("domain.local");
157 URL u = new URL("https://" + getServerName() + DomainOverview.PATH);
159 Matcher m = initailizeDomainForm(u);
160 String value = m.group(2);
163 createCertificateSelf(test, sslVariant == 1 ? "clientAuth" : "serverAuth", value);
165 createCertificate(test, CertificateProfile.getByName(sslVariant == 1 ? "client" : "server"));
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) {
174 if (sslVariant == 3) {
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>() {
190 public Boolean run() throws Exception {
191 return acceptSSLServer(sss);
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);
203 TestMail mail = getMailReciever().receive();
204 if (emailVariant == 0) {
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());
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);
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<>();
234 Date from = new Date();
235 Date to = new Date(from.getTime() + 1000 * 60 * 60 * 2);
236 List<Certificate.SubjectAlternateName> l = new LinkedList<>();
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));
242 private boolean acceptSSLServer(SSLServerSocket sss) throws IOException {
243 try (Socket s = sss.accept()) {
244 s.getOutputStream().write('b');
245 s.getOutputStream().close();
247 } catch (IOException e) {
252 private SSLServerSocket createSSLServer(final PrivateKey priv, final X509Certificate cert) throws Error, IOException {
255 sc = SSLContext.getInstance("SSL");
256 sc.init(new KeyManager[] {
257 new X509KeyManager() {
260 public String[] getServerAliases(String keyType, Principal[] issuers) {
261 return new String[] {
267 public PrivateKey getPrivateKey(String alias) {
272 public String[] getClientAliases(String keyType, Principal[] issuers) {
277 public X509Certificate[] getCertificateChain(String alias) {
278 return new X509Certificate[] {
284 public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
289 public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
294 }, new TrustManager[] {
295 new X509TrustManager() {
298 public X509Certificate[] getAcceptedIssuers() {
303 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
306 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
308 }, new SecureRandom());
309 } catch (NoSuchAlgorithmException e) {
312 } catch (KeyManagementException e) {
317 SSLServerSocketFactory sssf = sc.getServerSocketFactory();
318 return (SSLServerSocket) sssf.createServerSocket(0);
321 public static void main(String[] args) throws Exception {
323 TestSSL t1 = new TestSSL();
324 t1.sslAndMailSuccess();