1 package club.wpia.gigi.testUtils;
3 import static org.junit.Assert.*;
6 import java.io.FileInputStream;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.io.ObjectInputStream;
10 import java.io.ObjectOutputStream;
11 import java.math.BigInteger;
12 import java.security.GeneralSecurityException;
13 import java.security.KeyFactory;
14 import java.security.KeyPair;
15 import java.security.KeyPairGenerator;
16 import java.security.PrivateKey;
17 import java.security.PublicKey;
18 import java.security.SecureRandom;
19 import java.security.Signature;
20 import java.security.spec.RSAPrivateKeySpec;
21 import java.security.spec.RSAPublicKeySpec;
22 import java.sql.SQLException;
23 import java.text.SimpleDateFormat;
24 import java.util.Calendar;
25 import java.util.Date;
26 import java.util.Properties;
27 import java.util.Random;
28 import java.util.TimeZone;
29 import java.util.regex.Matcher;
30 import java.util.regex.Pattern;
32 import org.junit.AfterClass;
33 import org.junit.BeforeClass;
35 import club.wpia.gigi.Gigi;
36 import club.wpia.gigi.GigiApiException;
37 import club.wpia.gigi.database.DatabaseConnection;
38 import club.wpia.gigi.database.DatabaseConnection.Link;
39 import club.wpia.gigi.database.GigiPreparedStatement;
40 import club.wpia.gigi.database.SQLFileManager.ImportType;
41 import club.wpia.gigi.dbObjects.CATS.CATSType;
42 import club.wpia.gigi.dbObjects.CertificateProfile;
43 import club.wpia.gigi.dbObjects.Domain;
44 import club.wpia.gigi.dbObjects.DomainPingType;
45 import club.wpia.gigi.dbObjects.User;
46 import club.wpia.gigi.passwords.PasswordStrengthChecker;
47 import club.wpia.gigi.testUtils.TestEmailReceiver.TestMail;
48 import club.wpia.gigi.util.DatabaseManager;
49 import club.wpia.gigi.util.DomainAssessment;
50 import club.wpia.gigi.util.Notary;
51 import club.wpia.gigi.util.PEM;
52 import club.wpia.gigi.util.PasswordHash;
53 import club.wpia.gigi.util.ServerConstants;
54 import club.wpia.gigi.util.TimeConditions;
55 import sun.security.pkcs10.PKCS10;
56 import sun.security.pkcs10.PKCS10Attributes;
57 import sun.security.x509.X500Name;
60 * Base class for a Testsuite that makes use of the config variables that define
63 public abstract class ConfiguredTest {
65 static Properties testProps = new Properties();
67 public static Properties getTestProps() {
71 private static boolean envInited = false;
74 * Some password that fulfills the password criteria.
76 public static final String TEST_PASSWORD = "xvXV12°§";
78 public static final String DIFFICULT_CHARS = "ÜÖÄß𐀀";
81 public static void initEnvironmentHook() throws IOException {
85 private static Link l;
87 public static Properties initEnvironment() throws IOException {
88 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
91 synchronized (ConfiguredTest.class) {
93 l = DatabaseConnection.newLink(false);
96 } catch (InterruptedException e) {
99 return generateProps();
102 try (FileInputStream inStream = new FileInputStream("config/test.properties")) {
103 testProps.load(inStream);
105 Properties props = generateProps();
106 ServerConstants.init(props);
107 TimeConditions.init(props);
108 DomainAssessment.init(props);
109 PasswordHash.init(props);
110 Gigi.setPasswordChecker(new PasswordStrengthChecker());
112 if ( !DatabaseConnection.isInited()) {
113 DatabaseConnection.init(testProps);
115 synchronized (ConfiguredTest.class) {
117 l = DatabaseConnection.newLink(false);
120 } catch (InterruptedException e) {
129 public static void closeDBLink() {
130 synchronized (ConfiguredTest.class) {
138 private static Properties generateProps() throws Error {
139 Properties mainProps = new Properties();
140 mainProps.setProperty("name.secure", testProps.getProperty("name.secure"));
141 mainProps.setProperty("name.www", testProps.getProperty("name.www"));
142 mainProps.setProperty("name.static", testProps.getProperty("name.static"));
143 mainProps.setProperty("name.api", testProps.getProperty("name.api"));
144 mainProps.setProperty("name.suffix", testProps.getProperty("name.suffix"));
146 mainProps.setProperty("appName", "SomeCA");
147 mainProps.setProperty("appIdentifier", "someca");
149 mainProps.setProperty("https.port", testProps.getProperty("serverPort.https"));
150 mainProps.setProperty("http.port", testProps.getProperty("serverPort.http"));
152 File out = new File("financial.dat");
153 if ( !out.exists()) {
154 try (FileOutputStream fos = new FileOutputStream(out)) {
155 fos.write("google.com\ntwitter.com\n".getBytes("UTF-8"));
156 } catch (IOException e) {
160 mainProps.setProperty("highFinancialValue", out.getAbsolutePath());
161 mainProps.setProperty("scrypt.params", "1;1;1");
165 public static KeyPair generateKeypair() throws GeneralSecurityException {
166 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
167 kpg.initialize(4096);
168 KeyPair keyPair = null;
169 File f = new File("testKeypair");
171 try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
172 keyPair = (KeyPair) ois.readObject();
173 } catch (ClassNotFoundException e) {
175 } catch (IOException e) {
179 keyPair = kpg.generateKeyPair();
180 try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
181 oos.writeObject(keyPair);
183 } catch (IOException e) {
190 public static KeyPair generateBrokenKeypair() throws GeneralSecurityException {
191 KeyPair keyPair = null;
192 File f = new File("testBrokenKeypair");
194 try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
195 keyPair = (KeyPair) ois.readObject();
196 } catch (ClassNotFoundException e) {
198 } catch (IOException e) {
202 // -----BEGIN SHAMELESSLY ADAPTED BLOCK-----
204 * Modified original RSA key generator to use three primes with one
205 * prime set to fixed value to allow simple checking for such faulty
208 * @link sun.security.rsa.RSAKeyPairGenerator#generateKeyPair
211 KeyFactory factory = KeyFactory.getInstance("RSA");
212 Random random = new SecureRandom();
216 // The generated numbers p q and r fall into the
218 // - p: 2^(lp-1) < p < 2^lp
219 // - q: 2^(lq-1) < q < 2^lq
220 // - r: 2^12 < r < 2^13
221 // Thus the generated number has at least lp+lq+11 bit and
222 // can have at most lp+lq+13 bit.
223 // Thus for random selection of p and q the algorithm will
224 // at some point select a number of length n=n/2+lr+(n-n/2-lr)=>n
226 int lp = (keySize + 1) >> 1;
227 int lr = BigInteger.valueOf(r_lv).bitLength();
228 int lq = keySize - lp - lr;
230 BigInteger e = BigInteger.valueOf(7331);
233 while (keyPair == null) {
234 // generate two random primes of size lp/lq
235 BigInteger p, q, r, n;
237 r = BigInteger.valueOf(r_lv);
239 p = BigInteger.probablePrime(lp, random);
240 q = BigInteger.probablePrime(lq, random);
242 // modulus n = p * q * r
243 n = p.multiply(q).multiply(r);
245 // even with correctly sized p, q and r, there is a chance
246 // that n will be one bit short. re-generate the
248 } while (n.bitLength() < keySize);
250 // phi = (p - 1) * (q - 1) * (r - 1) must be relative prime to e
251 // otherwise RSA just won't work ;-)
252 BigInteger p1 = p.subtract(BigInteger.ONE);
253 BigInteger q1 = q.subtract(BigInteger.ONE);
254 BigInteger r1 = r.subtract(BigInteger.ONE);
255 BigInteger phi = p1.multiply(q1).multiply(r1);
257 // generate new p and q until they work. typically
258 if (e.gcd(phi).equals(BigInteger.ONE) == false) {
262 // private exponent d is the inverse of e mod phi
263 BigInteger d = e.modInverse(phi);
265 RSAPublicKeySpec publicSpec = new RSAPublicKeySpec(n, e);
266 RSAPrivateKeySpec privateSpec = new RSAPrivateKeySpec(n, d);
267 PublicKey publicKey = factory.generatePublic(publicSpec);
268 PrivateKey privateKey = factory.generatePrivate(privateSpec);
269 keyPair = new KeyPair(publicKey, privateKey);
271 // -----END SHAMELESSLY ADAPTED BLOCK-----
273 try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
274 oos.writeObject(keyPair);
276 } catch (IOException ioe) {
277 ioe.printStackTrace();
283 public static String generatePEMCSR(KeyPair kp, String dn) throws GeneralSecurityException, IOException {
284 return generatePEMCSR(kp, dn, new PKCS10Attributes());
287 public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts) throws GeneralSecurityException, IOException {
288 return generatePEMCSR(kp, dn, atts, "SHA512WithRSA");
291 public static String generatePEMCSR(KeyPair kp, String dn, PKCS10Attributes atts, String signature) throws GeneralSecurityException, IOException {
292 PKCS10 p10 = new PKCS10(kp.getPublic(), atts);
293 Signature s = Signature.getInstance(signature);
294 s.initSign(kp.getPrivate());
295 p10.encodeAndSign(new X500Name(dn), s);
296 return PEM.encode("CERTIFICATE REQUEST", p10.getEncoded());
299 static int count = 0;
301 public static String createRandomIDString() {
302 final char[] chars = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
303 final int idStringLength = 16;
308 StringBuilder sb = new StringBuilder(idStringLength);
309 for (int i = 0; i < idStringLength; i++) {
310 sb.append(chars[sr.nextInt(chars.length)]);
313 return sb.toString();
316 public static synchronized String createUniqueName() {
317 return "test" + createRandomIDString() + "a" + (count++) + "u";
320 public static CertificateProfile getClientProfile() {
321 return CertificateProfile.getByName("client");
324 public static int countRegex(String text, String pattern) {
325 Pattern p = Pattern.compile(pattern);
326 Matcher m = p.matcher(text);
334 public static void makeAgent(int uid) {
335 try (GigiPreparedStatement ps1 = new GigiPreparedStatement("INSERT INTO cats_passed SET user_id=?, variant_id=?, language='en_EN', version='1'")) {
337 ps1.setInt(2, CATSType.AGENT_CHALLENGE.getId());
341 try (GigiPreparedStatement ps2 = new GigiPreparedStatement("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'")) {
343 ps2.setInt(2, User.getById(uid).getPreferredName().getId());
348 public MailReceiver getMailReceiver() {
349 throw new Error("Feature requires Business or ManagedTest.");
352 public void verify(Domain d) {
354 d.addPing(DomainPingType.EMAIL, "admin");
355 TestMail testMail = getMailReceiver().receive("admin@" + d.getSuffix());
357 // Enforce successful ping :-)
358 d.addPing(DomainPingType.HTTP, "a:b");
359 try (GigiPreparedStatement gps = new GigiPreparedStatement("INSERT INTO `domainPinglog` SET `configId`=(SELECT `id` FROM `pingconfig` WHERE `domainid`=? AND `type`='http'), state='success', needsAction=false")) {
360 gps.setInt(1, d.getId());
363 assertTrue(d.isVerified());
364 } catch (GigiApiException e) {
366 } catch (IOException e) {
371 public static void purgeOnlyDB() throws SQLException, IOException {
372 System.out.println("... resetting Database");
373 long ms = System.currentTimeMillis();
375 DatabaseManager.run(new String[] {
376 testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"), testProps.getProperty("sql.user"), testProps.getProperty("sql.password")
377 }, ImportType.TRUNCATE);
378 } catch (ClassNotFoundException e) {
381 System.out.println("Database reset complete in " + (System.currentTimeMillis() - ms) + " ms.");
384 public static String validVerificationDateString() {
385 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
386 Calendar c = Calendar.getInstance();
387 c.setTimeInMillis(System.currentTimeMillis());
388 c.add(Calendar.MONTH, -Notary.LIMIT_MAX_MONTHS_VERIFICATION + 1);
389 return sdf.format(new Date(c.getTimeInMillis()));