]> WPIA git - gigi.git/blob - tests/org/cacert/gigi/testUtils/ManagedTest.java
[test-config] FIX: the ssl-pinger+ add various tests for that.
[gigi.git] / tests / org / cacert / gigi / testUtils / ManagedTest.java
1 package org.cacert.gigi.testUtils;
2
3 import static org.junit.Assert.*;
4
5 import java.io.BufferedReader;
6 import java.io.DataOutputStream;
7 import java.io.File;
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;
20 import java.net.URL;
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;
40
41 import javax.net.ssl.HttpsURLConnection;
42 import javax.net.ssl.KeyManager;
43 import javax.net.ssl.SSLContext;
44 import javax.net.ssl.X509KeyManager;
45
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;
62
63 import sun.security.pkcs10.PKCS10;
64 import sun.security.pkcs10.PKCS10Attributes;
65 import sun.security.x509.X500Name;
66
67 public class ManagedTest {
68
69     /**
70      * Some password that fullfills the password criteria.
71      */
72     protected static final String TEST_PASSWORD = "xvXV12°§";
73
74     private static TestEmailReciever ter;
75
76     private static Process gigi;
77
78     private static String url = "localhost:4443";
79
80     public static String getServerName() {
81         return url;
82     }
83
84     static Properties testProps = new Properties();
85
86     public static Properties getTestProps() {
87         return testProps;
88     }
89
90     static {
91         InitTruststore.run();
92         HttpURLConnection.setFollowRedirects(false);
93     }
94
95     @BeforeClass
96     public static void connectToServer() {
97         try {
98             testProps.load(new FileInputStream("config/test.properties"));
99             if ( !DatabaseConnection.isInited()) {
100                 DatabaseConnection.init(testProps);
101             }
102             purgeDatabase();
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])));
110                 return;
111             }
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");
116
117             byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
118             byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
119
120             DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts, keystore);
121             toGigi.flush();
122
123             final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
124             String line;
125             while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
126             }
127             new Thread() {
128
129                 @Override
130                 public void run() {
131                     String line;
132                     try {
133                         while ((line = br.readLine()) != null) {
134                             System.err.println(line);
135                         }
136                     } catch (IOException e) {
137                         e.printStackTrace();
138                     }
139                 }
140             }.start();
141             if (line == null) {
142                 throw new Error("Server startup failed");
143             }
144             ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
145             SimpleSigner.runSigner();
146         } catch (IOException e) {
147             throw new Error(e);
148         } catch (SQLException e1) {
149             e1.printStackTrace();
150         } catch (InterruptedException e) {
151             e.printStackTrace();
152         }
153
154     }
155
156     public static void purgeDatabase() throws SQLException, IOException {
157         System.out.print("... resetting Database");
158         long ms = System.currentTimeMillis();
159         try {
160             DatabaseManager.run(new String[] {
161                     testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"), testProps.getProperty("sql.user"), testProps.getProperty("sql.password")
162             }, true);
163         } catch (ClassNotFoundException e) {
164             e.printStackTrace();
165         }
166         System.out.println(" in " + (System.currentTimeMillis() - ms) + " ms");
167     }
168
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"));
175
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"));
184         return mainProps;
185     }
186
187     @AfterClass
188     public static void tearDownServer() {
189         String type = testProps.getProperty("type");
190         ter.destroy();
191         if (type.equals("local")) {
192             return;
193         }
194         gigi.destroy();
195         try {
196             SimpleSigner.stopSigner();
197         } catch (InterruptedException e) {
198             e.printStackTrace();
199         }
200     }
201
202     public final String uniq = createUniqueName();
203
204     @After
205     public void removeMails() {
206         ter.reset();
207     }
208
209     public TestMail waitForMail() {
210         try {
211             return ter.recieve();
212         } catch (InterruptedException e) {
213             throw new Error(e);
214         }
215     }
216
217     public static TestEmailReciever getMailReciever() {
218         return ter;
219     }
220
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();
225
226         String headerField = csrfConn.getHeaderField("Set-Cookie");
227         headerField = stripCookie(headerField);
228
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);
234         return d;
235     }
236
237     public static String fetchStartErrorMessage(String d) throws IOException {
238         String formFail = "<div class='formError'>";
239         int idx = d.indexOf(formFail);
240         if (idx == -1) {
241             return null;
242         }
243         String startError = d.substring(idx + formFail.length(), idx + 100).trim();
244         return startError;
245     }
246
247     public static void registerUser(String firstName, String lastName, String email, String password) {
248         try {
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));
251             assertNull(data);
252         } catch (UnsupportedEncodingException e) {
253             throw new Error(e);
254         } catch (IOException e) {
255             throw new Error(e);
256         }
257     }
258
259     public static int createVerifiedUser(String firstName, String lastName, String email, String password) {
260         registerUser(firstName, lastName, email, password);
261         try {
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();
267             ;
268             PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
269             ps.setString(1, email);
270             ResultSet rs = ps.executeQuery();
271             if (rs.next()) {
272                 return rs.getInt(1);
273             }
274             throw new Error();
275         } catch (InterruptedException e) {
276             throw new Error(e);
277         } catch (IOException e) {
278             throw new Error(e);
279         } catch (SQLException e) {
280             throw new Error(e);
281         }
282     }
283
284     /**
285      * Creates a new user with 100 Assurance points given by an (invalid)
286      * assurance.
287      * 
288      * @param firstName
289      *            the first name
290      * @param lastName
291      *            the last name
292      * @param email
293      *            the email
294      * @param password
295      *            the password
296      * @return a new userid.
297      */
298     public static int createAssuranceUser(String firstName, String lastName, String email, String password) {
299         int uid = createVerifiedUser(firstName, lastName, email, password);
300         try {
301             PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
302             ps.setInt(1, uid);
303             ps.setInt(2, 0);
304             ps.execute();
305             ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
306             ps.setInt(1, uid);
307             ps.setInt(2, uid);
308             ps.execute();
309
310         } catch (SQLException e) {
311             throw new Error(e);
312         }
313         return uid;
314     }
315
316     static int count = 0;
317
318     public static String createUniqueName() {
319         return "test" + System.currentTimeMillis() + "a" + (count++) + "u";
320     }
321
322     private static String stripCookie(String headerField) {
323         return headerField.substring(0, headerField.indexOf(';'));
324     }
325
326     public static final String SECURE_REFERENCE = MyDetails.PATH;
327
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;
333     }
334
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());
342         os.flush();
343         String headerField = huc.getHeaderField("Set-Cookie");
344         return stripCookie(headerField);
345     }
346
347     public static String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException, KeyManagementException, IOException, MalformedURLException {
348
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"));
354         } else {
355             return null;
356         }
357     }
358
359     public static void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {
360         KeyManager km = new X509KeyManager() {
361
362             @Override
363             public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
364                 return "client";
365             }
366
367             @Override
368             public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
369                 return null;
370             }
371
372             @Override
373             public X509Certificate[] getCertificateChain(String arg0) {
374                 return new X509Certificate[] {
375                     ce
376                 };
377             }
378
379             @Override
380             public String[] getClientAliases(String arg0, Principal[] arg1) {
381                 return new String[] {
382                     "client"
383                 };
384             }
385
386             @Override
387             public PrivateKey getPrivateKey(String arg0) {
388                 if (arg0.equals("client")) {
389                     return pk;
390                 }
391                 return null;
392             }
393
394             @Override
395             public String[] getServerAliases(String arg0, Principal[] arg1) {
396                 return new String[] {
397                     "client"
398                 };
399             }
400         };
401         SSLContext sc = SSLContext.getInstance("TLS");
402         sc.init(new KeyManager[] {
403             km
404         }, null, null);
405         if (connection instanceof HttpsURLConnection) {
406             ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
407         }
408     }
409
410     public static String getCSRF(URLConnection u) throws IOException {
411         return getCSRF(u, 0);
412     }
413
414     public static String getCSRF(URLConnection u, int formIndex) throws IOException {
415         String content = IOUtils.readURL(u);
416         return getCSRF(formIndex, content);
417     }
418
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++) {
423             if ( !m.find()) {
424                 throw new Error("No CSRF Token");
425             }
426         }
427         return m.group(1);
428     }
429
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");
435         if (f.exists()) {
436             try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
437                 keyPair = (KeyPair) ois.readObject();
438             } catch (ClassNotFoundException e) {
439                 e.printStackTrace();
440             } catch (IOException e) {
441                 e.printStackTrace();
442             }
443         } else {
444             keyPair = kpg.generateKeyPair();
445             try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
446                 oos.writeObject(keyPair);
447                 oos.close();
448             } catch (IOException e) {
449                 e.printStackTrace();
450             }
451         }
452         return keyPair;
453     }
454
455     public static String generatePEMCSR(KeyPair kp, String dn) throws GeneralSecurityException, IOException {
456         return generatePEMCSR(kp, dn, new PKCS10Attributes());
457     }
458
459     public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts) throws GeneralSecurityException, IOException {
460         return generatePEMCSR(kp, dn, atts, "SHA256WithRSA");
461     }
462
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());
469     }
470
471     public static String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException, UnsupportedEncodingException, IOException {
472         return executeBasicWebInteraction(cookie, path, query, 0);
473     }
474
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);
479
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") + "&" //
485         + query//
486         ).getBytes());
487         os.flush();
488         String error = fetchStartErrorMessage(IOUtils.readURL(uc));
489         return error;
490     }
491
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);
498         adrr.verify(hash);
499         getMailReciever().clearMails();
500         return adrr;
501     }
502
503     public static URLConnection cookie(URLConnection openConnection, String cookie) {
504         openConnection.setRequestProperty("Cookie", cookie);
505         return openConnection;
506     }
507
508 }