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;
9 import java.net.URLEncoder;
10 import java.security.GeneralSecurityException;
11 import java.security.KeyManagementException;
12 import java.security.KeyPair;
13 import java.security.NoSuchAlgorithmException;
14 import java.security.Principal;
15 import java.security.PrivateKey;
16 import java.security.SecureRandom;
17 import java.security.cert.CertificateException;
18 import java.security.cert.CertificateFactory;
19 import java.security.cert.X509Certificate;
20 import java.sql.SQLException;
21 import java.util.Arrays;
22 import java.util.Date;
23 import java.util.HashMap;
24 import java.util.LinkedList;
25 import java.util.List;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
29 import javax.net.ssl.KeyManager;
30 import javax.net.ssl.SSLContext;
31 import javax.net.ssl.SSLServerSocket;
32 import javax.net.ssl.SSLServerSocketFactory;
33 import javax.net.ssl.TrustManager;
34 import javax.net.ssl.X509KeyManager;
35 import javax.net.ssl.X509TrustManager;
36 import javax.security.auth.x500.X500Principal;
38 import org.cacert.gigi.GigiApiException;
39 import org.cacert.gigi.database.DatabaseConnection;
40 import org.cacert.gigi.database.DatabaseConnection.Link;
41 import org.cacert.gigi.dbObjects.Certificate;
42 import org.cacert.gigi.dbObjects.Certificate.CSRType;
43 import org.cacert.gigi.dbObjects.CertificateProfile;
44 import org.cacert.gigi.dbObjects.Digest;
45 import org.cacert.gigi.dbObjects.User;
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);
136 private void testEmailAndSSL(int sslVariant, int emailVariant, boolean successMail) throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
137 try (Link link = DatabaseConnection.newLink(false)) {
138 testEmailAndSSLWithLink(sslVariant, emailVariant, successMail);
145 * <li>0= all valid</li>
146 * <li>1= wrong type</li>
147 * <li>2= one server missing</li>
148 * <li>3= both servers missing</li>
150 * @param emailVariant
153 * @throws IOException
154 * @throws InterruptedException
155 * @throws SQLException
156 * @throws GeneralSecurityException
157 * @throws GigiApiException
160 private void testEmailAndSSLWithLink(int sslVariant, int emailVariant, boolean successMail) throws IOException, InterruptedException, SQLException, GeneralSecurityException, GigiApiException {
161 String test = getTestProps().getProperty("domain.local");
163 Matcher m = initailizeDomainForm();
164 String value = m.group(2);
167 createCertificateSelf(test, sslVariant == 1 ? "clientAuth" : "serverAuth", value);
169 createCertificate(test, CertificateProfile.getByName(sslVariant == 1 ? "client" : "server"));
172 final SSLServerSocket sss = createSSLServer(kp.getPrivate(), c);
173 int port = sss.getLocalPort();
174 final SSLServerSocket sss2 = createSSLServer(kp.getPrivate(), c);
175 int port2 = sss2.getLocalPort();
176 if (sslVariant == 3 || sslVariant == 2) {
178 if (sslVariant == 3) {
182 String content = "adddomain&newdomain=" + URLEncoder.encode(test, "UTF-8") + //
183 "&emailType=y&email=2&SSLType=y" + //
184 "&ssl-type-0=direct&ssl-port-0=" + port + //
185 "&ssl-type-1=direct&ssl-port-1=" + port2 + //
186 "&ssl-type-2=direct&ssl-port-2=" + //
187 "&ssl-type-3=direct&ssl-port-3=" + //
188 "&adddomain&csrf=" + csrf;
189 String p2 = sendDomainForm(content);
190 boolean firstSucceeds = sslVariant != 0 && sslVariant != 2;
191 AsyncTask<Boolean> ass = new AsyncTask<Boolean>() {
194 public Boolean run() throws Exception {
195 return acceptSSLServer(sss);
199 System.out.println(port + " and " + port2 + " ready");
200 System.err.println(port + " and " + port2 + " ready");
201 boolean accept2 = acceptSSLServer(sss2);
202 boolean accept1 = ass.join();
203 // assertTrue(firstSucceeds ^ accept1);
204 boolean secondsSucceeds = sslVariant != 0;
205 // assertTrue(secondsSucceeds ^ accept2);
207 TestMail mail = getMailReciever().receive();
208 if (emailVariant == 0) {
213 String newcontent = IOUtils.readURL(get(p2));
214 Pattern pat = Pattern.compile("<td>ssl</td>\\s*<td>success</td>");
215 Matcher matcher = pat.matcher(newcontent);
216 assertTrue(newcontent, firstSucceeds ^ matcher.find());
217 assertTrue(newcontent, secondsSucceeds ^ matcher.find());
218 assertFalse(newcontent, matcher.find());
219 pat = Pattern.compile("<td>email</td>\\s*<td>success</td>");
220 assertTrue(newcontent, !successMail ^ pat.matcher(newcontent).find());
223 private void createCertificate(String test, CertificateProfile profile) throws GeneralSecurityException, IOException, SQLException, InterruptedException, GigiApiException {
224 kp = generateKeypair();
225 String csr = generatePEMCSR(kp, "CN=" + test);
226 User u = User.getById(id);
227 Certificate c = new Certificate(u, u, Certificate.buildDN("CN", test), Digest.SHA256, csr, CSRType.CSR, profile);
228 c.issue(null, "2y", u).waitFor(60000);
232 private void createCertificateSelf(String test, String eku, String tok) throws GeneralSecurityException, IOException, SQLException, InterruptedException, GigiApiException {
233 kp = generateKeypair();
234 HashMap<String, String> name = new HashMap<>();
238 Date from = new Date();
239 Date to = new Date(from.getTime() + 1000 * 60 * 60 * 2);
240 List<Certificate.SubjectAlternateName> l = new LinkedList<>();
242 byte[] cert = SimpleSigner.generateCert(kp.getPublic(), kp.getPrivate(), name, new X500Principal(SimpleSigner.genX500Name(name).getEncoded()), l, from, to, Digest.SHA256, eku);
243 c = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(cert));
246 private boolean acceptSSLServer(SSLServerSocket sss) throws IOException {
247 try (Socket s = sss.accept()) {
248 s.getOutputStream().write('b');
249 s.getOutputStream().close();
251 } catch (IOException e) {
256 private SSLServerSocket createSSLServer(final PrivateKey priv, final X509Certificate cert) throws Error, IOException {
259 sc = SSLContext.getInstance("SSL");
260 sc.init(new KeyManager[] {
261 new X509KeyManager() {
264 public String[] getServerAliases(String keyType, Principal[] issuers) {
265 return new String[] {
271 public PrivateKey getPrivateKey(String alias) {
276 public String[] getClientAliases(String keyType, Principal[] issuers) {
281 public X509Certificate[] getCertificateChain(String alias) {
282 return new X509Certificate[] {
288 public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
293 public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
298 }, new TrustManager[] {
299 new X509TrustManager() {
302 public X509Certificate[] getAcceptedIssuers() {
307 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
310 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
312 }, new SecureRandom());
313 } catch (NoSuchAlgorithmException e) {
316 } catch (KeyManagementException e) {
321 SSLServerSocketFactory sssf = sc.getServerSocketFactory();
322 return (SSLServerSocket) sssf.createServerSocket(0);
325 public static void main(String[] args) throws Exception {
327 TestSSL t1 = new TestSSL();
328 t1.sslAndMailSuccess();