From 2824d1c165c501e2f3a8809044788b33b81f478a Mon Sep 17 00:00:00 2001 From: =?utf8?q?Felix=20D=C3=B6rre?= Date: Thu, 10 Jul 2014 01:22:51 +0200 Subject: [PATCH] [EMPTY] Formatting with configured formatter. --- src/org/cacert/gigi/Certificate.java | 44 +++---- src/org/cacert/gigi/DevelLauncher.java | 24 ++-- src/org/cacert/gigi/Gigi.java | 8 +- src/org/cacert/gigi/GigiConfig.java | 13 +- src/org/cacert/gigi/Language.java | 10 +- src/org/cacert/gigi/Launcher.java | 75 +++++------ src/org/cacert/gigi/Name.java | 1 + src/org/cacert/gigi/PolicyRedirector.java | 5 +- src/org/cacert/gigi/User.java | 54 +++++--- src/org/cacert/gigi/api/GigiAPI.java | 3 +- .../gigi/database/DatabaseConnection.java | 25 ++-- .../gigi/email/CommandlineEmailProvider.java | 9 +- src/org/cacert/gigi/email/EmailProvider.java | 52 +++----- src/org/cacert/gigi/email/Sendmail.java | 29 ++--- .../cacert/gigi/email/TestEmailProvider.java | 17 +-- .../cacert/gigi/output/CertificateTable.java | 7 +- .../cacert/gigi/output/ClientCSRGenerate.java | 16 +-- src/org/cacert/gigi/output/DateSelector.java | 11 +- src/org/cacert/gigi/output/Form.java | 9 +- src/org/cacert/gigi/output/Template.java | 21 ++- src/org/cacert/gigi/pages/LoginPage.java | 41 +++--- src/org/cacert/gigi/pages/MainPage.java | 4 +- src/org/cacert/gigi/pages/Page.java | 16 +-- src/org/cacert/gigi/pages/TestSecure.java | 3 +- src/org/cacert/gigi/pages/Verify.java | 28 ++-- .../cacert/gigi/pages/account/ChangeForm.java | 8 +- .../pages/account/ChangePasswordPage.java | 6 +- .../pages/account/MailCertificateAdd.java | 16 +-- .../gigi/pages/account/MailCertificates.java | 9 +- .../gigi/pages/account/MailOverview.java | 5 +- .../cacert/gigi/pages/account/MyDetails.java | 12 +- .../cacert/gigi/pages/error/PageNotFound.java | 6 +- .../cacert/gigi/pages/main/RegisterPage.java | 22 ++-- src/org/cacert/gigi/pages/main/Signup.java | 95 +++++--------- .../cacert/gigi/pages/wot/AssuranceForm.java | 41 +++--- src/org/cacert/gigi/pages/wot/AssurePage.java | 38 ++---- src/org/cacert/gigi/ping/DNSPinger.java | 14 +- src/org/cacert/gigi/ping/HTTPFetch.java | 3 +- src/org/cacert/gigi/ping/SSLPinger.java | 120 +++++++++--------- src/org/cacert/gigi/util/CipherInfo.java | 42 +++--- src/org/cacert/gigi/util/KeyStorage.java | 1 + src/org/cacert/gigi/util/Notary.java | 43 +++---- .../gigi/util/PasswordStrengthChecker.java | 4 + src/org/cacert/gigi/util/RandomToken.java | 1 + src/org/cacert/gigi/util/ServerConstants.java | 9 ++ tests/org/cacert/gigi/LoginTest.java | 3 + tests/org/cacert/gigi/TestSSL.java | 46 ++++--- .../org/cacert/gigi/TestSecurityHeaders.java | 10 +- tests/org/cacert/gigi/TestUser.java | 6 +- .../gigi/pages/main/RegisterPageTest.java | 44 ++++--- .../cacert/gigi/pages/wot/TestAssurance.java | 67 +++++----- tests/org/cacert/gigi/testUtils/IOUtils.java | 5 +- .../cacert/gigi/testUtils/InitTruststore.java | 2 + .../cacert/gigi/testUtils/ManagedTest.java | 108 +++++++--------- .../gigi/testUtils/TestEmailReciever.java | 18 ++- .../org/cacert/gigi/util/TestHTMLEncoder.java | 6 +- tests/org/cacert/gigi/util/TestNotary.java | 53 ++++---- .../cacert/gigi/util/TestPasswordHash.java | 7 +- .../util/TestPasswordStrengthChecker.java | 14 +- .../org/cacert/gigi/util/DatabaseManager.java | 23 ++-- util/org/cacert/gigi/util/FetchLocales.java | 27 ++-- util/org/cacert/gigi/util/SimpleSigner.java | 16 +-- 62 files changed, 688 insertions(+), 787 deletions(-) diff --git a/src/org/cacert/gigi/Certificate.java b/src/org/cacert/gigi/Certificate.java index f2011052..9d6d5d8d 100644 --- a/src/org/cacert/gigi/Certificate.java +++ b/src/org/cacert/gigi/Certificate.java @@ -23,6 +23,7 @@ public class Certificate { private String csrName; private String crtName; private String csr = null; + public Certificate(String dn, String md, String csr) { this.dn = dn; this.md = md; @@ -31,10 +32,8 @@ public class Certificate { public Certificate(int id) { try { - PreparedStatement ps = DatabaseConnection - .getInstance() - .prepare( - "SELECT subject, md, csr_name, crt_name FROM `emailcerts` WHERE id=?"); + PreparedStatement ps = DatabaseConnection.getInstance().prepare( + "SELECT subject, md, csr_name, crt_name FROM `emailcerts` WHERE id=?"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (!rs.next()) { @@ -88,6 +87,7 @@ public class Certificate { private CertificateStatus(boolean unstable) { this.unstable = unstable; } + /** * Checks, iff this certificate stage will be left by signer actions. * @@ -99,14 +99,13 @@ public class Certificate { } } + public CertificateStatus getStatus() throws SQLException { if (id == 0) { return CertificateStatus.DRAFT; } - PreparedStatement searcher = DatabaseConnection - .getInstance() - .prepare( - "SELECT crt_name, created, revoked, warning FROM emailcerts WHERE id=?"); + PreparedStatement searcher = DatabaseConnection.getInstance().prepare( + "SELECT crt_name, created, revoked, warning FROM emailcerts WHERE id=?"); searcher.setInt(1, id); ResultSet rs = searcher.executeQuery(); if (!rs.next()) { @@ -124,8 +123,7 @@ public class Certificate { if (rs.getTime(2) != null && rs.getTime(3) == null) { return CertificateStatus.ISSUED; } - if (rs.getTime(2) != null - && rs.getString(3).equals("1970-01-01 00:00:00.0")) { + if (rs.getTime(2) != null && rs.getString(3).equals("1970-01-01 00:00:00.0")) { return CertificateStatus.BEING_REVOKED; } return CertificateStatus.REVOKED; @@ -136,10 +134,8 @@ public class Certificate { if (getStatus() != CertificateStatus.DRAFT) { throw new IllegalStateException(); } - PreparedStatement inserter = DatabaseConnection - .getInstance() - .prepare( - "INSERT INTO emailcerts SET md=?, subject=?, coll_found=0, crt_name=''"); + PreparedStatement inserter = DatabaseConnection.getInstance().prepare( + "INSERT INTO emailcerts SET md=?, subject=?, coll_found=0, crt_name=''"); inserter.setString(1, md); inserter.setString(2, dn); inserter.execute(); @@ -150,8 +146,8 @@ public class Certificate { fos.write(csr.getBytes()); fos.close(); - PreparedStatement updater = DatabaseConnection.getInstance() - .prepare("UPDATE emailcerts SET csr_name=? WHERE id=?"); + PreparedStatement updater = DatabaseConnection.getInstance().prepare( + "UPDATE emailcerts SET csr_name=? WHERE id=?"); updater.setString(1, csrName); updater.setInt(2, id); updater.execute(); @@ -160,6 +156,7 @@ public class Certificate { } } + public boolean waitFor(int max) throws SQLException, InterruptedException { long start = System.currentTimeMillis(); while (getStatus().isUnstable()) { @@ -170,15 +167,14 @@ public class Certificate { } return true; } + public void revoke() { try { if (getStatus() != CertificateStatus.ISSUED) { throw new IllegalStateException(); } - PreparedStatement inserter = DatabaseConnection - .getInstance() - .prepare( - "UPDATE emailcerts SET revoked = '1970-01-01' WHERE id=?"); + PreparedStatement inserter = DatabaseConnection.getInstance().prepare( + "UPDATE emailcerts SET revoked = '1970-01-01' WHERE id=?"); inserter.setInt(1, id); inserter.execute(); } catch (SQLException e) { @@ -187,8 +183,7 @@ public class Certificate { } - public X509Certificate cert() throws IOException, GeneralSecurityException, - SQLException { + public X509Certificate cert() throws IOException, GeneralSecurityException, SQLException { CertificateStatus status = getStatus(); if (status != CertificateStatus.ISSUED) { throw new IllegalStateException(status + " is not wanted here."); @@ -206,18 +201,23 @@ public class Certificate { } return crt; } + public Certificate renew() { return null; } + public int getId() { return id; } + public int getSerial() { return serial; } + public String getDistinguishedName() { return dn; } + public String getMessageDigest() { return md; } diff --git a/src/org/cacert/gigi/DevelLauncher.java b/src/org/cacert/gigi/DevelLauncher.java index e8df9f5b..6fa8a29a 100644 --- a/src/org/cacert/gigi/DevelLauncher.java +++ b/src/org/cacert/gigi/DevelLauncher.java @@ -30,20 +30,18 @@ public class DevelLauncher { ByteArrayOutputStream chunkConfig = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(chunkConfig); byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks")); - byte[] keystore = Files.readAllBytes(Paths - .get("config/keystore.pkcs12")); + byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12")); - DevelLauncher.writeGigiConfig(dos, "changeit".getBytes(), - "changeit".getBytes(), mainProps, cacerts, keystore); + DevelLauncher.writeGigiConfig(dos, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts, keystore); dos.flush(); InputStream oldin = System.in; System.setIn(new ByteArrayInputStream(chunkConfig.toByteArray())); Launcher.main(args); System.setIn(oldin); } - public static void writeGigiConfig(OutputStream target, byte[] keystorepw, - byte[] truststorepw, Properties mainprop, byte[] cacerts, - byte[] keystore) throws IOException { + + public static void writeGigiConfig(OutputStream target, byte[] keystorepw, byte[] truststorepw, + Properties mainprop, byte[] cacerts, byte[] keystore) throws IOException { TarOutputStream tos = new TarOutputStream(target); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mainprop.store(baos, ""); @@ -56,21 +54,21 @@ public class DevelLauncher { tos.close(); } - private static void putTarEntry(byte[] data, TarOutputStream tos, - String name) throws IOException { + + private static void putTarEntry(byte[] data, TarOutputStream tos, String name) throws IOException { TarHeader th = new TarHeader(); th.name = new StringBuffer(name); th.size = data.length; tos.putNextEntry(new TarEntry(th)); tos.write(data); } - public static void writeChunk(DataOutputStream dos, byte[] chunk) - throws IOException { + + public static void writeChunk(DataOutputStream dos, byte[] chunk) throws IOException { dos.writeInt(chunk.length); dos.write(chunk); } - public static void launch(Properties props, File cacerts, File keystore) - throws IOException { + + public static void launch(Properties props, File cacerts, File keystore) throws IOException { ByteArrayOutputStream config = new ByteArrayOutputStream(); props.store(config, ""); } diff --git a/src/org/cacert/gigi/Gigi.java b/src/org/cacert/gigi/Gigi.java index 2741b732..a0f8671a 100644 --- a/src/org/cacert/gigi/Gigi.java +++ b/src/org/cacert/gigi/Gigi.java @@ -62,14 +62,14 @@ public class Gigi extends HttpServlet { pages.put(MailOverview.DEFAULT_PATH, new MailOverview("My email addresses")); baseTemplate = new Template(new InputStreamReader(Gigi.class.getResourceAsStream("Gigi.templ"))); m = new Menu("Certificates", "cert", new MenuItem(MailOverview.DEFAULT_PATH, "Emails"), new MenuItem("", - "Client Certificates"), new MenuItem("", "Domains"), new MenuItem("", "Server Certificates")); + "Client Certificates"), new MenuItem("", "Domains"), new MenuItem("", "Server Certificates")); super.init(); } @Override protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, - IOException { + IOException { addXSSHeaders(resp); // if (req.getHeader("Origin") != null) { // resp.getWriter().println("No cross domain access allowed."); @@ -154,7 +154,7 @@ public class Gigi extends HttpServlet { public static void addXSSHeaders(HttpServletResponse hsr) { hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePort() + " https://" - + ServerConstants.getSecureHostNamePort()); + + ServerConstants.getSecureHostNamePort()); hsr.addHeader("Access-Control-Max-Age", "60"); hsr.addHeader("Content-Security-Policy", getDefaultCSP()); @@ -174,7 +174,7 @@ public class Gigi extends HttpServlet { csp.append("script-src https://" + ServerConstants.getStaticHostNamePort()); csp.append(";style-src https://" + ServerConstants.getStaticHostNamePort()); csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" - + ServerConstants.getWwwHostNamePort()); + + ServerConstants.getWwwHostNamePort()); csp.append("report-url https://api.cacert.org/security/csp/report"); defaultCSP = csp.toString(); } diff --git a/src/org/cacert/gigi/GigiConfig.java b/src/org/cacert/gigi/GigiConfig.java index f8cf7637..86738007 100644 --- a/src/org/cacert/gigi/GigiConfig.java +++ b/src/org/cacert/gigi/GigiConfig.java @@ -21,12 +21,15 @@ public class GigiConfig { private GigiConfig() { } + public byte[] getCacerts() { return cacerts; } + public byte[] getKeystore() { return keystore; } + public Properties getMainProps() { return mainProps; } @@ -53,6 +56,7 @@ public class GigiConfig { tis.close(); return gc; } + public static byte[] readFully(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; @@ -63,6 +67,7 @@ public class GigiConfig { baos.close(); return baos.toByteArray(); } + private static char[] transformSafe(byte[] readChunk) { char[] res = new char[readChunk.length]; for (int i = 0; i < res.length; i++) { @@ -72,18 +77,18 @@ public class GigiConfig { return res; } - public KeyStore getPrivateStore() throws GeneralSecurityException, - IOException { + public KeyStore getPrivateStore() throws GeneralSecurityException, IOException { KeyStore ks1 = KeyStore.getInstance("pkcs12"); ks1.load(new ByteArrayInputStream(keystore), keystorpw); return ks1; } - public KeyStore getTrustStore() throws GeneralSecurityException, - IOException { + + public KeyStore getTrustStore() throws GeneralSecurityException, IOException { KeyStore ks1 = KeyStore.getInstance("jks"); ks1.load(new ByteArrayInputStream(cacerts), truststorepw); return ks1; } + public String getPrivateStorePw() { return new String(keystorpw); } diff --git a/src/org/cacert/gigi/Language.java b/src/org/cacert/gigi/Language.java index 5841c3c3..fc94ce1b 100644 --- a/src/org/cacert/gigi/Language.java +++ b/src/org/cacert/gigi/Language.java @@ -18,8 +18,8 @@ public class Language { private static HashMap langs = new HashMap(); HashMap translations = new HashMap(); Locale l; - private Language(String language) throws ParserConfigurationException, - IOException, SAXException { + + private Language(String language) throws ParserConfigurationException, IOException, SAXException { if (language.contains("_")) { String[] parts = language.split("_"); l = new Locale(parts[0], parts[1]); @@ -29,8 +29,7 @@ public class Language { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); - Document d = db.parse(new FileInputStream(new File("locale", language - + ".xml"))); + Document d = db.parse(new FileInputStream(new File("locale", language + ".xml"))); NodeList nl = d.getDocumentElement().getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { if (!(nl.item(i) instanceof Element)) { @@ -43,6 +42,7 @@ public class Language { } System.out.println(translations.size() + " strings loaded."); } + public String getTranslation(String text) { String string = translations.get(text); if (string == null || string.equals("")) { @@ -50,6 +50,7 @@ public class Language { } return string; } + public static Language getInstance(String language) { Language l = langs.get(language); if (l == null) { @@ -66,6 +67,7 @@ public class Language { } return l; } + public Locale getLocale() { return l; } diff --git a/src/org/cacert/gigi/Launcher.java b/src/org/cacert/gigi/Launcher.java index 2d8ab7ab..6eb5976a 100644 --- a/src/org/cacert/gigi/Launcher.java +++ b/src/org/cacert/gigi/Launcher.java @@ -1,4 +1,5 @@ package org.cacert.gigi; + import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStore; @@ -49,21 +50,18 @@ public class Launcher { // for client-cert auth https_config.addCustomizer(new SecureRequestCustomizer()); - ServerConnector connector = new ServerConnector(s, - createConnectionFactory(conf), new HttpConnectionFactory( - https_config)); + ServerConnector connector = new ServerConnector(s, createConnectionFactory(conf), new HttpConnectionFactory( + https_config)); connector.setHost(conf.getMainProps().getProperty("host")); - connector.setPort(Integer.parseInt(conf.getMainProps().getProperty( - "port"))); - s.setConnectors(new Connector[]{connector}); + connector.setPort(Integer.parseInt(conf.getMainProps().getProperty("port"))); + s.setConnectors(new Connector[] { connector }); HandlerList hl = new HandlerList(); - hl.setHandlers(new Handler[]{generateStaticContext(), - generateGigiContext(conf.getMainProps()), generateAPIContext()}); + hl.setHandlers(new Handler[] { generateStaticContext(), generateGigiContext(conf.getMainProps()), + generateAPIContext() }); s.setHandler(hl); s.start(); - if (connector.getPort() <= 1024 - && !System.getProperty("os.name").toLowerCase().contains("win")) { + if (connector.getPort() <= 1024 && !System.getProperty("os.name").toLowerCase().contains("win")) { SetUID uid = new SetUID(); if (!uid.setUid(65536 - 2, 65536 - 2).getSuccess()) { Log.getLogger(Launcher.class).warn("Couldn't set uid!"); @@ -71,17 +69,13 @@ public class Launcher { } } - private static SslConnectionFactory createConnectionFactory(GigiConfig conf) - throws GeneralSecurityException, IOException { - final SslContextFactory sslContextFactory = generateSSLContextFactory( - conf, "www"); - final SslContextFactory secureContextFactory = generateSSLContextFactory( - conf, "secure"); + private static SslConnectionFactory createConnectionFactory(GigiConfig conf) throws GeneralSecurityException, + IOException { + final SslContextFactory sslContextFactory = generateSSLContextFactory(conf, "www"); + final SslContextFactory secureContextFactory = generateSSLContextFactory(conf, "secure"); secureContextFactory.setNeedClientAuth(true); - final SslContextFactory staticContextFactory = generateSSLContextFactory( - conf, "static"); - final SslContextFactory apiContextFactory = generateSSLContextFactory( - conf, "api"); + final SslContextFactory staticContextFactory = generateSSLContextFactory(conf, "static"); + final SslContextFactory apiContextFactory = generateSSLContextFactory(conf, "api"); try { secureContextFactory.start(); staticContextFactory.start(); @@ -89,12 +83,12 @@ public class Launcher { } catch (Exception e) { e.printStackTrace(); } - return new SslConnectionFactory(sslContextFactory, - HttpVersion.HTTP_1_1.asString()) { + return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()) { @Override public boolean shouldRestartSSL() { return true; } + @Override public SSLEngine restartSSL(SSLSession sslSession) { SSLEngine e2 = null; @@ -105,17 +99,13 @@ public class Launcher { if (sniServerName instanceof SNIHostName) { SNIHostName host = (SNIHostName) sniServerName; String hostname = host.getAsciiName(); - if (hostname.equals(ServerConstants - .getWwwHostName())) { + if (hostname.equals(ServerConstants.getWwwHostName())) { e2 = sslContextFactory.newSSLEngine(); - } else if (hostname.equals(ServerConstants - .getStaticHostName())) { + } else if (hostname.equals(ServerConstants.getStaticHostName())) { e2 = staticContextFactory.newSSLEngine(); - } else if (hostname.equals(ServerConstants - .getSecureHostName())) { + } else if (hostname.equals(ServerConstants.getSecureHostName())) { e2 = secureContextFactory.newSSLEngine(); - } else if (hostname.equals(ServerConstants - .getApiHostName())) { + } else if (hostname.equals(ServerConstants.getApiHostName())) { e2 = apiContextFactory.newSSLEngine(); } break; @@ -123,8 +113,7 @@ public class Launcher { } } if (e2 == null) { - e2 = sslContextFactory.newSSLEngine( - sslSession.getPeerHost(), sslSession.getPeerPort()); + e2 = sslContextFactory.newSSLEngine(sslSession.getPeerHost(), sslSession.getPeerPort()); } e2.setUseClientMode(false); return e2; @@ -139,18 +128,15 @@ public class Launcher { HandlerWrapper hw = new PolicyRedirector(); hw.setHandler(rh); - ServletContextHandler servlet = new ServletContextHandler( - ServletContextHandler.SESSIONS); - servlet.setInitParameter(SessionManager.__SessionCookieProperty, - "CACert-Session"); + ServletContextHandler servlet = new ServletContextHandler(ServletContextHandler.SESSIONS); + servlet.setInitParameter(SessionManager.__SessionCookieProperty, "CACert-Session"); servlet.addServlet(new ServletHolder(new Gigi(conf)), "/*"); HandlerList hl = new HandlerList(); - hl.setHandlers(new Handler[]{hw, servlet}); + hl.setHandlers(new Handler[] { hw, servlet }); ContextHandler ch = new ContextHandler(); - ch.setVirtualHosts(new String[]{ServerConstants.getWwwHostName(), - ServerConstants.getSecureHostName()}); + ch.setVirtualHosts(new String[] { ServerConstants.getWwwHostName(), ServerConstants.getSecureHostName() }); ch.setHandler(hl); return ch; @@ -162,7 +148,7 @@ public class Launcher { ContextHandler ch = new ContextHandler(); ch.setHandler(rh); - ch.setVirtualHosts(new String[]{ServerConstants.getStaticHostName()}); + ch.setVirtualHosts(new String[] { ServerConstants.getStaticHostName() }); return ch; } @@ -170,13 +156,13 @@ public class Launcher { private static Handler generateAPIContext() { ServletContextHandler sch = new ServletContextHandler(); - sch.addVirtualHosts(new String[]{ServerConstants.getApiHostName()}); + sch.addVirtualHosts(new String[] { ServerConstants.getApiHostName() }); sch.addServlet(new ServletHolder(new GigiAPI()), "/*"); return sch; } - private static SslContextFactory generateSSLContextFactory(GigiConfig conf, - String alias) throws GeneralSecurityException, IOException { + private static SslContextFactory generateSSLContextFactory(GigiConfig conf, String alias) + throws GeneralSecurityException, IOException { SslContextFactory scf = new SslContextFactory() { String[] ciphers = null; @@ -188,8 +174,7 @@ public class Launcher { SSLParameters ssl = sslEngine.getSSLParameters(); ssl.setUseCipherSuitesOrder(true); if (ciphers == null) { - ciphers = CipherInfo.filter(sslEngine - .getSupportedCipherSuites()); + ciphers = CipherInfo.filter(sslEngine.getSupportedCipherSuites()); } ssl.setCipherSuites(ciphers); diff --git a/src/org/cacert/gigi/Name.java b/src/org/cacert/gigi/Name.java index bf6265b9..865090f0 100644 --- a/src/org/cacert/gigi/Name.java +++ b/src/org/cacert/gigi/Name.java @@ -29,6 +29,7 @@ public class Name implements Outputable { out.print(""); out.println(""); } + @Override public boolean equals(Object obj) { if (!(obj instanceof Name)) { diff --git a/src/org/cacert/gigi/PolicyRedirector.java b/src/org/cacert/gigi/PolicyRedirector.java index 6fd8969b..d96ed732 100644 --- a/src/org/cacert/gigi/PolicyRedirector.java +++ b/src/org/cacert/gigi/PolicyRedirector.java @@ -11,9 +11,8 @@ import org.eclipse.jetty.server.handler.HandlerWrapper; public class PolicyRedirector extends HandlerWrapper { @Override - public void handle(String target, Request baseRequest, - HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException { + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { if (target.equals("/")) { return; } diff --git a/src/org/cacert/gigi/User.java b/src/org/cacert/gigi/User.java index b492de48..95630394 100644 --- a/src/org/cacert/gigi/User.java +++ b/src/org/cacert/gigi/User.java @@ -20,15 +20,12 @@ public class User { public User(int id) { this.id = id; try { - PreparedStatement ps = DatabaseConnection - .getInstance() - .prepare( - "SELECT `fname`, `lname`,`mname`, `suffix`, `dob`, `email` FROM `users` WHERE id=?"); + PreparedStatement ps = DatabaseConnection.getInstance().prepare( + "SELECT `fname`, `lname`,`mname`, `suffix`, `dob`, `email` FROM `users` WHERE id=?"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (rs.next()) { - name = new Name(rs.getString(1), rs.getString(2), - rs.getString(3), rs.getString(4)); + name = new Name(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)); dob = rs.getDate(5); email = rs.getString(6); } @@ -37,61 +34,77 @@ public class User { e.printStackTrace(); } } + public User() { } + public int getId() { return id; } + public String getFname() { return name.fname; } + public String getLname() { return name.lname; } + public String getMname() { return name.mname; } + public Name getName() { return name; } + public void setMname(String mname) { this.name.mname = mname; } + public String getSuffix() { return name.suffix; } + public void setSuffix(String suffix) { this.name.suffix = suffix; } + public Date getDob() { return dob; } + public void setDob(Date dob) { this.dob = dob; } + public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } + public void setId(int id) { this.id = id; } + public void setFname(String fname) { this.name.fname = fname; } + public void setLname(String lname) { this.name.lname = lname; } + public void insert(String password) throws SQLException { if (id != 0) { throw new Error("refusing to insert"); } PreparedStatement query = DatabaseConnection.getInstance().prepare( - "insert into `users` set `email`=?, `password`=?, " - + "`fname`=?, `mname`=?, `lname`=?, " - + "`suffix`=?, `dob`=?, `created`=NOW(), locked=0"); + "insert into `users` set `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, " + + "`suffix`=?, `dob`=?, `created`=NOW(), locked=0"); query.setString(1, email); query.setString(2, PasswordHash.hash(password)); query.setString(3, name.fname); @@ -112,9 +125,10 @@ public class User { return hasPassedCATS(); } + public boolean hasPassedCATS() throws SQLException { PreparedStatement query = DatabaseConnection.getInstance().prepare( - "SELECT 1 FROM `cats_passed` where `user_id`=?"); + "SELECT 1 FROM `cats_passed` where `user_id`=?"); query.setInt(1, id); ResultSet rs = query.executeQuery(); if (rs.next()) { @@ -123,11 +137,10 @@ public class User { return false; } } + public int getAssurancePoints() throws SQLException { - PreparedStatement query = DatabaseConnection - .getInstance() - .prepare( - "SELECT sum(points) FROM `notary` where `to`=? AND `deleted`=0"); + PreparedStatement query = DatabaseConnection.getInstance().prepare( + "SELECT sum(points) FROM `notary` where `to`=? AND `deleted`=0"); query.setInt(1, id); ResultSet rs = query.executeQuery(); int points = 0; @@ -137,9 +150,10 @@ public class User { rs.close(); return points; } + public int getExperiencePoints() throws SQLException { PreparedStatement query = DatabaseConnection.getInstance().prepare( - "SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0"); + "SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0"); query.setInt(1, id); ResultSet rs = query.executeQuery(); int points = 0; @@ -149,15 +163,19 @@ public class User { rs.close(); return points; } + @Override public boolean equals(Object obj) { if (!(obj instanceof User)) { return false; } User s = (User) obj; - return name.equals(s.name) && email.equals(s.email) - && dob.toString().equals(s.dob.toString()); // This is due to - // day cutoff + return name.equals(s.name) && email.equals(s.email) && dob.toString().equals(s.dob.toString()); // This + // is + // due + // to + // day + // cutoff } /** diff --git a/src/org/cacert/gigi/api/GigiAPI.java b/src/org/cacert/gigi/api/GigiAPI.java index 88c8da81..4104feb3 100644 --- a/src/org/cacert/gigi/api/GigiAPI.java +++ b/src/org/cacert/gigi/api/GigiAPI.java @@ -11,8 +11,7 @@ import javax.servlet.http.HttpServletResponse; public class GigiAPI extends HttpServlet { @Override - protected void service(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pi = req.getPathInfo(); if (pi == null) { return; diff --git a/src/org/cacert/gigi/database/DatabaseConnection.java b/src/org/cacert/gigi/database/DatabaseConnection.java index 6bed8bd9..b52b63de 100644 --- a/src/org/cacert/gigi/database/DatabaseConnection.java +++ b/src/org/cacert/gigi/database/DatabaseConnection.java @@ -15,6 +15,7 @@ public class DatabaseConnection { HashMap statements = new HashMap(); private static Properties credentials; Statement adHoc; + public DatabaseConnection() { try { Class.forName(credentials.getProperty("sql.driver")); @@ -24,14 +25,12 @@ public class DatabaseConnection { tryConnect(); } + private void tryConnect() { try { - c = DriverManager.getConnection(credentials.getProperty("sql.url") - + "?zeroDateTimeBehavior=convertToNull", - credentials.getProperty("sql.user"), - credentials.getProperty("sql.password")); - PreparedStatement ps = c - .prepareStatement("SET SESSION wait_timeout=?;"); + c = DriverManager.getConnection(credentials.getProperty("sql.url") + "?zeroDateTimeBehavior=convertToNull", + credentials.getProperty("sql.user"), credentials.getProperty("sql.password")); + PreparedStatement ps = c.prepareStatement("SET SESSION wait_timeout=?;"); ps.setInt(1, CONNECTION_TIMEOUT); ps.execute(); ps.close(); @@ -40,17 +39,19 @@ public class DatabaseConnection { e.printStackTrace(); } } + public PreparedStatement prepare(String query) throws SQLException { ensureOpen(); PreparedStatement statement = statements.get(query); if (statement == null) { - statement = c.prepareStatement(query, - Statement.RETURN_GENERATED_KEYS); + statement = c.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); statements.put(query, statement); } return statement; } + long lastAction = System.currentTimeMillis(); + private void ensureOpen() { if (System.currentTimeMillis() - lastAction > CONNECTION_TIMEOUT * 1000L) { try { @@ -65,6 +66,7 @@ public class DatabaseConnection { } lastAction = System.currentTimeMillis(); } + public static int lastInsertId(PreparedStatement query) throws SQLException { ResultSet rs = query.getGeneratedKeys(); rs.next(); @@ -72,31 +74,38 @@ public class DatabaseConnection { rs.close(); return id; } + static ThreadLocal instances = new ThreadLocal() { @Override protected DatabaseConnection initialValue() { return new DatabaseConnection(); } }; + public static DatabaseConnection getInstance() { return instances.get(); } + public static boolean isInited() { return credentials != null; } + public static void init(Properties conf) { if (credentials != null) { throw new Error("Re-initiaizing is forbidden."); } credentials = conf; } + public void beginTransaction() throws SQLException { c.setAutoCommit(false); } + public void commitTransaction() throws SQLException { c.commit(); c.setAutoCommit(true); } + public void quitTransaction() { try { if (!c.getAutoCommit()) { diff --git a/src/org/cacert/gigi/email/CommandlineEmailProvider.java b/src/org/cacert/gigi/email/CommandlineEmailProvider.java index 2f7502b5..a9149fab 100644 --- a/src/org/cacert/gigi/email/CommandlineEmailProvider.java +++ b/src/org/cacert/gigi/email/CommandlineEmailProvider.java @@ -8,9 +8,8 @@ public class CommandlineEmailProvider extends EmailProvider { } @Override - public void sendmail(String to, String subject, String message, - String from, String replyto, String toname, String fromname, - String errorsto, boolean extra) throws IOException { + public void sendmail(String to, String subject, String message, String from, String replyto, String toname, + String fromname, String errorsto, boolean extra) throws IOException { synchronized (System.out) { System.out.println("== MAIL =="); System.out.println("To: " + to); @@ -22,9 +21,9 @@ public class CommandlineEmailProvider extends EmailProvider { } } + @Override - public String checkEmailServer(int forUid, String address) - throws IOException { + public String checkEmailServer(int forUid, String address) throws IOException { System.out.println("checkMailBox: " + address); return OK; } diff --git a/src/org/cacert/gigi/email/EmailProvider.java b/src/org/cacert/gigi/email/EmailProvider.java index 644c4621..0efe603e 100644 --- a/src/org/cacert/gigi/email/EmailProvider.java +++ b/src/org/cacert/gigi/email/EmailProvider.java @@ -14,18 +14,19 @@ import java.util.regex.Pattern; import org.cacert.gigi.database.DatabaseConnection; public abstract class EmailProvider { - public abstract void sendmail(String to, String subject, String message, - String from, String replyto, String toname, String fromname, - String errorsto, boolean extra) throws IOException; + public abstract void sendmail(String to, String subject, String message, String from, String replyto, + String toname, String fromname, String errorsto, boolean extra) throws IOException; + private static EmailProvider instance; + public static EmailProvider getInstance() { return instance; } + public static void init(Properties conf) { try { Class c = Class.forName(conf.getProperty("emailProvider")); - instance = (EmailProvider) c.getDeclaredConstructor( - Properties.class).newInstance(conf); + instance = (EmailProvider) c.getDeclaredConstructor(Properties.class).newInstance(conf); } catch (ReflectiveOperationException e) { e.printStackTrace(); } @@ -34,10 +35,9 @@ public abstract class EmailProvider { public static final String OK = "OK"; public static final String FAIL = "FAIL"; private static final Pattern MAIL = Pattern - .compile("^([a-zA-Z0-9])+([a-zA-Z0-9\\+\\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\\._-]+)+$"); + .compile("^([a-zA-Z0-9])+([a-zA-Z0-9\\+\\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\\._-]+)+$"); - public String checkEmailServer(int forUid, String address) - throws IOException { + public String checkEmailServer(int forUid, String address) throws IOException { if (MAIL.matcher(address).matches()) { String[] parts = address.split("@", 2); String domain = parts[1]; @@ -46,12 +46,10 @@ public abstract class EmailProvider { for (String host : mxhosts) { try (Socket s = new Socket(host, 25); - BufferedReader br = new BufferedReader( - new InputStreamReader(s.getInputStream())); - PrintWriter pw = new PrintWriter(s.getOutputStream())) { + BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); + PrintWriter pw = new PrintWriter(s.getOutputStream())) { String line; - while ((line = br.readLine()) != null - && line.startsWith("220-")) { + while ((line = br.readLine()) != null && line.startsWith("220-")) { } if (line == null || !line.startsWith("220")) { continue; @@ -60,8 +58,7 @@ public abstract class EmailProvider { pw.print("HELO www.cacert.org\r\n"); pw.flush(); - while ((line = br.readLine()) != null - && line.startsWith("220")) { + while ((line = br.readLine()) != null && line.startsWith("220")) { } if (line == null || !line.startsWith("250")) { @@ -83,10 +80,8 @@ public abstract class EmailProvider { pw.flush(); try { - PreparedStatement statmt = DatabaseConnection - .getInstance() - .prepare( - "insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?"); + PreparedStatement statmt = DatabaseConnection.getInstance().prepare( + "insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?"); statmt.setString(1, address); statmt.setString(2, line); statmt.setInt(3, forUid); @@ -105,13 +100,10 @@ public abstract class EmailProvider { } } try { - PreparedStatement statmt = DatabaseConnection - .getInstance() - .prepare( - "insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?"); + PreparedStatement statmt = DatabaseConnection.getInstance().prepare( + "insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?"); statmt.setString(1, address); - statmt.setString(2, - "Failed to make a connection to the mail server"); + statmt.setString(2, "Failed to make a connection to the mail server"); statmt.setInt(3, forUid); statmt.execute(); } catch (SQLException e) { @@ -119,13 +111,11 @@ public abstract class EmailProvider { } return FAIL; } - private static LinkedList getMxHosts(String domain) - throws IOException { + + private static LinkedList getMxHosts(String domain) throws IOException { LinkedList mxhosts = new LinkedList(); - Process dig = Runtime.getRuntime().exec( - new String[]{"dig", "+short", "MX", domain}); - try (BufferedReader br = new BufferedReader(new InputStreamReader( - dig.getInputStream()))) { + Process dig = Runtime.getRuntime().exec(new String[] { "dig", "+short", "MX", domain }); + try (BufferedReader br = new BufferedReader(new InputStreamReader(dig.getInputStream()))) { String line; while ((line = br.readLine()) != null) { String[] mxparts = line.split(" ", 2); diff --git a/src/org/cacert/gigi/email/Sendmail.java b/src/org/cacert/gigi/email/Sendmail.java index c61494b7..f47d2bc3 100644 --- a/src/org/cacert/gigi/email/Sendmail.java +++ b/src/org/cacert/gigi/email/Sendmail.java @@ -15,20 +15,18 @@ import java.util.regex.Pattern; public class Sendmail extends EmailProvider { protected Sendmail(Properties props) { } - private static final Pattern NON_ASCII = Pattern - .compile("[^a-zA-Z0-9 .-\\[\\]!_@]"); + + private static final Pattern NON_ASCII = Pattern.compile("[^a-zA-Z0-9 .-\\[\\]!_@]"); @Override - public void sendmail(String to, String subject, String message, - String from, String replyto, String toname, String fromname, - String errorsto, boolean extra) throws IOException { + public void sendmail(String to, String subject, String message, String from, String replyto, String toname, + String fromname, String errorsto, boolean extra) throws IOException { String[] bits = from.split(","); Socket smtp = new Socket("dogcraft.de", 25); PrintWriter out = new PrintWriter(smtp.getOutputStream()); - BufferedReader in = new BufferedReader(new InputStreamReader( - smtp.getInputStream())); + BufferedReader in = new BufferedReader(new InputStreamReader(smtp.getInputStream())); readResponse(in); out.print("HELO www.cacert.org\r\n"); out.flush(); @@ -50,11 +48,8 @@ public class Sendmail extends EmailProvider { // out.print("X-OriginatingIP: ".$_SERVER["REMOTE_ADDR"]."\r\n"); // } // TODO - SimpleDateFormat emailDate = new SimpleDateFormat( - "E, d MMM yyyy HH:mm:ss ZZZZ (z)", Locale.ENGLISH); - out.print("Date: " - + emailDate.format(new Date(System.currentTimeMillis())) - + "\r\n"); + SimpleDateFormat emailDate = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss ZZZZ (z)", Locale.ENGLISH); + out.print("Date: " + emailDate.format(new Date(System.currentTimeMillis())) + "\r\n"); out.print("Sender: " + errorsto + "\r\n"); out.print("Errors-To: " + errorsto + "\r\n"); if (replyto != null) { @@ -66,9 +61,7 @@ public class Sendmail extends EmailProvider { out.print("To: " + to + "\r\n"); if (NON_ASCII.matcher(subject).matches()) { - out.print("Subject: =?utf-8?B?" - + Base64.getEncoder().encodeToString(subject.getBytes()) - + "?=\r\n"); + out.print("Subject: =?utf-8?B?" + Base64.getEncoder().encodeToString(subject.getBytes()) + "?=\r\n"); } else { out.print("Subject: " + subject + "\r\n"); } @@ -87,9 +80,8 @@ public class Sendmail extends EmailProvider { // $message)))."\r\n.\r\n"); message = message + "\r\n"; - String sendM = message.replace("\r", "").replace("\n.\n", "\n") - .replace("\n.\n", "\n").replace("\n", "\r\n") - + ".\r\n"; + String sendM = message.replace("\r", "").replace("\n.\n", "\n").replace("\n.\n", "\n").replace("\n", "\r\n") + + ".\r\n"; out.print(sendM); out.flush(); readResponse(in); @@ -98,6 +90,7 @@ public class Sendmail extends EmailProvider { readResponse(in); smtp.close(); } + private static void readResponse(BufferedReader in) throws IOException { String line; while ((line = in.readLine()) != null && line.matches("\\d+-")) { diff --git a/src/org/cacert/gigi/email/TestEmailProvider.java b/src/org/cacert/gigi/email/TestEmailProvider.java index 07343502..35c4b3fe 100644 --- a/src/org/cacert/gigi/email/TestEmailProvider.java +++ b/src/org/cacert/gigi/email/TestEmailProvider.java @@ -13,19 +13,19 @@ class TestEmailProvider extends EmailProvider { Socket client; DataOutputStream out; DataInputStream in; + protected TestEmailProvider(Properties props) { try { - servs = new ServerSocket(Integer.parseInt(props - .getProperty("emailProvider.port")), 10, - InetAddress.getByName("127.0.0.1")); + servs = new ServerSocket(Integer.parseInt(props.getProperty("emailProvider.port")), 10, + InetAddress.getByName("127.0.0.1")); } catch (IOException e) { e.printStackTrace(); } } + @Override - public synchronized void sendmail(String to, String subject, - String message, String from, String replyto, String toname, - String fromname, String errorsto, boolean extra) throws IOException { + public synchronized void sendmail(String to, String subject, String message, String from, String replyto, + String toname, String fromname, String errorsto, boolean extra) throws IOException { while (true) { assureLocalConnection(); try { @@ -42,6 +42,7 @@ class TestEmailProvider extends EmailProvider { } } } + private void assureLocalConnection() throws IOException { if (out != null) { try { @@ -56,9 +57,9 @@ class TestEmailProvider extends EmailProvider { in = new DataInputStream(client.getInputStream()); } } + @Override - public synchronized String checkEmailServer(int forUid, String address) - throws IOException { + public synchronized String checkEmailServer(int forUid, String address) throws IOException { while (true) { assureLocalConnection(); try { diff --git a/src/org/cacert/gigi/output/CertificateTable.java b/src/org/cacert/gigi/output/CertificateTable.java index 413de877..9f310f19 100644 --- a/src/org/cacert/gigi/output/CertificateTable.java +++ b/src/org/cacert/gigi/output/CertificateTable.java @@ -9,12 +9,13 @@ import org.cacert.gigi.Language; public class CertificateTable implements Outputable { String resultSet; + public CertificateTable(String resultSet) { this.resultSet = resultSet; } - private static final String[] columnNames = new String[]{ - "Renew/Revoke/Delete", "Status", "Email Address", "SerialNumber", - "Revoked", "Expires", "Login"}; + + private static final String[] columnNames = new String[] { "Renew/Revoke/Delete", "Status", "Email Address", + "SerialNumber", "Revoked", "Expires", "Login" }; @Override public void output(PrintWriter out, Language l, Map vars) { diff --git a/src/org/cacert/gigi/output/ClientCSRGenerate.java b/src/org/cacert/gigi/output/ClientCSRGenerate.java index aeb7d9b8..9398c220 100644 --- a/src/org/cacert/gigi/output/ClientCSRGenerate.java +++ b/src/org/cacert/gigi/output/ClientCSRGenerate.java @@ -15,21 +15,17 @@ public class ClientCSRGenerate { static Template IE; static { normal = new Template(new InputStreamReader( - ClientCSRGenerate.class - .getResourceAsStream("ClientCSRGenerate.templ"))); + ClientCSRGenerate.class.getResourceAsStream("ClientCSRGenerate.templ"))); IE = new Template(new InputStreamReader( - ClientCSRGenerate.class - .getResourceAsStream("ClientCSRGenerateIE.templ"))); + ClientCSRGenerate.class.getResourceAsStream("ClientCSRGenerateIE.templ"))); } + public static void output(HttpServletRequest req, HttpServletResponse resp) { HashMap vars = new HashMap(); vars.put("minsize", "2048"); - vars.put("normalhost", - "https://" + ServerConstants.getWwwHostNamePort()); - vars.put("securehost", - "https://" + ServerConstants.getSecureHostNamePort()); - vars.put("statichost", - "https://" + ServerConstants.getStaticHostNamePort()); + vars.put("normalhost", "https://" + ServerConstants.getWwwHostNamePort()); + vars.put("securehost", "https://" + ServerConstants.getSecureHostNamePort()); + vars.put("statichost", "https://" + ServerConstants.getStaticHostNamePort()); try { normal.output(resp.getWriter(), Page.getLanguage(req), vars); } catch (IOException e) { diff --git a/src/org/cacert/gigi/output/DateSelector.java b/src/org/cacert/gigi/output/DateSelector.java index c8cc0f10..4c162cfc 100644 --- a/src/org/cacert/gigi/output/DateSelector.java +++ b/src/org/cacert/gigi/output/DateSelector.java @@ -13,12 +13,15 @@ import org.cacert.gigi.Language; public class DateSelector implements Outputable { String[] names; + public DateSelector(String day, String month, String year) { - this.names = new String[]{day, month, year}; + this.names = new String[] { day, month, year }; } + int day; int month; int year; + @Override public void output(PrintWriter out, Language l, Map vars) { out.print(""); } - protected abstract void outputContent(PrintWriter out, Language l, - Map vars); + protected abstract void outputContent(PrintWriter out, Language l, Map vars); protected void outputError(PrintWriter out, ServletRequest req, String text) { out.print("
"); @@ -39,6 +39,7 @@ public abstract class Form implements Outputable { protected String getCSRFToken() { return csrf; } + protected void checkCSRF(HttpServletRequest req) { if (!csrf.equals(req.getParameter("csrf"))) { throw new CSRFError(); diff --git a/src/org/cacert/gigi/output/Template.java b/src/org/cacert/gigi/output/Template.java index b6fb111e..33720034 100644 --- a/src/org/cacert/gigi/output/Template.java +++ b/src/org/cacert/gigi/output/Template.java @@ -19,7 +19,7 @@ public class Template implements Outputable { LinkedList commands = new LinkedList(); StringBuffer buf = new StringBuffer(); int ch = r.read(); - outer : while (true) { + outer: while (true) { while (!endsWith(buf, "= string.length() - && buf.substring(buf.length() - string.length(), buf.length()) - .equals(string); + && buf.substring(buf.length() - string.length(), buf.length()).equals(string); } + private Outputable parseCommand(String s2) { s2 = s2.replace("\n", ""); if (s2.startsWith("=_")) { @@ -61,8 +62,7 @@ public class Template implements Outputable { return new Outputable() { @Override - public void output(PrintWriter out, Language l, - Map vars) { + public void output(PrintWriter out, Language l, Map vars) { out.print(l.getTranslation(raw)); } }; @@ -71,8 +71,7 @@ public class Template implements Outputable { return new Outputable() { @Override - public void output(PrintWriter out, Language l, - Map vars) { + public void output(PrintWriter out, Language l, Map vars) { outputVar(out, l, vars, raw); } }; @@ -88,8 +87,7 @@ public class Template implements Outputable { return new Outputable() { @Override - public void output(PrintWriter out, Language l, - Map vars) { + public void output(PrintWriter out, Language l, Map vars) { String[] parts = l.getTranslation(text).split("%s"); String[] myvars = store.toArray(new String[store.size()]); out.print(parts[0]); @@ -104,6 +102,7 @@ public class Template implements Outputable { } return null; } + public void output(PrintWriter out, Language l, Map vars) { for (int i = 0; i < contents.length; i++) { out.print(contents[i]); @@ -112,8 +111,8 @@ public class Template implements Outputable { } } } - private void outputVar(PrintWriter out, Language l, - Map vars, String varname) { + + private void outputVar(PrintWriter out, Language l, Map vars, String varname) { Object s = vars.get(varname); if (s == null) { diff --git a/src/org/cacert/gigi/pages/LoginPage.java b/src/org/cacert/gigi/pages/LoginPage.java index 7febf2e5..7be71177 100644 --- a/src/org/cacert/gigi/pages/LoginPage.java +++ b/src/org/cacert/gigi/pages/LoginPage.java @@ -25,22 +25,17 @@ public class LoginPage extends Page { } @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { - resp.getWriter() - .println( - "
" - + "" - + "
"); + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + resp.getWriter().println( + "
" + "" + + "
"); } @Override - public boolean beforeTemplate(HttpServletRequest req, - HttpServletResponse resp) throws IOException { + public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException { String redir = (String) req.getSession().getAttribute(LOGIN_RETURNPATH); if (req.getSession().getAttribute("loggedin") == null) { - X509Certificate[] cert = (X509Certificate[]) req - .getAttribute("javax.servlet.request.X509Certificate"); + X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate"); if (cert != null && cert[0] != null) { tryAuthWithCertificate(req, cert[0]); } @@ -63,18 +58,18 @@ public class LoginPage extends Page { } return false; } + @Override public boolean needsLogin() { return false; } + private void tryAuthWithUnpw(HttpServletRequest req) { String un = req.getParameter("username"); String pw = req.getParameter("password"); try { - PreparedStatement ps = DatabaseConnection - .getInstance() - .prepare( - "SELECT `password`, `id` FROM `users` WHERE `email`=? AND locked='0' AND verified='1'"); + PreparedStatement ps = DatabaseConnection.getInstance().prepare( + "SELECT `password`, `id` FROM `users` WHERE `email`=? AND locked='0' AND verified='1'"); ps.setString(1, un); ResultSet rs = ps.executeQuery(); if (rs.next()) { @@ -90,19 +85,17 @@ public class LoginPage extends Page { e.printStackTrace(); } } + public static User getUser(HttpServletRequest req) { return (User) req.getSession().getAttribute(USER); } - private void tryAuthWithCertificate(HttpServletRequest req, - X509Certificate x509Certificate) { - String serial = x509Certificate.getSerialNumber().toString(16) - .toUpperCase(); + + private void tryAuthWithCertificate(HttpServletRequest req, X509Certificate x509Certificate) { + String serial = x509Certificate.getSerialNumber().toString(16).toUpperCase(); try { - PreparedStatement ps = DatabaseConnection - .getInstance() - .prepare( - "SELECT `memid` FROM `emailcerts` WHERE `serial`=? AND `disablelogin`='0' AND `revoked` = " - + "'0000-00-00 00:00:00'"); + PreparedStatement ps = DatabaseConnection.getInstance().prepare( + "SELECT `memid` FROM `emailcerts` WHERE `serial`=? AND `disablelogin`='0' AND `revoked` = " + + "'0000-00-00 00:00:00'"); ps.setString(1, serial); ResultSet rs = ps.executeQuery(); if (rs.next()) { diff --git a/src/org/cacert/gigi/pages/MainPage.java b/src/org/cacert/gigi/pages/MainPage.java index adeaa802..96b30aed 100644 --- a/src/org/cacert/gigi/pages/MainPage.java +++ b/src/org/cacert/gigi/pages/MainPage.java @@ -11,10 +11,10 @@ public class MainPage extends Page { } @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.getWriter().println("Access granted."); } + @Override public boolean needsLogin() { return false; diff --git a/src/org/cacert/gigi/pages/Page.java b/src/org/cacert/gigi/pages/Page.java index 04f1dc67..b6a30573 100644 --- a/src/org/cacert/gigi/pages/Page.java +++ b/src/org/cacert/gigi/pages/Page.java @@ -23,11 +23,9 @@ public abstract class Page { public Page(String title) { this.title = title; try { - InputStream resource = getClass().getResourceAsStream( - getClass().getSimpleName() + ".templ"); + InputStream resource = getClass().getResourceAsStream(getClass().getSimpleName() + ".templ"); if (resource != null) { - defaultTemplate = new Template(new InputStreamReader(resource, - "UTF-8")); + defaultTemplate = new Template(new InputStreamReader(resource, "UTF-8")); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); @@ -57,8 +55,7 @@ public abstract class Page { * @throws IOException * if output goes wrong. */ - public boolean beforeTemplate(HttpServletRequest req, - HttpServletResponse resp) throws IOException { + public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException { return false; } @@ -73,8 +70,7 @@ public abstract class Page { * @throws IOException * if output goes wrong. */ - public abstract void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException; + public abstract void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException; /** * Same as {@link #doGet(HttpServletRequest, HttpServletResponse)} but for @@ -88,8 +84,7 @@ public abstract class Page { * @throws IOException * if output goes wrong. */ - public void doPost(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } @@ -109,6 +104,7 @@ public abstract class Page { public void setTitle(String title) { this.title = title; } + public static Language getLanguage(ServletRequest req) { return Language.getInstance("de"); } diff --git a/src/org/cacert/gigi/pages/TestSecure.java b/src/org/cacert/gigi/pages/TestSecure.java index e3d2f3cb..02c8ada8 100644 --- a/src/org/cacert/gigi/pages/TestSecure.java +++ b/src/org/cacert/gigi/pages/TestSecure.java @@ -12,8 +12,7 @@ public class TestSecure extends Page { } @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.getWriter().println("This page is secure."); } diff --git a/src/org/cacert/gigi/pages/Verify.java b/src/org/cacert/gigi/pages/Verify.java index 8d292667..32da5425 100644 --- a/src/org/cacert/gigi/pages/Verify.java +++ b/src/org/cacert/gigi/pages/Verify.java @@ -13,41 +13,37 @@ import org.cacert.gigi.database.DatabaseConnection; public class Verify extends Page { public static final String PATH = "/verify"; + public Verify() { super("Verify email"); } + @Override public boolean needsLogin() { return false; } + @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); String hash = req.getParameter("hash"); String type = req.getParameter("type"); String id = req.getParameter("id"); if ("email".equals(type)) { try { - PreparedStatement ps = DatabaseConnection - .getInstance() - .prepare( - "select email, memid from `email` where `id`=? and `hash`=? and `hash` != '' and `deleted` = 0"); + PreparedStatement ps = DatabaseConnection.getInstance().prepare( + "select email, memid from `email` where `id`=? and `hash`=? and `hash` != '' and `deleted` = 0"); ps.setString(1, id); ps.setString(2, hash); ResultSet rs = ps.executeQuery(); rs.last(); if (rs.getRow() == 1) { - PreparedStatement ps1 = DatabaseConnection - .getInstance() - .prepare( - "update `email` set `hash`='', `modified`=NOW() where `id`=?"); + PreparedStatement ps1 = DatabaseConnection.getInstance().prepare( + "update `email` set `hash`='', `modified`=NOW() where `id`=?"); ps1.setString(1, id); ps1.execute(); - PreparedStatement ps2 = DatabaseConnection - .getInstance() - .prepare( - "update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'"); + PreparedStatement ps2 = DatabaseConnection.getInstance().prepare( + "update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'"); ps2.setString(1, rs.getString(2)); ps2.setString(2, rs.getString(1)); ps2.execute(); @@ -60,9 +56,9 @@ public class Verify extends Page { } } } + @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String hash = req.getParameter("hash"); String type = req.getParameter("type"); if ("email".equals(type)) { diff --git a/src/org/cacert/gigi/pages/account/ChangeForm.java b/src/org/cacert/gigi/pages/account/ChangeForm.java index 95975ead..f69dbd11 100644 --- a/src/org/cacert/gigi/pages/account/ChangeForm.java +++ b/src/org/cacert/gigi/pages/account/ChangeForm.java @@ -13,14 +13,12 @@ import org.cacert.gigi.output.Template; public class ChangeForm extends Form { private static Template t; static { - t = new Template(new InputStreamReader( - ChangePasswordPage.class - .getResourceAsStream("ChangePasswordForm.templ"))); + t = new Template( + new InputStreamReader(ChangePasswordPage.class.getResourceAsStream("ChangePasswordForm.templ"))); } @Override - public void outputContent(PrintWriter out, Language l, - Map vars) { + public void outputContent(PrintWriter out, Language l, Map vars) { t.output(out, l, vars); } diff --git a/src/org/cacert/gigi/pages/account/ChangePasswordPage.java b/src/org/cacert/gigi/pages/account/ChangePasswordPage.java index fd4c9b2d..703bbdc3 100644 --- a/src/org/cacert/gigi/pages/account/ChangePasswordPage.java +++ b/src/org/cacert/gigi/pages/account/ChangePasswordPage.java @@ -16,10 +16,8 @@ public class ChangePasswordPage extends Page { } @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { - new ChangeForm().output(resp.getWriter(), getLanguage(req), - new HashMap()); + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + new ChangeForm().output(resp.getWriter(), getLanguage(req), new HashMap()); } } diff --git a/src/org/cacert/gigi/pages/account/MailCertificateAdd.java b/src/org/cacert/gigi/pages/account/MailCertificateAdd.java index fe93959d..f01b8f0c 100644 --- a/src/org/cacert/gigi/pages/account/MailCertificateAdd.java +++ b/src/org/cacert/gigi/pages/account/MailCertificateAdd.java @@ -20,19 +20,16 @@ public class MailCertificateAdd extends Page { } @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { HashMap vars = new HashMap(); - vars.put("CCA", - "CCA"); + vars.put("CCA", "CCA"); getDefaultTemplate().output(resp.getWriter(), getLanguage(req), vars); } + @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); - if (req.getParameter("optionalCSR") == null - || req.getParameter("optionalCSR").equals("")) { + if (req.getParameter("optionalCSR") == null || req.getParameter("optionalCSR").equals("")) { out.println("csr missing"); ClientCSRGenerate.output(req, resp); } @@ -41,8 +38,7 @@ public class MailCertificateAdd extends Page { // Error. return; } - Certificate c = new Certificate("/commonName=CAcert WoT User", - "sha256", csr); + Certificate c = new Certificate("/commonName=CAcert WoT User", "sha256", csr); c.issue(); try { c.waitFor(60000); diff --git a/src/org/cacert/gigi/pages/account/MailCertificates.java b/src/org/cacert/gigi/pages/account/MailCertificates.java index 6eae585a..72a14a31 100644 --- a/src/org/cacert/gigi/pages/account/MailCertificates.java +++ b/src/org/cacert/gigi/pages/account/MailCertificates.java @@ -27,8 +27,7 @@ public class MailCertificates extends Page { } @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); String pi = req.getPathInfo().substring(PATH.length()); if (pi.length() != 0) { @@ -51,10 +50,8 @@ public class MailCertificates extends Page { HashMap vars = new HashMap(); User us = LoginPage.getUser(req); try { - PreparedStatement ps = DatabaseConnection - .getInstance() - .prepare( - "SELECT `id`, `CN`, `serial`, `revoked`, `expire`, `disablelogin` FROM `emailcerts` WHERE `memid`=?"); + PreparedStatement ps = DatabaseConnection.getInstance().prepare( + "SELECT `id`, `CN`, `serial`, `revoked`, `expire`, `disablelogin` FROM `emailcerts` WHERE `memid`=?"); ps.setInt(1, us.getId()); ResultSet rs = ps.executeQuery(); vars.put("mailcerts", rs); diff --git a/src/org/cacert/gigi/pages/account/MailOverview.java b/src/org/cacert/gigi/pages/account/MailOverview.java index 54eda005..3e8da14a 100644 --- a/src/org/cacert/gigi/pages/account/MailOverview.java +++ b/src/org/cacert/gigi/pages/account/MailOverview.java @@ -28,14 +28,13 @@ public class MailOverview extends Page { } @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { final User us = LoginPage.getUser(req); Language lang = Page.getLanguage(req); int id = us.getId(); try { PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "SELECT * from `email` WHERE `memid`=? AND `deleted`=0"); + "SELECT * from `email` WHERE `memid`=? AND `deleted`=0"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); HashMap vars = new HashMap<>(); diff --git a/src/org/cacert/gigi/pages/account/MyDetails.java b/src/org/cacert/gigi/pages/account/MyDetails.java index 6bce47b8..753bdb2b 100644 --- a/src/org/cacert/gigi/pages/account/MyDetails.java +++ b/src/org/cacert/gigi/pages/account/MyDetails.java @@ -23,21 +23,15 @@ public class MyDetails extends Page { public static final String PATH = "/account/details"; @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { User u = (User) req.getSession().getAttribute(USER); PrintWriter out = resp.getWriter(); HashMap map = new HashMap(); map.put("fname", HTMLEncoder.encodeHTML(u.getFname())); - map.put("mname", - u.getMname() == null - ? "" - : HTMLEncoder.encodeHTML(u.getMname())); + map.put("mname", u.getMname() == null ? "" : HTMLEncoder.encodeHTML(u.getMname())); map.put("lname", HTMLEncoder.encodeHTML(u.getLname())); - map.put("suffix", - u.getSuffix() == null ? "" : HTMLEncoder.encodeHTML(u - .getSuffix())); + map.put("suffix", u.getSuffix() == null ? "" : HTMLEncoder.encodeHTML(u.getSuffix())); DateSelector ds = new DateSelector("day", "month", "year"); map.put("DoB", ds); map.put("details", ""); diff --git a/src/org/cacert/gigi/pages/error/PageNotFound.java b/src/org/cacert/gigi/pages/error/PageNotFound.java index 72057a66..0033f239 100644 --- a/src/org/cacert/gigi/pages/error/PageNotFound.java +++ b/src/org/cacert/gigi/pages/error/PageNotFound.java @@ -14,10 +14,8 @@ public class PageNotFound extends Page { } @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { - getDefaultTemplate().output(resp.getWriter(), Page.getLanguage(req), - null); + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + getDefaultTemplate().output(resp.getWriter(), Page.getLanguage(req), null); } } diff --git a/src/org/cacert/gigi/pages/main/RegisterPage.java b/src/org/cacert/gigi/pages/main/RegisterPage.java index b3819499..38c69974 100644 --- a/src/org/cacert/gigi/pages/main/RegisterPage.java +++ b/src/org/cacert/gigi/pages/main/RegisterPage.java @@ -20,14 +20,14 @@ public class RegisterPage extends Page { } @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); HashMap vars = new HashMap(); getDefaultTemplate().output(out, getLanguage(req), vars); Signup s = getForm(req); s.output(out, getLanguage(req), vars); } + public Signup getForm(HttpServletRequest req) { HttpSession hs = req.getSession(); Signup s = (Signup) hs.getAttribute(SIGNUP_PROCESS); @@ -38,26 +38,24 @@ public class RegisterPage extends Page { return s; } + @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { Signup s = getForm(req); if (s.submit(resp.getWriter(), req)) { HttpSession hs = req.getSession(); hs.setAttribute(SIGNUP_PROCESS, null); - resp.getWriter() - .println( - translate( - req, - "Your information has been submitted" - + " into our system. You will now be sent an email with a web link," - + " you need to open that link in your web browser within 24 hours" - + " or your information will be removed from our system!")); + resp.getWriter().println( + translate(req, "Your information has been submitted" + + " into our system. You will now be sent an email with a web link," + + " you need to open that link in your web browser within 24 hours" + + " or your information will be removed from our system!")); return; } super.doPost(req, resp); } + @Override public boolean needsLogin() { return false; diff --git a/src/org/cacert/gigi/pages/main/Signup.java b/src/org/cacert/gigi/pages/main/Signup.java index bd4037a1..560b2727 100644 --- a/src/org/cacert/gigi/pages/main/Signup.java +++ b/src/org/cacert/gigi/pages/main/Signup.java @@ -31,10 +31,10 @@ public class Signup extends Form { User buildup = new User(); Template t; boolean general = true, country = true, regional = true, radius = true; + public Signup() { try { - t = new Template(new InputStreamReader( - Signup.class.getResourceAsStream("Signup.templ"), "UTF-8")); + t = new Template(new InputStreamReader(Signup.class.getResourceAsStream("Signup.templ"), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } @@ -45,11 +45,11 @@ public class Signup extends Form { buildup.setEmail(""); buildup.setDob(new Date(0)); } + DateSelector myDoB = new DateSelector("day", "month", "year"); @Override - public void outputContent(PrintWriter out, Language l, - Map outerVars) { + public void outputContent(PrintWriter out, Language l, Map outerVars) { HashMap vars = new HashMap(); vars.put("fname", HTMLEncoder.encodeHTML(buildup.getFname())); vars.put("mname", HTMLEncoder.encodeHTML(buildup.getMname())); @@ -61,14 +61,11 @@ public class Signup extends Form { vars.put("country", country ? " checked=\"checked\"" : ""); vars.put("regional", regional ? " checked=\"checked\"" : ""); vars.put("radius", radius ? " checked=\"checked\"" : ""); - vars.put( - "helpOnNames", - String.format( - l.getTranslation("Help on Names %sin the wiki%s"), - "", - "")); + vars.put("helpOnNames", String.format(l.getTranslation("Help on Names %sin the wiki%s"), + "", "")); t.output(out, l, vars); } + private void update(HttpServletRequest r) { if (r.getParameter("fname") != null) { buildup.setFname(r.getParameter("fname")); @@ -106,8 +103,7 @@ public class Signup extends Form { failed = true; } if (!"1".equals(req.getParameter("cca_agree"))) { - outputError(out, req, - "You have to agree to the CAcert Community agreement."); + outputError(out, req, "You have to agree to the CAcert Community agreement."); failed = true; } if (buildup.getEmail().equals("")) { @@ -125,12 +121,8 @@ public class Signup extends Form { } int pwpoints = PasswordStrengthChecker.checkpw(pw1, buildup); if (pwpoints < 3) { - outputError( - out, - req, - "The Pass Phrase you submitted failed to contain enough" - + " differing characters and/or contained words from" - + " your name and/or email address."); + outputError(out, req, "The Pass Phrase you submitted failed to contain enough" + + " differing characters and/or contained words from" + " your name and/or email address."); failed = true; } if (failed) { @@ -139,24 +131,21 @@ public class Signup extends Form { } try { PreparedStatement q1 = DatabaseConnection.getInstance().prepare( - "select * from `email` where `email`=? and `deleted`=0"); + "select * from `email` where `email`=? and `deleted`=0"); PreparedStatement q2 = DatabaseConnection.getInstance().prepare( - "select * from `users` where `email`=? and `deleted`=0"); + "select * from `users` where `email`=? and `deleted`=0"); q1.setString(1, buildup.getEmail()); q2.setString(1, buildup.getEmail()); ResultSet r1 = q1.executeQuery(); ResultSet r2 = q2.executeQuery(); if (r1.next() || r2.next()) { - outputError(out, req, - "This email address is currently valid in the system."); + outputError(out, req, "This email address is currently valid in the system."); failed = true; } r1.close(); r2.close(); - PreparedStatement q3 = DatabaseConnection - .getInstance() - .prepare( - "select `domain` from `baddomains` where `domain`=RIGHT(?, LENGTH(`domain`))"); + PreparedStatement q3 = DatabaseConnection.getInstance().prepare( + "select `domain` from `baddomains` where `domain`=RIGHT(?, LENGTH(`domain`))"); q3.setString(1, buildup.getEmail()); ResultSet r3 = q3.executeQuery(); @@ -164,9 +153,7 @@ public class Signup extends Form { String domain = r3.getString(1); out.print("
"); out.print(String.format( - Page.translate(req, - "We don't allow signups from people using email addresses from %s"), - domain)); + Page.translate(req, "We don't allow signups from people using email addresses from %s"), domain)); out.println("
"); failed = true; } @@ -177,29 +164,20 @@ public class Signup extends Form { } String mailResult = EmailProvider.FAIL; try { - mailResult = EmailProvider.getInstance().checkEmailServer(0, - buildup.getEmail()); + mailResult = EmailProvider.getInstance().checkEmailServer(0, buildup.getEmail()); } catch (IOException e) { } if (!mailResult.equals(EmailProvider.OK)) { if (mailResult.startsWith("4")) { - outputError( - out, - req, - "The mail server responsible for your domain indicated" - + " a temporary failure. This may be due to anti-SPAM measures, such" - + " as greylisting. Please try again in a few minutes."); + outputError(out, req, "The mail server responsible for your domain indicated" + + " a temporary failure. This may be due to anti-SPAM measures, such" + + " as greylisting. Please try again in a few minutes."); } else { - outputError( - out, - req, - "Email Address given was invalid, or a test connection" - + " couldn't be made to your server, or the server" - + " rejected the email address as invalid"); + outputError(out, req, "Email Address given was invalid, or a test connection" + + " couldn't be made to your server, or the server" + " rejected the email address as invalid"); } if (mailResult.equals(EmailProvider.FAIL)) { - outputError(out, req, - "Failed to make a connection to the mail server"); + outputError(out, req, "Failed to make a connection to the mail server"); } else { out.print("
"); out.print(mailResult); @@ -220,8 +198,7 @@ public class Signup extends Form { return true; } - private void run(HttpServletRequest req, String password) - throws SQLException { + private void run(HttpServletRequest req, String password) throws SQLException { try { DatabaseConnection.getInstance().beginTransaction(); String hash = RandomToken.generateToken(16); @@ -230,32 +207,27 @@ public class Signup extends Form { buildup.insert(password); int memid = buildup.getId(); PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "insert into `email` set `email`=?," - + " `hash`=?, `created`=NOW(),`memid`=?"); + "insert into `email` set `email`=?," + " `hash`=?, `created`=NOW(),`memid`=?"); ps.setString(1, buildup.getEmail()); ps.setString(2, hash); ps.setInt(3, memid); ps.execute(); int emailid = DatabaseConnection.lastInsertId(ps); - ps = DatabaseConnection - .getInstance() - .prepare( - "insert into `alerts` set `memid`=?," - + " `general`=?, `country`=?, `regional`=?, `radius`=?"); + ps = DatabaseConnection.getInstance().prepare( + "insert into `alerts` set `memid`=?," + " `general`=?, `country`=?, `regional`=?, `radius`=?"); ps.setInt(1, memid); ps.setString(2, general ? "1" : "0"); ps.setString(3, country ? "1" : "0"); ps.setString(4, regional ? "1" : "0"); ps.setString(5, radius ? "1" : "0"); ps.execute(); - Notary.writeUserAgreement(memid, "CCA", "account creation", "", - true, 0); + Notary.writeUserAgreement(memid, "CCA", "account creation", "", true, 0); StringBuffer body = new StringBuffer(); body.append(Page - .translate( - req, - "Thanks for signing up with CAcert.org, below is the link you need to open to verify your account. Once your account is verified you will be able to start issuing certificates till your hearts' content!")); + .translate( + req, + "Thanks for signing up with CAcert.org, below is the link you need to open to verify your account. Once your account is verified you will be able to start issuing certificates till your hearts' content!")); body.append("\n\nhttps://"); body.append(ServerConstants.getWwwHostNamePort()); body.append("/verify?type=email&id="); @@ -268,9 +240,8 @@ public class Signup extends Form { body.append(Page.translate(req, "CAcert.org Support!")); try { EmailProvider.getInstance().sendmail(buildup.getEmail(), - "[CAcert.org] " + Page.translate(req, "Mail Probe"), - body.toString(), "support@cacert.org", null, null, - null, null, false); + "[CAcert.org] " + Page.translate(req, "Mail Probe"), body.toString(), "support@cacert.org", null, + null, null, null, false); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/org/cacert/gigi/pages/wot/AssuranceForm.java b/src/org/cacert/gigi/pages/wot/AssuranceForm.java index 9bb87af5..3743e321 100644 --- a/src/org/cacert/gigi/pages/wot/AssuranceForm.java +++ b/src/org/cacert/gigi/pages/wot/AssuranceForm.java @@ -23,18 +23,17 @@ public class AssuranceForm extends Form { User assuree; static final Template templ; static { - templ = new Template(new InputStreamReader( - AssuranceForm.class.getResourceAsStream("AssuranceForm.templ"))); + templ = new Template(new InputStreamReader(AssuranceForm.class.getResourceAsStream("AssuranceForm.templ"))); } public AssuranceForm(int assuree) { this.assuree = new User(assuree); } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); @Override - public void outputContent(PrintWriter out, Language l, - Map vars) { + public void outputContent(PrintWriter out, Language l, Map vars) { HashMap res = new HashMap(); res.putAll(vars); res.put("name", assuree.getName()); @@ -54,43 +53,34 @@ public class AssuranceForm extends Form { out.println("
"); boolean failed = false; - if (!"1".equals(req.getParameter("certify")) - || !"1".equals(req.getParameter("rules")) - || !"1".equals(req.getParameter("CCAAgreed")) - || !"1".equals(req.getParameter("assertion"))) { + if (!"1".equals(req.getParameter("certify")) || !"1".equals(req.getParameter("rules")) + || !"1".equals(req.getParameter("CCAAgreed")) || !"1".equals(req.getParameter("assertion"))) { outputError(out, req, "You failed to check all boxes to validate" - + " your adherence to the rules and policies of CAcert"); + + " your adherence to the rules and policies of CAcert"); failed = true; } - if (req.getParameter("date") == null - || req.getParameter("date").equals("")) { - outputError(out, req, - "You must enter the date when you met the assuree."); + if (req.getParameter("date") == null || req.getParameter("date").equals("")) { + outputError(out, req, "You must enter the date when you met the assuree."); failed = true; } else { try { Date d = sdf.parse(req.getParameter("date")); if (d.getTime() > System.currentTimeMillis()) { - outputError(out, req, - "You must not enter a date in the future."); + outputError(out, req, "You must not enter a date in the future."); failed = true; } } catch (ParseException e) { - outputError(out, req, - "You must enter the date in this format: YYYY-MM-DD."); + outputError(out, req, "You must enter the date in this format: YYYY-MM-DD."); failed = true; } } // check location, min 3 characters - if (req.getParameter("location") == null - || req.getParameter("location").equals("")) { - outputError(out, req, - "You failed to enter a location of your meeting."); + if (req.getParameter("location") == null || req.getParameter("location").equals("")) { + outputError(out, req, "You failed to enter a location of your meeting."); failed = true; } else if (req.getParameter("location").length() <= 2) { - outputError(out, req, - "You must enter a location with at least 3 characters eg town and country."); + outputError(out, req, "You must enter a location with at least 3 characters eg town and country."); failed = true; } // TODO checkPoints @@ -104,9 +94,8 @@ public class AssuranceForm extends Form { return false; } try { - AssuranceResult success = Notary.assure(LoginPage.getUser(req), - assuree, Integer.parseInt(req.getParameter("points")), - req.getParameter("location"), req.getParameter("date")); + AssuranceResult success = Notary.assure(LoginPage.getUser(req), assuree, + Integer.parseInt(req.getParameter("points")), req.getParameter("location"), req.getParameter("date")); if (success != AssuranceResult.ASSURANCE_SUCCEDED) { outputError(out, req, success.getMessage()); } diff --git a/src/org/cacert/gigi/pages/wot/AssurePage.java b/src/org/cacert/gigi/pages/wot/AssurePage.java index f553793e..70b5985e 100644 --- a/src/org/cacert/gigi/pages/wot/AssurePage.java +++ b/src/org/cacert/gigi/pages/wot/AssurePage.java @@ -30,22 +30,19 @@ public class AssurePage extends Page { public AssurePage() { super("Assure someone"); - t = new Template(new InputStreamReader( - AssuranceForm.class.getResourceAsStream("AssureeSearch.templ"))); + t = new Template(new InputStreamReader(AssuranceForm.class.getResourceAsStream("AssureeSearch.templ"))); } @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); String pi = req.getPathInfo().substring(PATH.length()); if (pi.length() > 1) { User myself = LoginPage.getUser(req); int mid = Integer.parseInt(pi.substring(1)); - AssuranceResult check = Notary.checkAssuranceIsPossible(myself, - new User(mid)); + AssuranceResult check = Notary.checkAssuranceIsPossible(myself, new User(mid)); if (check != AssuranceResult.ASSURANCE_SUCCEDED) { out.println(translate(req, check.getMessage())); return; @@ -57,16 +54,17 @@ public class AssurePage extends Page { hs.setAttribute(SESSION, form); } - form.output(out, getLanguage(req), new HashMap());; + form.output(out, getLanguage(req), new HashMap()); + ; } else { HashMap vars = new HashMap(); vars.put("DoB", ds); t.output(out, getLanguage(req), vars); } } + @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) - throws IOException { + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); String pi = req.getPathInfo().substring(PATH.length()); if (pi.length() > 1) { @@ -77,8 +75,7 @@ public class AssurePage extends Page { return; } - AssuranceForm form = (AssuranceForm) req.getSession().getAttribute( - SESSION); + AssuranceForm form = (AssuranceForm) req.getSession().getAttribute(SESSION); if (form == null) { out.println("No form found. This is an Error. Fill in the form again."); return; @@ -96,13 +93,10 @@ public class AssurePage extends Page { System.out.println("searching for"); ResultSet rs = null; try { - PreparedStatement ps = DatabaseConnection - .getInstance() - .prepare( - "SELECT id, verified FROM users WHERE email=? AND dob=? AND deleted=0"); + PreparedStatement ps = DatabaseConnection.getInstance().prepare( + "SELECT id, verified FROM users WHERE email=? AND dob=? AND deleted=0"); ps.setString(1, req.getParameter("email")); - String day = req.getParameter("year") + "-" - + req.getParameter("month") + "-" + req.getParameter("day"); + String day = req.getParameter("year") + "-" + req.getParameter("month") + "-" + req.getParameter("day"); ps.setString(2, day); rs = ps.executeQuery(); int id = 0; @@ -113,19 +107,15 @@ public class AssurePage extends Page { out.println("Error, ambigous user. Please contact support@cacert.org."); } else { if (verified == 0) { - out.println(translate(req, - "User is not yet verified. Please try again in 24 hours!")); + out.println(translate(req, "User is not yet verified. Please try again in 24 hours!")); } resp.sendRedirect(PATH + "/" + id); } } else { out.print("
"); - out.println(translate( - req, - "I'm sorry, there was no email and date of birth matching" - + " what you entered in the system. Please double check" - + " your information.")); + out.println(translate(req, "I'm sorry, there was no email and date of birth matching" + + " what you entered in the system. Please double check" + " your information.")); out.print("
"); } diff --git a/src/org/cacert/gigi/ping/DNSPinger.java b/src/org/cacert/gigi/ping/DNSPinger.java index 3231c0f0..3b459389 100644 --- a/src/org/cacert/gigi/ping/DNSPinger.java +++ b/src/org/cacert/gigi/ping/DNSPinger.java @@ -11,10 +11,8 @@ public class DNSPinger extends DomainPinger { @Override public void ping(String domain, String configuration, String expToken) { try { - Process p = Runtime.getRuntime().exec( - new String[]{"dig", "+short", "NS", domain}); - BufferedReader br = new BufferedReader(new InputStreamReader( - p.getInputStream())); + Process p = Runtime.getRuntime().exec(new String[] { "dig", "+short", "NS", domain }); + BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; LinkedList nameservers = new LinkedList(); while ((line = br.readLine()) != null) { @@ -24,13 +22,11 @@ public class DNSPinger extends DomainPinger { StringBuffer result = new StringBuffer(); result.append("failed: "); boolean failed = nameservers.isEmpty(); - nameservers : for (String NS : nameservers) { - String[] call = new String[]{"dig", "+short", "TXT", - "cacert." + domain, NS}; + nameservers: for (String NS : nameservers) { + String[] call = new String[] { "dig", "+short", "TXT", "cacert." + domain, NS }; System.out.println(Arrays.toString(call)); p = Runtime.getRuntime().exec(call); - br = new BufferedReader(new InputStreamReader( - p.getInputStream())); + br = new BufferedReader(new InputStreamReader(p.getInputStream())); String token = null; boolean found = false; while ((line = br.readLine()) != null) { diff --git a/src/org/cacert/gigi/ping/HTTPFetch.java b/src/org/cacert/gigi/ping/HTTPFetch.java index de5ec0da..b4e88ea4 100644 --- a/src/org/cacert/gigi/ping/HTTPFetch.java +++ b/src/org/cacert/gigi/ping/HTTPFetch.java @@ -11,8 +11,7 @@ public class HTTPFetch extends DomainPinger { public void ping(String domain, String configuration, String expToken) { try { URL u = new URL("http://" + domain + "/cacert_rai.txt"); - BufferedReader br = new BufferedReader(new InputStreamReader( - u.openStream(), "UTF-8")); + BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream(), "UTF-8")); String line = br.readLine(); if (line == null) { // empty diff --git a/src/org/cacert/gigi/ping/SSLPinger.java b/src/org/cacert/gigi/ping/SSLPinger.java index fd113ec2..78adc12a 100644 --- a/src/org/cacert/gigi/ping/SSLPinger.java +++ b/src/org/cacert/gigi/ping/SSLPinger.java @@ -27,22 +27,21 @@ public class SSLPinger extends DomainPinger { try { SocketChannel sch = SocketChannel.open(); String[] parts = configuration.split(":", 2); - sch.connect(new InetSocketAddress(domain, Integer - .parseInt(parts[0]))); + sch.connect(new InetSocketAddress(domain, Integer.parseInt(parts[0]))); if (parts.length == 2) { switch (parts[1]) { - case "xmpp" : - startXMPP(sch, false, domain); - break; - case "server-xmpp" : - startXMPP(sch, true, domain); - break; - case "smtp" : - startSMTP(sch); - break; - case "imap" : - startIMAP(sch); - break; + case "xmpp": + startXMPP(sch, false, domain); + break; + case "server-xmpp": + startXMPP(sch, true, domain); + break; + case "smtp": + startSMTP(sch); + break; + case "imap": + startIMAP(sch); + break; } } @@ -52,6 +51,7 @@ public class SSLPinger extends DomainPinger { } } + private void startIMAP(SocketChannel sch) throws IOException { Socket s = sch.socket(); InputStream is = s.getInputStream(); @@ -61,22 +61,21 @@ public class SSLPinger extends DomainPinger { os.flush(); scanFor(is, "\n"); } - private void startXMPP(SocketChannel sch, boolean server, String domain) - throws IOException { + + private void startXMPP(SocketChannel sch, boolean server, String domain) throws IOException { Socket s = sch.socket(); InputStream is = s.getInputStream(); OutputStream os = s.getOutputStream(); - os.write(("") - .getBytes()); + os.write(("") + .getBytes()); os.flush(); - os.write("" - .getBytes()); + os.write("".getBytes()); os.flush(); scanFor(is, ""); } + private void scanFor(InputStream is, String scanFor) throws IOException { int pos = 0; while (pos < scanFor.length()) { @@ -87,6 +86,7 @@ public class SSLPinger extends DomainPinger { } } } + private void startSMTP(SocketChannel sch) throws IOException { Socket s = sch.socket(); InputStream is = s.getInputStream(); @@ -101,6 +101,7 @@ public class SSLPinger extends DomainPinger { s.getOutputStream().flush(); readSMTP(is); } + private void readSMTP(InputStream is) throws IOException { int counter = 0; boolean finish = true; @@ -125,65 +126,60 @@ public class SSLPinger extends DomainPinger { } } } + private void test(SocketChannel sch, String domain) { try { SSLContext sc = SSLContext.getDefault(); SSLEngine se = sc.createSSLEngine(); - ByteBuffer enc_in = ByteBuffer.allocate(se.getSession() - .getPacketBufferSize()); - ByteBuffer enc_out = ByteBuffer.allocate(se.getSession() - .getPacketBufferSize()); - ByteBuffer dec_in = ByteBuffer.allocate(se.getSession() - .getApplicationBufferSize()); - ByteBuffer dec_out = ByteBuffer.allocate(se.getSession() - .getApplicationBufferSize()); + ByteBuffer enc_in = ByteBuffer.allocate(se.getSession().getPacketBufferSize()); + ByteBuffer enc_out = ByteBuffer.allocate(se.getSession().getPacketBufferSize()); + ByteBuffer dec_in = ByteBuffer.allocate(se.getSession().getApplicationBufferSize()); + ByteBuffer dec_out = ByteBuffer.allocate(se.getSession().getApplicationBufferSize()); se.setUseClientMode(true); SSLParameters sp = se.getSSLParameters(); - sp.setServerNames(Arrays. asList(new SNIHostName( - domain))); + sp.setServerNames(Arrays. asList(new SNIHostName(domain))); se.setSSLParameters(sp); se.beginHandshake(); enc_in.limit(0); while (se.getHandshakeStatus() != HandshakeStatus.FINISHED - && se.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) { + && se.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) { switch (se.getHandshakeStatus()) { - case NEED_WRAP : - dec_out.limit(0); - se.wrap(dec_out, enc_out); - enc_out.flip(); - while (enc_out.remaining() > 0) { - sch.write(enc_out); - } - enc_out.clear(); - break; - case NEED_UNWRAP : - if (enc_in.remaining() == 0) { - enc_in.clear(); - sch.read(enc_in); - enc_in.flip(); - } - while (se.unwrap(enc_in, dec_in).getStatus() == Status.BUFFER_UNDERFLOW) { - enc_in.position(enc_in.limit()); - enc_in.limit(enc_in.capacity()); - sch.read(enc_in); - enc_in.flip(); - } - enc_in.compact(); + case NEED_WRAP: + dec_out.limit(0); + se.wrap(dec_out, enc_out); + enc_out.flip(); + while (enc_out.remaining() > 0) { + sch.write(enc_out); + } + enc_out.clear(); + break; + case NEED_UNWRAP: + if (enc_in.remaining() == 0) { + enc_in.clear(); + sch.read(enc_in); + enc_in.flip(); + } + while (se.unwrap(enc_in, dec_in).getStatus() == Status.BUFFER_UNDERFLOW) { + enc_in.position(enc_in.limit()); + enc_in.limit(enc_in.capacity()); + sch.read(enc_in); enc_in.flip(); - break; - case NEED_TASK : - se.getDelegatedTask().run(); - break; - case NOT_HANDSHAKING : - case FINISHED : + } + enc_in.compact(); + enc_in.flip(); + break; + case NEED_TASK: + se.getDelegatedTask().run(); + break; + case NOT_HANDSHAKING: + case FINISHED: } } System.out.println("completed"); System.out.println(se.getSession().getCipherSuite()); - X509Certificate[] peerCertificateChain = se.getSession() - .getPeerCertificateChain(); + X509Certificate[] peerCertificateChain = se.getSession().getPeerCertificateChain(); for (X509Certificate x509Certificate : peerCertificateChain) { System.out.println(x509Certificate.getSubjectDN().getName()); } diff --git a/src/org/cacert/gigi/util/CipherInfo.java b/src/org/cacert/gigi/util/CipherInfo.java index 5860c119..4c20710a 100644 --- a/src/org/cacert/gigi/util/CipherInfo.java +++ b/src/org/cacert/gigi/util/CipherInfo.java @@ -25,8 +25,7 @@ public class CipherInfo implements Comparable { public CipherInfoGenerator() throws ReflectiveOperationException { SSLContextImpl sc = new SSLContextImpl.TLS12Context(); - Method m = SSLContextImpl.class - .getDeclaredMethod("getSupportedCipherSuiteList"); + Method m = SSLContextImpl.class.getDeclaredMethod("getSupportedCipherSuiteList"); m.setAccessible(true); Object o = m.invoke(sc); Class cipherSuiteList = o.getClass(); @@ -58,8 +57,8 @@ public class CipherInfo implements Comparable { macSize = mac.getDeclaredField("size"); macSize.setAccessible(true); } - public CipherInfo generateInfo(String suiteName) - throws IllegalArgumentException, IllegalAccessException { + + public CipherInfo generateInfo(String suiteName) throws IllegalArgumentException, IllegalAccessException { Object suite = names.get(suiteName); String keyExchange = exchange.get(suite).toString(); Object bulkCipher = cipher.get(suite); @@ -79,12 +78,12 @@ public class CipherInfo implements Comparable { padding = transformationParts[2]; } - return new CipherInfo(suiteName, keyExchange, - transformationParts[0], keysize * 8, chaining, padding, - macNam, macSiz * 8); + return new CipherInfo(suiteName, keyExchange, transformationParts[0], keysize * 8, chaining, padding, + macNam, macSiz * 8); } } + String keyExchange; String cipher; int keySize; @@ -94,9 +93,8 @@ public class CipherInfo implements Comparable { int macSize; String suiteName; - private CipherInfo(String suiteName, String keyExchange, String cipher, - int keySize, String cipherChaining, String cipherPadding, - String macName, int macSize) { + private CipherInfo(String suiteName, String keyExchange, String cipher, int keySize, String cipherChaining, + String cipherPadding, String macName, int macSize) { this.suiteName = suiteName; this.keyExchange = keyExchange; this.cipher = cipher; @@ -129,9 +127,11 @@ public class CipherInfo implements Comparable { } return null; } + public String getSuiteName() { return suiteName; } + /** * 5: ECDHE, AES||CAMELLIA, keysize >=256
* 4: DHE, AES||CAMELLIA, keysize >= 256
@@ -143,8 +143,7 @@ public class CipherInfo implements Comparable { * @return the strength */ public int getStrength() { - if (cipher.equals("NULL") || cipher.equals("RC4") - || cipher.contains("DES")) { + if (cipher.equals("NULL") || cipher.equals("RC4") || cipher.contains("DES")) { return 0; } boolean ecdhe = keyExchange.startsWith("ECDHE"); @@ -168,16 +167,16 @@ public class CipherInfo implements Comparable { } return 0; } - private static final String[] CIPHER_RANKING = new String[]{"CAMELLIA", - "AES", "RC4", "3DES", "DES", "DES40"}; + + private static final String[] CIPHER_RANKING = new String[] { "CAMELLIA", "AES", "RC4", "3DES", "DES", "DES40" }; @Override public String toString() { - return "CipherInfo [keyExchange=" + keyExchange + ", cipher=" + cipher - + ", keySize=" + keySize + ", cipherChaining=" + cipherChaining - + ", cipherPadding=" + cipherPadding + ", macName=" + macName - + ", macSize=" + macSize + "]"; + return "CipherInfo [keyExchange=" + keyExchange + ", cipher=" + cipher + ", keySize=" + keySize + + ", cipherChaining=" + cipherChaining + ", cipherPadding=" + cipherPadding + ", macName=" + macName + + ", macSize=" + macSize + "]"; } + /** * ECDHE
* GCM
@@ -255,15 +254,17 @@ public class CipherInfo implements Comparable { return suiteName.compareTo(o.suiteName); } + static String[] cipherRanking = null; + public static String[] getCompleteRanking() { if (cipherRanking == null) { - String[] ciphers = filterCiphers((Iterable) cig.names - .keySet()); + String[] ciphers = filterCiphers((Iterable) cig.names.keySet()); cipherRanking = ciphers; } return cipherRanking; } + private static String[] filterCiphers(Iterable toFilter) { TreeSet chosenCiphers = new TreeSet(); for (String o : toFilter) { @@ -282,6 +283,7 @@ public class CipherInfo implements Comparable { } return ciphers; } + public static String[] filter(String[] supportedCipherSuites) { return filterCiphers(Arrays.asList(supportedCipherSuites)); } diff --git a/src/org/cacert/gigi/util/KeyStorage.java b/src/org/cacert/gigi/util/KeyStorage.java index 2149f808..6bac57c0 100644 --- a/src/org/cacert/gigi/util/KeyStorage.java +++ b/src/org/cacert/gigi/util/KeyStorage.java @@ -11,6 +11,7 @@ public class KeyStorage { parent.mkdirs(); return new File(parent, id + ".crt"); } + public static File locateCsr(int id) { File parent = new File(csr, (id / 1000) + ""); parent.mkdirs(); diff --git a/src/org/cacert/gigi/util/Notary.java b/src/org/cacert/gigi/util/Notary.java index 515b25cd..7cd38e37 100644 --- a/src/org/cacert/gigi/util/Notary.java +++ b/src/org/cacert/gigi/util/Notary.java @@ -8,14 +8,11 @@ import org.cacert.gigi.User; import org.cacert.gigi.database.DatabaseConnection; public class Notary { - public static void writeUserAgreement(int memid, String document, - String method, String comment, boolean active, int secmemid) - throws SQLException { - PreparedStatement q = DatabaseConnection - .getInstance() - .prepare( - "insert into `user_agreements` set `memid`=?, `secmemid`=?," - + " `document`=?,`date`=NOW(), `active`=?,`method`=?,`comment`=?"); + public static void writeUserAgreement(int memid, String document, String method, String comment, boolean active, + int secmemid) throws SQLException { + PreparedStatement q = DatabaseConnection.getInstance().prepare( + "insert into `user_agreements` set `memid`=?, `secmemid`=?," + + " `document`=?,`date`=NOW(), `active`=?,`method`=?,`comment`=?"); q.setInt(1, memid); q.setInt(2, secmemid); q.setString(3, document); @@ -25,16 +22,13 @@ public class Notary { q.execute(); } - public static AssuranceResult checkAssuranceIsPossible(User assurer, - User target) { + public static AssuranceResult checkAssuranceIsPossible(User assurer, User target) { if (assurer.getId() == target.getId()) { return AssuranceResult.CANNOT_ASSURE_SELF; } try { - PreparedStatement ps = DatabaseConnection - .getInstance() - .prepare( - "SELECT 1 FROM `notary` where `to`=? and `from`=? AND `deleted`=0"); + PreparedStatement ps = DatabaseConnection.getInstance().prepare( + "SELECT 1 FROM `notary` where `to`=? and `from`=? AND `deleted`=0"); ps.setInt(1, target.getId()); ps.setInt(2, assurer.getId()); ResultSet rs = ps.executeQuery(); @@ -53,23 +47,22 @@ public class Notary { } public enum AssuranceResult { - CANNOT_ASSURE("You cannot assure."), ALREADY_ASSUREED( - "You already assured this person."), CANNOT_ASSURE_SELF( - "Cannot assure myself."), ASSURANCE_SUCCEDED(""), ASSUREE_CHANGED( - "Person details changed. Please start over again."), POINTS_OUT_OF_RANGE( - "Points out of range."); + CANNOT_ASSURE("You cannot assure."), ALREADY_ASSUREED("You already assured this person."), CANNOT_ASSURE_SELF( + "Cannot assure myself."), ASSURANCE_SUCCEDED(""), ASSUREE_CHANGED( + "Person details changed. Please start over again."), POINTS_OUT_OF_RANGE("Points out of range."); private final String message; + private AssuranceResult(String message) { this.message = message; } + public String getMessage() { return message; } } - public synchronized static AssuranceResult assure(User assurer, - User target, int awarded, String location, String date) - throws SQLException { + public synchronized static AssuranceResult assure(User assurer, User target, int awarded, String location, + String date) throws SQLException { AssuranceResult can = checkAssuranceIsPossible(assurer, target); if (can != AssuranceResult.ASSURANCE_SUCCEDED) { return can; @@ -82,10 +75,8 @@ public class Notary { return AssuranceResult.POINTS_OUT_OF_RANGE; } - PreparedStatement ps = DatabaseConnection - .getInstance() - .prepare( - "INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?"); + PreparedStatement ps = DatabaseConnection.getInstance().prepare( + "INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?"); ps.setInt(1, assurer.getId()); ps.setInt(2, target.getId()); ps.setInt(3, awarded); diff --git a/src/org/cacert/gigi/util/PasswordStrengthChecker.java b/src/org/cacert/gigi/util/PasswordStrengthChecker.java index 07898f26..cad2aba5 100644 --- a/src/org/cacert/gigi/util/PasswordStrengthChecker.java +++ b/src/org/cacert/gigi/util/PasswordStrengthChecker.java @@ -10,8 +10,10 @@ public class PasswordStrengthChecker { static Pattern upper = Pattern.compile("[A-Z]"); static Pattern whitespace = Pattern.compile("\\s"); static Pattern special = Pattern.compile("(?!\\s)\\W"); + private PasswordStrengthChecker() { } + private static int checkpwlight(String pw) { int points = 0; if (pw.length() > 15) { @@ -43,6 +45,7 @@ public class PasswordStrengthChecker { } return points; } + public static int checkpw(String pw, User u) { if (pw == null) { return 0; @@ -66,6 +69,7 @@ public class PasswordStrengthChecker { // TODO dictionary check return light; } + private static boolean contained(String pw, String check) { if (check == null || check.equals("")) { return false; diff --git a/src/org/cacert/gigi/util/RandomToken.java b/src/org/cacert/gigi/util/RandomToken.java index 7d87b7bd..b84ee037 100644 --- a/src/org/cacert/gigi/util/RandomToken.java +++ b/src/org/cacert/gigi/util/RandomToken.java @@ -4,6 +4,7 @@ import java.security.SecureRandom; public class RandomToken { static SecureRandom sr = new SecureRandom(); + public static String generateToken(int length) { StringBuffer token = new StringBuffer(); for (int i = 0; i < length; i++) { diff --git a/src/org/cacert/gigi/util/ServerConstants.java b/src/org/cacert/gigi/util/ServerConstants.java index 2f22d439..eafe9393 100644 --- a/src/org/cacert/gigi/util/ServerConstants.java +++ b/src/org/cacert/gigi/util/ServerConstants.java @@ -8,6 +8,7 @@ public class ServerConstants { private static String staticHostName = "static.cacert.local"; private static String apiHostName = "api.cacert.local"; private static String port; + public static void init(Properties conf) { port = ""; if (!conf.getProperty("port").equals("443")) { @@ -18,27 +19,35 @@ public class ServerConstants { staticHostName = conf.getProperty("name.static"); apiHostName = conf.getProperty("name.api"); } + public static String getSecureHostName() { return secureHostName; } + public static String getStaticHostName() { return staticHostName; } + public static String getWwwHostName() { return wwwHostName; } + public static String getApiHostName() { return apiHostName; } + public static String getSecureHostNamePort() { return secureHostName + port; } + public static String getStaticHostNamePort() { return staticHostName + port; } + public static String getWwwHostNamePort() { return wwwHostName + port; } + public static String getApiHostNamePort() { return apiHostName + port; } diff --git a/tests/org/cacert/gigi/LoginTest.java b/tests/org/cacert/gigi/LoginTest.java index 729a5988..f4bfe85f 100644 --- a/tests/org/cacert/gigi/LoginTest.java +++ b/tests/org/cacert/gigi/LoginTest.java @@ -12,6 +12,7 @@ import org.junit.Test; public class LoginTest extends ManagedTest { public static final String secureReference = "/account/certs/email"; + @Test public void testLoginUnverified() throws IOException { long uniq = System.currentTimeMillis(); @@ -21,6 +22,7 @@ public class LoginTest extends ManagedTest { waitForMail(); assertFalse(isLoggedin(login(email, pw))); } + @Test public void testLoginVerified() throws IOException { long uniq = System.currentTimeMillis(); @@ -29,6 +31,7 @@ public class LoginTest extends ManagedTest { createVerifiedUser("an", "bn", email, pw); assertTrue(isLoggedin(login(email, pw))); } + public boolean isLoggedin(String cookie) throws IOException { URL u = new URL("https://" + getServerName() + secureReference); HttpURLConnection huc = (HttpURLConnection) u.openConnection(); diff --git a/tests/org/cacert/gigi/TestSSL.java b/tests/org/cacert/gigi/TestSSL.java index 9756a7f3..c39b20f5 100644 --- a/tests/org/cacert/gigi/TestSSL.java +++ b/tests/org/cacert/gigi/TestSSL.java @@ -25,14 +25,13 @@ public class TestSSL extends ManagedTest { static { InitTruststore.run(); } + @Test - public void testClientIntitiatedRenegotiation() - throws NoSuchAlgorithmException, IOException { + public void testClientIntitiatedRenegotiation() throws NoSuchAlgorithmException, IOException { SSLContext sc = SSLContext.getDefault(); SSLEngine se = sc.createSSLEngine(); String[] serverParts = getServerName().split(":", 2); - SocketChannel s = SocketChannel.open(new InetSocketAddress( - serverParts[0], Integer.parseInt(serverParts[1]))); + SocketChannel s = SocketChannel.open(new InetSocketAddress(serverParts[0], Integer.parseInt(serverParts[1]))); in = ByteBuffer.allocate(se.getSession().getApplicationBufferSize()); inC = ByteBuffer.allocate(se.getSession().getPacketBufferSize()); @@ -47,34 +46,33 @@ public class TestSSL extends ManagedTest { se.beginHandshake(); try { work(se, s); - throw new Error( - "Client re-negotiation succeded (possible DoS vulnerability"); + throw new Error("Client re-negotiation succeded (possible DoS vulnerability"); } catch (EOFException e) { // Cool, server closed connection } } - private void work(SSLEngine se, SocketChannel s) throws SSLException, - IOException { + + private void work(SSLEngine se, SocketChannel s) throws SSLException, IOException { while (se.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING - && se.getHandshakeStatus() != HandshakeStatus.FINISHED) { + && se.getHandshakeStatus() != HandshakeStatus.FINISHED) { switch (se.getHandshakeStatus()) { - case NEED_WRAP : - wrap(se, s); - break; - case NEED_UNWRAP : - unwrap(se, s); - break; - case NEED_TASK : - se.getDelegatedTask().run(); - break; - default : - System.out.println(se.getHandshakeStatus()); + case NEED_WRAP: + wrap(se, s); + break; + case NEED_UNWRAP: + unwrap(se, s); + break; + case NEED_TASK: + se.getDelegatedTask().run(); + break; + default: + System.out.println(se.getHandshakeStatus()); } } } - private SSLEngineResult unwrap(SSLEngine se, SocketChannel s) - throws IOException, SSLException { + + private SSLEngineResult unwrap(SSLEngine se, SocketChannel s) throws IOException, SSLException { if (inC.remaining() == 0) { inC.clear(); s.read(inC); @@ -95,8 +93,8 @@ public class TestSSL extends ManagedTest { } return result; } - private SSLEngineResult wrap(SSLEngine se, SocketChannel s) - throws SSLException, IOException { + + private SSLEngineResult wrap(SSLEngine se, SocketChannel s) throws SSLException, IOException { outC.clear(); SSLEngineResult result = se.wrap(out, outC); outC.flip(); diff --git a/tests/org/cacert/gigi/TestSecurityHeaders.java b/tests/org/cacert/gigi/TestSecurityHeaders.java index 9df4e22c..75675c66 100644 --- a/tests/org/cacert/gigi/TestSecurityHeaders.java +++ b/tests/org/cacert/gigi/TestSecurityHeaders.java @@ -12,19 +12,17 @@ import static org.junit.Assert.*; public class TestSecurityHeaders extends ManagedTest { @Test public void testSTS() throws IOException { - HttpURLConnection uc = (HttpURLConnection) new URL("https://" - + getServerName()).openConnection(); + HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection(); assertNotNull(uc.getHeaderField("Strict-Transport-Security")); } public void testCSP() throws IOException { - HttpURLConnection uc = (HttpURLConnection) new URL("https://" - + getServerName()).openConnection(); + HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection(); assertNotNull(uc.getHeaderField("Content-Security-Policy")); } + public void testAllowOrigin() throws IOException { - HttpURLConnection uc = (HttpURLConnection) new URL("https://" - + getServerName()).openConnection(); + HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection(); assertNotNull(uc.getHeaderField("Access-Control-Allow-Origin")); } diff --git a/tests/org/cacert/gigi/TestUser.java b/tests/org/cacert/gigi/TestUser.java index 61fc7529..72d72491 100644 --- a/tests/org/cacert/gigi/TestUser.java +++ b/tests/org/cacert/gigi/TestUser.java @@ -26,8 +26,7 @@ public class TestUser extends ManagedTest { @Test public void testWebStoreAndLoad() throws SQLException { - int id = createVerifiedUser("aä", "b", createUniqueName() - + "a@email.org", "xvXV12°§"); + int id = createVerifiedUser("aä", "b", createUniqueName() + "a@email.org", "xvXV12°§"); User u = new User(id); assertEquals("aä", u.getFname()); @@ -37,8 +36,7 @@ public class TestUser extends ManagedTest { @Test public void testAssurerUtilMethods() throws SQLException { - int id = createAssuranceUser("aä", "b", createUniqueName() - + "a@email.org", "xvXV12°§"); + int id = createAssuranceUser("aä", "b", createUniqueName() + "a@email.org", "xvXV12°§"); User u = new User(id); assertTrue(u.canAssure()); diff --git a/tests/org/cacert/gigi/pages/main/RegisterPageTest.java b/tests/org/cacert/gigi/pages/main/RegisterPageTest.java index af56fdf3..87d8a9d4 100644 --- a/tests/org/cacert/gigi/pages/main/RegisterPageTest.java +++ b/tests/org/cacert/gigi/pages/main/RegisterPageTest.java @@ -21,6 +21,7 @@ public class RegisterPageTest extends ManagedTest { @Before public void setUp() throws Exception { } + @Test public void testSuccess() throws IOException { long uniq = System.currentTimeMillis(); @@ -29,14 +30,17 @@ public class RegisterPageTest extends ManagedTest { String link = tm.extractLink(); assertTrue(link, link.startsWith("https://")); } + @Test public void testNoFname() throws IOException { testFailedForm("lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=1910&cca_agree=1"); } + @Test public void testNoLname() throws IOException { testFailedForm("fname=a&email=e&pword1=ap&pword2=ap&day=1&month=1&year=1910&cca_agree=1"); } + @Test public void testNoEmail() throws IOException { testFailedForm("fname=a&lname=b&pword1=ap&pword2=ap&day=1&month=1&year=1910&cca_agree=1"); @@ -56,20 +60,24 @@ public class RegisterPageTest extends ManagedTest { public void testNoDay() throws IOException { testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&month=1&year=1910&cca_agree=1"); } + @Test public void testNoMonth() throws IOException { testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&year=1910&cca_agree=1"); } + @Test public void testNoYear() throws IOException { testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&cca_agree=1"); } + @Test public void testInvDay() throws IOException { testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=40&month=1&year=1910&cca_agree=1"); testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=0&month=1&year=1910&cca_agree=1"); testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=a&month=1&year=1910&cca_agree=1"); } + @Test public void testInvMonth() throws IOException { testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=20&year=1910&cca_agree=1"); @@ -77,6 +85,7 @@ public class RegisterPageTest extends ManagedTest { testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=-1&year=1910&cca_agree=1"); testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=a&year=1910&cca_agree=1"); } + @Test public void testInvYear() throws IOException { testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=0&cca_agree=1"); @@ -84,6 +93,7 @@ public class RegisterPageTest extends ManagedTest { testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=a&cca_agree=1"); testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=-1&cca_agree=1"); } + @Test public void testNoAgree() throws IOException { testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=1910&cca_agree=a"); @@ -92,9 +102,8 @@ public class RegisterPageTest extends ManagedTest { @Test public void testDataStays() throws IOException { long uniq = System.currentTimeMillis(); - String run = runRegister("fname=fn" + uniq + "&lname=ln" + uniq - + "&email=ma" + uniq + "@cacert.org&pword1=pas" + uniq - + "&pword2=pas2" + uniq + "&day=1&month=1&year=0"); + String run = runRegister("fname=fn" + uniq + "&lname=ln" + uniq + "&email=ma" + uniq + "@cacert.org&pword1=pas" + + uniq + "&pword2=pas2" + uniq + "&day=1&month=1&year=0"); assertTrue(run.contains("fn" + uniq)); assertTrue(run.contains("ln" + uniq)); assertTrue(run.contains("ma" + uniq + "@cacert.org")); @@ -106,48 +115,41 @@ public class RegisterPageTest extends ManagedTest { @Test public void testCheckboxesStay() throws IOException { String run2 = runRegister("general=1&country=a®ional=1&radius=0"); - assertTrue(run2 - .contains("name=\"general\" value=\"1\" checked=\"checked\">")); + assertTrue(run2.contains("name=\"general\" value=\"1\" checked=\"checked\">")); assertTrue(run2.contains("name=\"country\" value=\"1\">")); - assertTrue(run2 - .contains("name=\"regional\" value=\"1\" checked=\"checked\">")); + assertTrue(run2.contains("name=\"regional\" value=\"1\" checked=\"checked\">")); assertTrue(run2.contains("name=\"radius\" value=\"1\">")); run2 = runRegister("general=0&country=1&radius=1"); assertTrue(run2.contains("name=\"general\" value=\"1\">")); - assertTrue(run2 - .contains("name=\"country\" value=\"1\" checked=\"checked\">")); + assertTrue(run2.contains("name=\"country\" value=\"1\" checked=\"checked\">")); assertTrue(run2.contains("name=\"regional\" value=\"1\">")); - assertTrue(run2 - .contains("name=\"radius\" value=\"1\" checked=\"checked\">")); + assertTrue(run2.contains("name=\"radius\" value=\"1\" checked=\"checked\">")); } @Test public void testDoubleMail() throws IOException { long uniq = System.currentTimeMillis(); - registerUser("RegisterTest", "User", "testmail" + uniq + "@cacert.org", - "registerPW'1"); + registerUser("RegisterTest", "User", "testmail" + uniq + "@cacert.org", "registerPW'1"); try { - registerUser("RegisterTest", "User", "testmail" + uniq - + "@cacert.org", "registerPW"); - throw new Error( - "Registering a user with the same email needs to fail."); + registerUser("RegisterTest", "User", "testmail" + uniq + "@cacert.org", "registerPW"); + throw new Error("Registering a user with the same email needs to fail."); } catch (AssertionError e) { } } + @Test public void testInvalidMailbox() { getMailReciever().setApproveRegex(Pattern.compile("a")); long uniq = System.currentTimeMillis(); try { - registerUser("RegisterTest", "User", "testInvalidMailbox" + uniq - + "@cacert.org", "registerPW"); - throw new Error( - "Registering a user with invalid mailbox must fail."); + registerUser("RegisterTest", "User", "testInvalidMailbox" + uniq + "@cacert.org", "registerPW"); + throw new Error("Registering a user with invalid mailbox must fail."); } catch (AssertionError e) { } } + private void testFailedForm(String query) throws IOException { String startError = fetchStartErrorMessage(runRegister(query)); assertTrue(startError, !startError.startsWith("
")); diff --git a/tests/org/cacert/gigi/pages/wot/TestAssurance.java b/tests/org/cacert/gigi/pages/wot/TestAssurance.java index cedbcde6..42e2c18a 100644 --- a/tests/org/cacert/gigi/pages/wot/TestAssurance.java +++ b/tests/org/cacert/gigi/pages/wot/TestAssurance.java @@ -26,6 +26,7 @@ public class TestAssurance extends ManagedTest { private int assurer; private int assuree; private String cookie; + @Before public void setup() throws IOException { assurerM = createUniqueName() + "@cacert-test.org"; @@ -35,33 +36,30 @@ public class TestAssurance extends ManagedTest { cookie = login(assurerM, "xvXV.1"); } + @Test public void testAssureSearch() throws IOException { - String loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") - + "&day=1&month=1&year=1910"); + String loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=1&year=1910"); assertTrue(loc, loc.endsWith(AssurePage.PATH + "/" + assuree)); } @Test public void testAssureSearchEmail() throws IOException { - String loc = search("email=1" + URLEncoder.encode(assureeM, "UTF-8") - + "&day=1&month=1&year=1910"); + String loc = search("email=1" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=1&year=1910"); assertNull(loc); } + @Test public void testAssureSearchDob() throws IOException { - String loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") - + "&day=2&month=1&year=1910"); + String loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=2&month=1&year=1910"); assertNull(loc); - loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") - + "&day=1&month=2&year=1910"); + loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=2&year=1910"); assertNull(loc); - loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") - + "&day=1&month=1&year=1911"); + loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=1&year=1911"); assertNull(loc); } - private String search(String query) throws MalformedURLException, - IOException, UnsupportedEncodingException { + + private String search(String query) throws MalformedURLException, IOException, UnsupportedEncodingException { URL u = new URL("https://" + getServerName() + AssurePage.PATH); URLConnection uc = u.openConnection(); uc.setDoOutput(true); @@ -72,6 +70,7 @@ public class TestAssurance extends ManagedTest { String loc = uc.getHeaderField("Location"); return loc; } + @Test public void testAssureForm() throws IOException { String error = getError("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10"); @@ -82,46 +81,46 @@ public class TestAssurance extends ManagedTest { public void testAssureFormNoCSRF() throws IOException { // override csrf HttpURLConnection uc = (HttpURLConnection) buildupAssureFormConnection(false); - uc.getOutputStream() - .write(("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10") - .getBytes()); + uc.getOutputStream().write( + ("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10").getBytes()); uc.getOutputStream().flush(); assertEquals(500, uc.getResponseCode()); } + @Test public void testAssureFormWrongCSRF() throws IOException { // override csrf HttpURLConnection uc = (HttpURLConnection) buildupAssureFormConnection(false); - uc.getOutputStream() - .write(("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10&csrf=aragc") - .getBytes()); + uc.getOutputStream().write( + ("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10&csrf=aragc") + .getBytes()); uc.getOutputStream().flush(); assertEquals(500, uc.getResponseCode()); } + @Test public void testAssureFormRace() throws IOException, SQLException { URLConnection uc = buildupAssureFormConnection(true); - PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "UPDATE `users` SET email='changed' WHERE id=?"); + PreparedStatement ps = DatabaseConnection.getInstance() + .prepare("UPDATE `users` SET email='changed' WHERE id=?"); ps.setInt(1, assuree); ps.execute(); - uc.getOutputStream() - .write(("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10") - .getBytes()); + uc.getOutputStream().write( + ("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10").getBytes()); uc.getOutputStream().flush(); String error = fetchStartErrorMessage(IOUtils.readURL(uc)); assertTrue(error, !error.startsWith("
")); } + @Test public void testAssureFormFuture() throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("YYYY"); - int year = Integer.parseInt(sdf.format(new Date(System - .currentTimeMillis()))) + 2; - String error = getError("date=" - + year - + "-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10"); + int year = Integer.parseInt(sdf.format(new Date(System.currentTimeMillis()))) + 2; + String error = getError("date=" + year + + "-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10"); assertTrue(error, !error.startsWith("
")); } + @Test public void testAssureFormNoLoc() throws IOException { String error = getError("date=2000-01-01&location=a&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10"); @@ -137,6 +136,7 @@ public class TestAssurance extends ManagedTest { error = getError("date=&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10"); assertTrue(error, !error.startsWith("")); } + @Test public void testAssureFormBoxes() throws IOException { String error = getError("date=2000-01-01&location=testcase&certify=0&rules=1&CCAAgreed=1&assertion=1&points=10"); @@ -148,18 +148,17 @@ public class TestAssurance extends ManagedTest { error = getError("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=z&points=10"); assertTrue(error, !error.startsWith("")); } - private String getError(String query) throws MalformedURLException, - IOException { + + private String getError(String query) throws MalformedURLException, IOException { URLConnection uc = buildupAssureFormConnection(true); uc.getOutputStream().write((query).getBytes()); uc.getOutputStream().flush(); String error = fetchStartErrorMessage(IOUtils.readURL(uc)); return error; } - private URLConnection buildupAssureFormConnection(boolean doCSRF) - throws MalformedURLException, IOException { - URL u = new URL("https://" + getServerName() + AssurePage.PATH + "/" - + assuree); + + private URLConnection buildupAssureFormConnection(boolean doCSRF) throws MalformedURLException, IOException { + URL u = new URL("https://" + getServerName() + AssurePage.PATH + "/" + assuree); URLConnection uc = u.openConnection(); uc.addRequestProperty("Cookie", cookie); String csrf = getCSRF(uc); diff --git a/tests/org/cacert/gigi/testUtils/IOUtils.java b/tests/org/cacert/gigi/testUtils/IOUtils.java index ab18ee2e..b7452d2a 100644 --- a/tests/org/cacert/gigi/testUtils/IOUtils.java +++ b/tests/org/cacert/gigi/testUtils/IOUtils.java @@ -10,11 +10,11 @@ public class IOUtils { private IOUtils() { } + public static String readURL(URLConnection in) { try { if (!in.getContentType().equals("text/html; charset=UTF-8")) { - throw new Error("Unrecognized content-type: " - + in.getContentType()); + throw new Error("Unrecognized content-type: " + in.getContentType()); } return readURL(new InputStreamReader(in.getInputStream(), "UTF-8")); } catch (IOException e) { @@ -22,6 +22,7 @@ public class IOUtils { } } + public static String readURL(Reader in) { CharArrayWriter caw = new CharArrayWriter(); char[] buffer = new char[1024]; diff --git a/tests/org/cacert/gigi/testUtils/InitTruststore.java b/tests/org/cacert/gigi/testUtils/InitTruststore.java index 39c1d370..7811470d 100644 --- a/tests/org/cacert/gigi/testUtils/InitTruststore.java +++ b/tests/org/cacert/gigi/testUtils/InitTruststore.java @@ -3,10 +3,12 @@ package org.cacert.gigi.testUtils; public class InitTruststore { private InitTruststore() { } + static { System.setProperty("javax.net.ssl.trustStorePassword", "changeit"); System.setProperty("javax.net.ssl.trustStore", "config/cacerts.jks"); } + public static void run() { } diff --git a/tests/org/cacert/gigi/testUtils/ManagedTest.java b/tests/org/cacert/gigi/testUtils/ManagedTest.java index 9a545323..2f685dbf 100644 --- a/tests/org/cacert/gigi/testUtils/ManagedTest.java +++ b/tests/org/cacert/gigi/testUtils/ManagedTest.java @@ -42,6 +42,7 @@ public class ManagedTest { public static String getServerName() { return url; } + static Properties testProps = new Properties(); static { InitTruststore.run(); @@ -56,59 +57,44 @@ public class ManagedTest { DatabaseConnection.init(testProps); } System.out.println("... purging Database"); - DatabaseManager.run(new String[]{ - testProps.getProperty("sql.driver"), - testProps.getProperty("sql.url"), - testProps.getProperty("sql.user"), - testProps.getProperty("sql.password")}); + DatabaseManager.run(new String[] { testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"), + testProps.getProperty("sql.user"), testProps.getProperty("sql.password") }); String type = testProps.getProperty("type"); if (type.equals("local")) { url = testProps.getProperty("server"); String[] parts = testProps.getProperty("mail").split(":", 2); - ter = new TestEmailReciever(new InetSocketAddress(parts[0], - Integer.parseInt(parts[1]))); + ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1]))); return; } - url = testProps.getProperty("name.www") + ":" - + testProps.getProperty("serverPort"); + url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort"); gigi = Runtime.getRuntime().exec(testProps.getProperty("java")); - DataOutputStream toGigi = new DataOutputStream( - gigi.getOutputStream()); + DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream()); System.out.println("... starting server"); Properties mainProps = new Properties(); mainProps.setProperty("host", "127.0.0.1"); mainProps.setProperty("name.secure", "sec"); - mainProps - .setProperty("name.www", testProps.getProperty("name.www")); + mainProps.setProperty("name.www", testProps.getProperty("name.www")); mainProps.setProperty("name.static", "stat"); mainProps.setProperty("port", testProps.getProperty("serverPort")); - mainProps.setProperty("emailProvider", - "org.cacert.gigi.email.TestEmailProvider"); + mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider"); mainProps.setProperty("emailProvider.port", "8473"); - mainProps.setProperty("sql.driver", - testProps.getProperty("sql.driver")); + mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver")); mainProps.setProperty("sql.url", testProps.getProperty("sql.url")); - mainProps - .setProperty("sql.user", testProps.getProperty("sql.user")); - mainProps.setProperty("sql.password", - testProps.getProperty("sql.password")); + mainProps.setProperty("sql.user", testProps.getProperty("sql.user")); + mainProps.setProperty("sql.password", testProps.getProperty("sql.password")); - byte[] cacerts = Files - .readAllBytes(Paths.get("config/cacerts.jks")); - byte[] keystore = Files.readAllBytes(Paths - .get("config/keystore.pkcs12")); + byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks")); + byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12")); - DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), - "changeit".getBytes(), mainProps, cacerts, keystore); + DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts, + keystore); toGigi.flush(); - final BufferedReader br = new BufferedReader(new InputStreamReader( - gigi.getErrorStream())); + final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream())); String line; - while ((line = br.readLine()) != null - && !line.contains("Server:main: Started")) { + while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) { } new Thread() { @Override @@ -126,8 +112,7 @@ public class ManagedTest { if (line == null) { throw new Error("Server startup failed"); } - ter = new TestEmailReciever( - new InetSocketAddress("localhost", 8473)); + ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473)); } catch (IOException e) { throw new Error(e); } catch (ClassNotFoundException e1) { @@ -137,6 +122,7 @@ public class ManagedTest { } } + @AfterClass public static void tearDownServer() { String type = testProps.getProperty("type"); @@ -146,6 +132,7 @@ public class ManagedTest { } gigi.destroy(); } + @After public void removeMails() { ter.reset(); @@ -158,35 +145,34 @@ public class ManagedTest { throw new Error(e); } } + public static TestEmailReciever getMailReciever() { return ter; } + public String runRegister(String param) throws IOException { - HttpURLConnection uc = (HttpURLConnection) new URL("https://" - + getServerName() + registerService).openConnection(); + HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName() + registerService) + .openConnection(); uc.setDoOutput(true); uc.getOutputStream().write(param.getBytes()); String d = IOUtils.readURL(uc); return d; } + public String fetchStartErrorMessage(String d) throws IOException { String formFail = "
"; int idx = d.indexOf(formFail); assertNotEquals(-1, idx); - String startError = d.substring(idx + formFail.length(), idx + 100) - .trim(); + String startError = d.substring(idx + formFail.length(), idx + 100).trim(); return startError; } - public void registerUser(String firstName, String lastName, String email, - String password) { + public void registerUser(String firstName, String lastName, String email, String password) { try { - 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"; + 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"; String data = fetchStartErrorMessage(runRegister(query)); assertTrue(data, data.startsWith("
")); } catch (UnsupportedEncodingException e) { @@ -195,18 +181,17 @@ public class ManagedTest { throw new Error(e); } } - public int createVerifiedUser(String firstName, String lastName, - String email, String password) { + + public int createVerifiedUser(String firstName, String lastName, String email, String password) { registerUser(firstName, lastName, email, password); try { TestMail tm = ter.recieve(); String verifyLink = tm.extractLink(); String[] parts = verifyLink.split("\\?"); - URL u = new URL("https://" + getServerName() + "/verify?" - + parts[1]); - u.openStream().close();; - PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "SELECT id FROM users where email=?"); + URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]); + u.openStream().close(); + ; + PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?"); ps.setString(1, email); ResultSet rs = ps.executeQuery(); if (rs.next()) { @@ -221,6 +206,7 @@ public class ManagedTest { throw new Error(e); } } + /** * Creates a new user with 100 Assurance points given by an (invalid) * assurance. @@ -235,19 +221,15 @@ public class ManagedTest { * the password * @return a new userid. */ - public int createAssuranceUser(String firstName, String lastName, - String email, String password) { + public int createAssuranceUser(String firstName, String lastName, String email, String password) { int uid = createVerifiedUser(firstName, lastName, email, password); try { - PreparedStatement ps = DatabaseConnection - .getInstance() - .prepare( - "INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?"); + PreparedStatement ps = DatabaseConnection.getInstance().prepare( + "INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?"); ps.setInt(1, uid); ps.setInt(2, 0); ps.execute(); - ps = DatabaseConnection.getInstance().prepare( - "INSERT INTO `notary` SET `from`=?, `to`=?, points='100'"); + ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'"); ps.setInt(1, uid); ps.setInt(2, uid); ps.execute(); @@ -257,17 +239,19 @@ public class ManagedTest { } return uid; } + static int count = 0; + public String createUniqueName() { return "test" + System.currentTimeMillis() + "a" + (count++); } + public String login(String email, String pw) throws IOException { URL u = new URL("https://" + getServerName() + "/login"); HttpURLConnection huc = (HttpURLConnection) u.openConnection(); huc.setDoOutput(true); OutputStream os = huc.getOutputStream(); - String data = "username=" + URLEncoder.encode(email, "UTF-8") - + "&password=" + URLEncoder.encode(pw, "UTF-8"); + String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8"); os.write(data.getBytes()); os.flush(); String headerField = huc.getHeaderField("Set-Cookie"); diff --git a/tests/org/cacert/gigi/testUtils/TestEmailReciever.java b/tests/org/cacert/gigi/testUtils/TestEmailReciever.java index d9ffdf3f..4aa4cbfe 100644 --- a/tests/org/cacert/gigi/testUtils/TestEmailReciever.java +++ b/tests/org/cacert/gigi/testUtils/TestEmailReciever.java @@ -17,29 +17,35 @@ public class TestEmailReciever implements Runnable { String message; String from; String replyto; - public TestMail(String to, String subject, String message, String from, - String replyto) { + + public TestMail(String to, String subject, String message, String from, String replyto) { this.to = to; this.subject = subject; this.message = message; this.from = from; this.replyto = replyto; } + public String getTo() { return to; } + public String getSubject() { return subject; } + public String getMessage() { return message; } + public String getFrom() { return from; } + public String getReplyto() { return replyto; } + public String extractLink() { Pattern link = Pattern.compile("https?://[^\\s]+(?=\\s)"); Matcher m = link.matcher(getMessage()); @@ -48,6 +54,7 @@ public class TestEmailReciever implements Runnable { } } + private Socket s; private DataInputStream dis; private DataOutputStream dos; @@ -61,11 +68,13 @@ public class TestEmailReciever implements Runnable { dos = new DataOutputStream(s.getOutputStream()); new Thread(this).start(); } + LinkedBlockingQueue mails = new LinkedBlockingQueue(); public TestMail recieve() throws InterruptedException { return mails.poll(5, TimeUnit.SECONDS); } + @Override public void run() { try { @@ -98,7 +107,9 @@ public class TestEmailReciever implements Runnable { } } + Pattern approveRegex = Pattern.compile(".*"); + public void setApproveRegex(Pattern approveRegex) { this.approveRegex = approveRegex; } @@ -106,11 +117,14 @@ public class TestEmailReciever implements Runnable { public void clearMails() { mails.clear(); } + public void reset() { clearMails(); approveRegex = Pattern.compile(".*"); } + boolean closed = false; + public void destroy() { try { closed = true; diff --git a/tests/org/cacert/gigi/util/TestHTMLEncoder.java b/tests/org/cacert/gigi/util/TestHTMLEncoder.java index 7875df93..f7c21ab3 100644 --- a/tests/org/cacert/gigi/util/TestHTMLEncoder.java +++ b/tests/org/cacert/gigi/util/TestHTMLEncoder.java @@ -10,15 +10,17 @@ public class TestHTMLEncoder { public void testEncodeSimpleString() { assertEquals("1234_ä", HTMLEncoder.encodeHTML("1234_ä")); } + @Test public void testEncodeQuotes() { assertEquals("\\"_ä.", HTMLEncoder.encodeHTML("\\\"_ä.")); } + @Test public void testEncodeTagString() { - assertEquals("<td class="&amp;">", - HTMLEncoder.encodeHTML("")); + assertEquals("<td class="&amp;">", HTMLEncoder.encodeHTML("")); } + @Test public void testEncodeSingleQuoteString() { assertEquals("'&#39;", HTMLEncoder.encodeHTML("''")); diff --git a/tests/org/cacert/gigi/util/TestNotary.java b/tests/org/cacert/gigi/util/TestNotary.java index 274b3239..faccd4a4 100644 --- a/tests/org/cacert/gigi/util/TestNotary.java +++ b/tests/org/cacert/gigi/util/TestNotary.java @@ -16,28 +16,24 @@ public class TestNotary extends ManagedTest { public void testNormalAssurance() throws SQLException { User[] users = new User[30]; for (int i = 0; i < users.length; i++) { - int id = createVerifiedUser("fn" + i, "ln" + i, createUniqueName() - + "@email.org", "xvXV12°§"); + int id = createVerifiedUser("fn" + i, "ln" + i, createUniqueName() + "@email.org", "xvXV12°§"); users[i] = new User(id); } - User assurer = new User(createAssuranceUser("fn", "ln", - createUniqueName() + "@email.org", "xvXV12°§")); - int[] result = new int[]{10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, - 20, 20, 20, 25, 25, 25, 25, 25, 30, 30, 30, 30, 30, 35, 35, 35, - 35, 35, 35}; + User assurer = new User(createAssuranceUser("fn", "ln", createUniqueName() + "@email.org", "xvXV12°§")); + int[] result = new int[] { 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20, 20, 25, 25, 25, 25, 25, 30, 30, + 30, 30, 30, 35, 35, 35, 35, 35, 35 }; System.out.println(result.length); - assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure( - assurer, users[0], -1, "test-notary", "2014-01-01")); + assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, + Notary.assure(assurer, users[0], -1, "test-notary", "2014-01-01")); for (int i = 0; i < result.length; i++) { assertEquals(result[i], assurer.getMaxAssurePoints()); - assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure( - assurer, users[i], result[i] + 1, "test-notary", - "2014-01-01")); - assertEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure( - assurer, users[i], result[i], "test-notary", "2014-01-01")); - assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure( - assurer, users[i], result[i], "test-notary", "2014-01-01")); + assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, + Notary.assure(assurer, users[i], result[i] + 1, "test-notary", "2014-01-01")); + assertEquals(AssuranceResult.ASSURANCE_SUCCEDED, + Notary.assure(assurer, users[i], result[i], "test-notary", "2014-01-01")); + assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, + Notary.assure(assurer, users[i], result[i], "test-notary", "2014-01-01")); } assertEquals(35, assurer.getMaxAssurePoints()); @@ -50,26 +46,23 @@ public class TestNotary extends ManagedTest { public void testPoJam() throws SQLException { User[] users = new User[30]; for (int i = 0; i < users.length; i++) { - int id = createVerifiedUser("fn" + i, "ln" + i, createUniqueName() - + "@email.org", "xvXV12°§"); + int id = createVerifiedUser("fn" + i, "ln" + i, createUniqueName() + "@email.org", "xvXV12°§"); users[i] = new User(id); } - int id = createAssuranceUser("fn", "ln", createUniqueName() - + "@email.org", "xvXV12°§"); - PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "UPDATE users SET dob=NOW() WHERE id=?"); + int id = createAssuranceUser("fn", "ln", createUniqueName() + "@email.org", "xvXV12°§"); + PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET dob=NOW() WHERE id=?"); ps.setInt(1, id); ps.execute(); User assurer = new User(id); for (int i = 0; i < users.length; i++) { - assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure( - assurer, users[i], -1, "test-notary", "2014-01-01")); - assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure( - assurer, users[i], 11, "test-notary", "2014-01-01")); - assertEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure( - assurer, users[i], 10, "test-notary", "2014-01-01")); - assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure( - assurer, users[i], 10, "test-notary", "2014-01-01")); + assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, + Notary.assure(assurer, users[i], -1, "test-notary", "2014-01-01")); + assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, + Notary.assure(assurer, users[i], 11, "test-notary", "2014-01-01")); + assertEquals(AssuranceResult.ASSURANCE_SUCCEDED, + Notary.assure(assurer, users[i], 10, "test-notary", "2014-01-01")); + assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, + Notary.assure(assurer, users[i], 10, "test-notary", "2014-01-01")); } } } diff --git a/tests/org/cacert/gigi/util/TestPasswordHash.java b/tests/org/cacert/gigi/util/TestPasswordHash.java index 0e79ae6b..21f5f8bd 100644 --- a/tests/org/cacert/gigi/util/TestPasswordHash.java +++ b/tests/org/cacert/gigi/util/TestPasswordHash.java @@ -9,13 +9,12 @@ public class TestPasswordHash { assertTrue(PasswordHash.verifyHash("a", PasswordHash.hash("a"))); assertTrue(PasswordHash.verifyHash("", PasswordHash.hash(""))); assertTrue(PasswordHash.verifyHash("a1234", PasswordHash.hash("a1234"))); - assertTrue(PasswordHash.verifyHash("auhlcb4 9x,IUQẞ&lvrvä", - PasswordHash.hash("auhlcb4 9x,IUQẞ&lvrvä"))); + assertTrue(PasswordHash.verifyHash("auhlcb4 9x,IUQẞ&lvrvä", PasswordHash.hash("auhlcb4 9x,IUQẞ&lvrvä"))); } + @Test public void testVerifyNegative() { assertFalse(PasswordHash.verifyHash("b", PasswordHash.hash("a"))); - assertFalse(PasswordHash.verifyHash("ae", - PasswordHash.hash("auhlcb4 9x,IUQẞ&lvrvä"))); + assertFalse(PasswordHash.verifyHash("ae", PasswordHash.hash("auhlcb4 9x,IUQẞ&lvrvä"))); } } diff --git a/tests/org/cacert/gigi/util/TestPasswordStrengthChecker.java b/tests/org/cacert/gigi/util/TestPasswordStrengthChecker.java index c271735b..f57e71af 100644 --- a/tests/org/cacert/gigi/util/TestPasswordStrengthChecker.java +++ b/tests/org/cacert/gigi/util/TestPasswordStrengthChecker.java @@ -6,6 +6,7 @@ import static org.junit.Assert.*; public class TestPasswordStrengthChecker { User u; + public TestPasswordStrengthChecker() { u = new User(); u.setFname("fname"); @@ -14,17 +15,16 @@ public class TestPasswordStrengthChecker { u.setEmail("email"); u.setSuffix("suffix"); } + @Test public void testPasswordLength() { assertEquals(1, PasswordStrengthChecker.checkpw("01234", u)); assertEquals(2, PasswordStrengthChecker.checkpw("0123456789012345", u)); - assertEquals(3, - PasswordStrengthChecker.checkpw("012345678901234567890", u)); - assertEquals(4, PasswordStrengthChecker.checkpw( - "01234567890123456789012345", u)); - assertEquals(5, PasswordStrengthChecker.checkpw( - "0123456789012345678901234567890", u)); + assertEquals(3, PasswordStrengthChecker.checkpw("012345678901234567890", u)); + assertEquals(4, PasswordStrengthChecker.checkpw("01234567890123456789012345", u)); + assertEquals(5, PasswordStrengthChecker.checkpw("0123456789012345678901234567890", u)); } + @Test public void testPasswordNonASCII() { assertEquals(2, PasswordStrengthChecker.checkpw("0ä", u)); @@ -32,6 +32,7 @@ public class TestPasswordStrengthChecker { assertEquals(3, PasswordStrengthChecker.checkpw("0azä", u)); assertEquals(3, PasswordStrengthChecker.checkpw("0az.ä", u)); } + @Test public void testPasswordCharTypes() { assertEquals(1, PasswordStrengthChecker.checkpw("0", u)); @@ -56,6 +57,7 @@ public class TestPasswordStrengthChecker { assertEquals(2, PasswordStrengthChecker.checkpw(" Z", u)); } + @Test public void testPasswordContains() { assertEquals(-1, PasswordStrengthChecker.checkpw("fnamea", u)); diff --git a/util/org/cacert/gigi/util/DatabaseManager.java b/util/org/cacert/gigi/util/DatabaseManager.java index 547922e6..47108395 100644 --- a/util/org/cacert/gigi/util/DatabaseManager.java +++ b/util/org/cacert/gigi/util/DatabaseManager.java @@ -14,27 +14,24 @@ public class DatabaseManager { public static String readFile(File f) throws IOException { return new String(Files.readAllBytes(f.toPath())); } - public static void main(String[] args) throws SQLException, - ClassNotFoundException, IOException { + + public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException { if (args.length == 0) { Properties p = new Properties(); p.load(new FileReader("config/gigi.properties")); - args = new String[]{p.getProperty("sql.driver"), - p.getProperty("sql.url"), p.getProperty("sql.user"), - p.getProperty("sql.password")}; + args = new String[] { p.getProperty("sql.driver"), p.getProperty("sql.url"), p.getProperty("sql.user"), + p.getProperty("sql.password") }; } if (args.length < 4) { - System.err - .println("Usage: com.mysql.jdbc.Driver jdbc:mysql://localhost/cacert user password"); + System.err.println("Usage: com.mysql.jdbc.Driver jdbc:mysql://localhost/cacert user password"); return; } run(args); } - public static void run(String[] args) throws ClassNotFoundException, - SQLException, IOException { + + public static void run(String[] args) throws ClassNotFoundException, SQLException, IOException { Class.forName(args[0]); - Connection conn = DriverManager - .getConnection(args[1], args[2], args[3]); + Connection conn = DriverManager.getConnection(args[1], args[2], args[3]); Statement stmt = conn.createStatement(); addFile(stmt, new File("doc/tableStructure.sql")); File localData = new File("doc/sampleData.sql"); @@ -44,8 +41,8 @@ public class DatabaseManager { stmt.executeBatch(); stmt.close(); } - private static void addFile(Statement stmt, File f) throws IOException, - SQLException { + + private static void addFile(Statement stmt, File f) throws IOException, SQLException { String sql = readFile(f); String[] stmts = sql.split(";"); for (String string : stmts) { diff --git a/util/org/cacert/gigi/util/FetchLocales.java b/util/org/cacert/gigi/util/FetchLocales.java index c5378438..731ba7c8 100644 --- a/util/org/cacert/gigi/util/FetchLocales.java +++ b/util/org/cacert/gigi/util/FetchLocales.java @@ -23,13 +23,11 @@ import org.w3c.dom.Node; public class FetchLocales { public static final String DOWNLOAD_SERVER = "translations.cacert.org"; - public static final String PO_URL_TEMPLATE = "http://" + DOWNLOAD_SERVER - + "/export/cacert/%/messages.po"; - public static final String[] AUTO_LANGS = new String[]{"en", "de", "nl", - "pt_BR", "fr", "sv", "it", "es", "hu", "fi", "ja", "bg", "pt", - "da", "pl", "zh_CN", "ru", "lv", "cs", "zh_TW", "el", "tr", "ar"}; - public static void main(String[] args) throws IOException, - ParserConfigurationException, TransformerException { + public static final String PO_URL_TEMPLATE = "http://" + DOWNLOAD_SERVER + "/export/cacert/%/messages.po"; + public static final String[] AUTO_LANGS = new String[] { "en", "de", "nl", "pt_BR", "fr", "sv", "it", "es", "hu", + "fi", "ja", "bg", "pt", "da", "pl", "zh_CN", "ru", "lv", "cs", "zh_TW", "el", "tr", "ar" }; + + public static void main(String[] args) throws IOException, ParserConfigurationException, TransformerException { System.out.println("downloading locales ..."); File locale = new File("locale"); locale.mkdir(); @@ -55,8 +53,7 @@ public class FetchLocales { contents.delete(0, contents.length()); // System.out.println("msgstr"); s = readString(s, sc, contents); - String msg = contents.toString().replace("\\\"", "\"") - .replace("\\n", "\n"); + String msg = contents.toString().replace("\\\"", "\"").replace("\\n", "\n"); insertTranslation(doc, id, msg); } else if (s.startsWith("#")) { // System.out.println(s); @@ -71,16 +68,15 @@ public class FetchLocales { Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(doc); - FileOutputStream fos = new FileOutputStream(new File(locale, lang - + ".xml")); + FileOutputStream fos = new FileOutputStream(new File(locale, lang + ".xml")); StreamResult result = new StreamResult(fos); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty( - "{http://xml.apache.org/xslt}indent-amount", "2"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(source, result); fos.close(); } } + private static String readLine(Scanner sc) { String line = sc.findWithinHorizon("[^\n]*\n", 0); if (line == null) { @@ -88,6 +84,7 @@ public class FetchLocales { } return line.substring(0, line.length() - 1); } + private static void insertTranslation(Document doc, String id, String msg) { Node idN = doc.createTextNode(id); Node textN = doc.createTextNode(msg); @@ -100,8 +97,8 @@ public class FetchLocales { tr.appendChild(e); doc.getDocumentElement().appendChild(tr); } - private static String readString(String head, Scanner sc, - StringBuffer contents) throws IOException { + + private static String readString(String head, Scanner sc, StringBuffer contents) throws IOException { head = head.split(" ", 2)[1]; contents.append(head.substring(1, head.length() - 1)); String s; diff --git a/util/org/cacert/gigi/util/SimpleSigner.java b/util/org/cacert/gigi/util/SimpleSigner.java index 36da084a..d67cb8e8 100644 --- a/util/org/cacert/gigi/util/SimpleSigner.java +++ b/util/org/cacert/gigi/util/SimpleSigner.java @@ -29,19 +29,19 @@ public class SimpleSigner { DatabaseConnection.init(p); readyMail = DatabaseConnection.getInstance().prepare( - "SELECT id, csr_name, subject FROM emailcerts" + " WHERE csr_name is not null"// - + " AND created=0"// - + " AND crt_name=''"// - + " AND warning<3"); + "SELECT id, csr_name, subject FROM emailcerts" + " WHERE csr_name is not null"// + + " AND created=0"// + + " AND crt_name=''"// + + " AND warning<3"); updateMail = DatabaseConnection.getInstance().prepare( - "UPDATE emailcerts SET crt_name=?," + " created=NOW(), serial=? WHERE id=?"); + "UPDATE emailcerts SET crt_name=?," + " created=NOW(), serial=? WHERE id=?"); warnMail = DatabaseConnection.getInstance().prepare("UPDATE emailcerts SET warning=warning+1 WHERE id=?"); revoke = DatabaseConnection.getInstance().prepare( - "SELECT id, csr_name FROM emailcerts" + " WHERE csr_name is not null"// - + " AND created != 0"// - + " AND revoked = '1970-01-01'"); + "SELECT id, csr_name FROM emailcerts" + " WHERE csr_name is not null"// + + " AND created != 0"// + + " AND revoked = '1970-01-01'"); revokeCompleted = DatabaseConnection.getInstance().prepare("UPDATE emailcerts SET revoked=NOW() WHERE id=?"); gencrl(); while (true) { -- 2.39.2