1 package org.cacert.gigi.testUtils;
3 import static org.junit.Assert.*;
5 import java.io.BufferedReader;
6 import java.io.DataOutputStream;
8 import java.io.FileInputStream;
9 import java.io.FileOutputStream;
10 import java.io.IOException;
11 import java.io.InputStreamReader;
12 import java.io.ObjectInputStream;
13 import java.io.ObjectOutputStream;
14 import java.io.OutputStream;
15 import java.io.UnsupportedEncodingException;
16 import java.net.HttpURLConnection;
17 import java.net.InetSocketAddress;
18 import java.net.MalformedURLException;
19 import java.net.Socket;
21 import java.net.URLConnection;
22 import java.net.URLEncoder;
23 import java.nio.file.Files;
24 import java.nio.file.Paths;
25 import java.security.GeneralSecurityException;
26 import java.security.KeyManagementException;
27 import java.security.KeyPair;
28 import java.security.KeyPairGenerator;
29 import java.security.NoSuchAlgorithmException;
30 import java.security.Principal;
31 import java.security.PrivateKey;
32 import java.security.Signature;
33 import java.security.cert.X509Certificate;
34 import java.sql.PreparedStatement;
35 import java.sql.ResultSet;
36 import java.sql.SQLException;
37 import java.util.Properties;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
41 import javax.net.ssl.HttpsURLConnection;
42 import javax.net.ssl.KeyManager;
43 import javax.net.ssl.SSLContext;
44 import javax.net.ssl.X509KeyManager;
46 import org.cacert.gigi.DevelLauncher;
47 import org.cacert.gigi.EmailAddress;
48 import org.cacert.gigi.GigiApiException;
49 import org.cacert.gigi.User;
50 import org.cacert.gigi.database.DatabaseConnection;
51 import org.cacert.gigi.localisation.Language;
52 import org.cacert.gigi.pages.account.MyDetails;
53 import org.cacert.gigi.pages.main.RegisterPage;
54 import org.cacert.gigi.testUtils.TestEmailReciever.TestMail;
55 import org.cacert.gigi.util.DatabaseManager;
56 import org.cacert.gigi.util.PEM;
57 import org.cacert.gigi.util.ServerConstants;
58 import org.cacert.gigi.util.SimpleSigner;
59 import org.junit.After;
60 import org.junit.AfterClass;
61 import org.junit.BeforeClass;
63 import sun.security.pkcs10.PKCS10;
64 import sun.security.pkcs10.PKCS10Attributes;
65 import sun.security.x509.X500Name;
67 public class ManagedTest {
70 * Some password that fullfills the password criteria.
72 protected static final String TEST_PASSWORD = "xvXV12°§";
74 private static TestEmailReciever ter;
76 private static Process gigi;
78 private static String url = "localhost:4443";
80 public static String getServerName() {
84 static Properties testProps = new Properties();
86 public static Properties getTestProps() {
92 HttpURLConnection.setFollowRedirects(false);
96 public static void connectToServer() {
98 testProps.load(new FileInputStream("config/test.properties"));
99 if ( !DatabaseConnection.isInited()) {
100 DatabaseConnection.init(testProps);
103 String type = testProps.getProperty("type");
104 Properties mainProps = generateMainProps();
105 ServerConstants.init(mainProps);
106 if (type.equals("local")) {
107 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort.https");
108 String[] parts = testProps.getProperty("mail").split(":", 2);
109 ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
112 url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort.https");
113 gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
114 DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
115 System.out.println("... starting server");
117 byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
118 byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
120 DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts, keystore);
123 final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
125 while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
133 while ((line = br.readLine()) != null) {
134 System.err.println(line);
136 } catch (IOException e) {
142 throw new Error("Server startup failed");
144 ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
145 SimpleSigner.runSigner();
146 } catch (IOException e) {
148 } catch (SQLException e1) {
149 e1.printStackTrace();
150 } catch (InterruptedException e) {
156 public static void purgeDatabase() throws SQLException, IOException {
157 System.out.print("... resetting Database");
158 long ms = System.currentTimeMillis();
160 DatabaseManager.run(new String[] {
161 testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"), testProps.getProperty("sql.user"), testProps.getProperty("sql.password")
163 } catch (ClassNotFoundException e) {
166 System.out.println(" in " + (System.currentTimeMillis() - ms) + " ms");
169 private static Properties generateMainProps() {
170 Properties mainProps = new Properties();
171 mainProps.setProperty("host", "127.0.0.1");
172 mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
173 mainProps.setProperty("name.www", testProps.getProperty("name.www"));
174 mainProps.setProperty("name.static", testProps.getProperty("name.static"));
176 mainProps.setProperty("https.port", testProps.getProperty("serverPort.https"));
177 mainProps.setProperty("http.port", testProps.getProperty("serverPort.http"));
178 mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
179 mainProps.setProperty("emailProvider.port", "8473");
180 mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
181 mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
182 mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
183 mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
188 public static void tearDownServer() {
189 String type = testProps.getProperty("type");
191 if (type.equals("local")) {
196 SimpleSigner.stopSigner();
197 } catch (InterruptedException e) {
202 public final String uniq = createUniqueName();
205 public void removeMails() {
209 public TestMail waitForMail() {
211 return ter.recieve();
212 } catch (InterruptedException e) {
217 public static TestEmailReciever getMailReciever() {
221 public static String runRegister(String param) throws IOException {
222 URL regist = new URL("https://" + getServerName() + RegisterPage.PATH);
223 HttpURLConnection uc = (HttpURLConnection) regist.openConnection();
224 HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection();
226 String headerField = csrfConn.getHeaderField("Set-Cookie");
227 headerField = stripCookie(headerField);
229 String csrf = getCSRF(csrfConn);
230 uc.addRequestProperty("Cookie", headerField);
231 uc.setDoOutput(true);
232 uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes());
233 String d = IOUtils.readURL(uc);
237 public static String fetchStartErrorMessage(String d) throws IOException {
238 String formFail = "<div class='formError'>";
239 int idx = d.indexOf(formFail);
243 String startError = d.substring(idx + formFail.length(), idx + 100).trim();
247 public static void registerUser(String firstName, String lastName, String email, String password) {
249 String query = "fname=" + URLEncoder.encode(firstName, "UTF-8") + "&lname=" + URLEncoder.encode(lastName, "UTF-8") + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pword1=" + URLEncoder.encode(password, "UTF-8") + "&pword2=" + URLEncoder.encode(password, "UTF-8") + "&day=1&month=1&year=1910&cca_agree=1";
250 String data = fetchStartErrorMessage(runRegister(query));
252 } catch (UnsupportedEncodingException e) {
254 } catch (IOException e) {
259 public static int createVerifiedUser(String firstName, String lastName, String email, String password) {
260 registerUser(firstName, lastName, email, password);
262 TestMail tm = ter.recieve();
263 String verifyLink = tm.extractLink();
264 String[] parts = verifyLink.split("\\?");
265 URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
266 u.openStream().close();
268 PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
269 ps.setString(1, email);
270 ResultSet rs = ps.executeQuery();
275 } catch (InterruptedException e) {
277 } catch (IOException e) {
279 } catch (SQLException e) {
285 * Creates a new user with 100 Assurance points given by an (invalid)
296 * @return a new userid.
298 public static int createAssuranceUser(String firstName, String lastName, String email, String password) {
299 int uid = createVerifiedUser(firstName, lastName, email, password);
301 PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
305 ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
310 } catch (SQLException e) {
316 static int count = 0;
318 public static String createUniqueName() {
319 return "test" + System.currentTimeMillis() + "a" + (count++) + "u";
322 private static String stripCookie(String headerField) {
323 return headerField.substring(0, headerField.indexOf(';'));
326 public static final String SECURE_REFERENCE = MyDetails.PATH;
328 public static boolean isLoggedin(String cookie) throws IOException {
329 URL u = new URL("https://" + getServerName() + SECURE_REFERENCE);
330 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
331 huc.addRequestProperty("Cookie", cookie);
332 return huc.getResponseCode() == 200;
335 public static String login(String email, String pw) throws IOException {
336 URL u = new URL("https://" + getServerName() + "/login");
337 HttpURLConnection huc = (HttpURLConnection) u.openConnection();
338 huc.setDoOutput(true);
339 OutputStream os = huc.getOutputStream();
340 String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
341 os.write(data.getBytes());
343 String headerField = huc.getHeaderField("Set-Cookie");
344 return stripCookie(headerField);
347 public static String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException, KeyManagementException, IOException, MalformedURLException {
349 HttpURLConnection connection = (HttpURLConnection) new URL("https://" + getServerName().replaceFirst("^www.", "secure.") + "/login").openConnection();
350 authenticateClientCert(pk, ce, connection);
351 if (connection.getResponseCode() == 302) {
352 assertEquals("https://" + getServerName().replaceFirst("^www.", "secure.").replaceFirst(":443$", "") + "/", connection.getHeaderField("Location").replaceFirst(":443$", ""));
353 return stripCookie(connection.getHeaderField("Set-Cookie"));
359 public static void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {
360 KeyManager km = new X509KeyManager() {
363 public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
368 public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
373 public X509Certificate[] getCertificateChain(String arg0) {
374 return new X509Certificate[] {
380 public String[] getClientAliases(String arg0, Principal[] arg1) {
381 return new String[] {
387 public PrivateKey getPrivateKey(String arg0) {
388 if (arg0.equals("client")) {
395 public String[] getServerAliases(String arg0, Principal[] arg1) {
396 return new String[] {
401 SSLContext sc = SSLContext.getInstance("TLS");
402 sc.init(new KeyManager[] {
405 if (connection instanceof HttpsURLConnection) {
406 ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
410 public static String getCSRF(URLConnection u) throws IOException {
411 return getCSRF(u, 0);
414 public static String getCSRF(URLConnection u, int formIndex) throws IOException {
415 String content = IOUtils.readURL(u);
416 return getCSRF(formIndex, content);
419 public static String getCSRF(int formIndex, String content) throws Error {
420 Pattern p = Pattern.compile("<input type='hidden' name='csrf' value='([^']+)'>");
421 Matcher m = p.matcher(content);
422 for (int i = 0; i < formIndex + 1; i++) {
424 throw new Error("No CSRF Token");
430 public static KeyPair generateKeypair() throws GeneralSecurityException {
431 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
432 kpg.initialize(4096);
433 KeyPair keyPair = null;
434 File f = new File("testKeypair");
436 try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
437 keyPair = (KeyPair) ois.readObject();
438 } catch (ClassNotFoundException e) {
440 } catch (IOException e) {
444 keyPair = kpg.generateKeyPair();
445 try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
446 oos.writeObject(keyPair);
448 } catch (IOException e) {
455 public static String generatePEMCSR(KeyPair kp, String dn) throws GeneralSecurityException, IOException {
456 return generatePEMCSR(kp, dn, new PKCS10Attributes());
459 public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts) throws GeneralSecurityException, IOException {
460 return generatePEMCSR(kp, dn, atts, "SHA256WithRSA");
463 public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts, String signature) throws GeneralSecurityException, IOException {
464 PKCS10 p10 = new PKCS10(kp.getPublic(), atts);
465 Signature s = Signature.getInstance(signature);
466 s.initSign(kp.getPrivate());
467 p10.encodeAndSign(new X500Name(dn), s);
468 return PEM.encode("CERTIFICATE REQUEST", p10.getEncoded());
471 public static String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException, UnsupportedEncodingException, IOException {
472 return executeBasicWebInteraction(cookie, path, query, 0);
475 public static String executeBasicWebInteraction(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException {
476 URLConnection uc = new URL("https://" + getServerName() + path).openConnection();
477 uc.addRequestProperty("Cookie", cookie);
478 String csrf = getCSRF(uc, formIndex);
480 uc = new URL("https://" + getServerName() + path).openConnection();
481 uc.addRequestProperty("Cookie", cookie);
482 uc.setDoOutput(true);
483 OutputStream os = uc.getOutputStream();
484 os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" //
488 String error = fetchStartErrorMessage(IOUtils.readURL(uc));
492 public static EmailAddress createVerifiedEmail(User u) throws InterruptedException, GigiApiException {
493 EmailAddress adrr = new EmailAddress(createUniqueName() + "test@test.tld", u);
494 adrr.insert(Language.getInstance("en"));
495 TestMail testMail = getMailReciever().recieve();
496 assertTrue(adrr.getAddress().equals(testMail.getTo()));
497 String hash = testMail.extractLink().substring(testMail.extractLink().lastIndexOf('=') + 1);
499 getMailReciever().clearMails();
503 public static URLConnection cookie(URLConnection openConnection, String cookie) {
504 openConnection.setRequestProperty("Cookie", cookie);
505 return openConnection;