From: Felix Dörre Date: Sat, 26 Jul 2014 20:57:42 +0000 (+0200) Subject: Format code according do BenBE's formatter. X-Git-Url: https://code.wpia.club/?p=gigi.git;a=commitdiff_plain;h=943d8e7ed0ea5a9d56e7e694a3cbd849c52bad16 Format code according do BenBE's formatter. --- diff --git a/src/org/cacert/gigi/Certificate.java b/src/org/cacert/gigi/Certificate.java index 7a13b45f..d7af542b 100644 --- a/src/org/cacert/gigi/Certificate.java +++ b/src/org/cacert/gigi/Certificate.java @@ -19,194 +19,198 @@ import org.cacert.gigi.util.KeyStorage; import org.cacert.gigi.util.Notary; public class Certificate { - public enum CSRType { - CSR, SPKAC; - } - - private int id; - private int ownerId; - private String serial; - private String dn; - private String md; - private String csrName; - private String crtName; - private String csr = null; - private CSRType csrType; - - public Certificate(int ownerId, String dn, String md, String csr, CSRType csrType) { - this.ownerId = ownerId; - this.dn = dn; - this.md = md; - this.csr = csr; - this.csrType = csrType; - } - - private Certificate(String serial) { - try { - PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "SELECT id,subject, md, csr_name, crt_name,memid FROM `emailcerts` WHERE serial=?"); - ps.setString(1, serial); - ResultSet rs = ps.executeQuery(); - if (!rs.next()) { - throw new IllegalArgumentException("Invalid mid " + serial); - } - this.id = rs.getInt(1); - dn = rs.getString(2); - md = rs.getString(3); - csrName = rs.getString(4); - crtName = rs.getString(5); - ownerId = rs.getInt(6); - this.serial = serial; - rs.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public enum CertificateStatus { - /** - * This certificate is not in the database, has no id and only exists as - * this java object. - */ - DRAFT(), - /** - * The certificate has been signed. It is stored in the database. - * {@link Certificate#cert()} is valid. - */ - ISSUED(), - - /** - * The certificate has been revoked. - */ - REVOKED(), - - /** - * If this certificate cannot be updated because an error happened in - * the signer. - */ - ERROR(); - - private CertificateStatus() { - } - - } - - public CertificateStatus getStatus() throws SQLException { - if (id == 0) { - return CertificateStatus.DRAFT; - } - PreparedStatement searcher = DatabaseConnection.getInstance().prepare( - "SELECT crt_name, created, revoked, serial FROM emailcerts WHERE id=?"); - searcher.setInt(1, id); - ResultSet rs = searcher.executeQuery(); - if (!rs.next()) { - throw new IllegalStateException("Certificate not in Database"); - } - - crtName = rs.getString(1); - serial = rs.getString(4); - if (rs.getTime(2) == null) { - return CertificateStatus.DRAFT; - } - if (rs.getTime(2) != null && rs.getTime(3) == null) { - return CertificateStatus.ISSUED; - } - return CertificateStatus.REVOKED; - } - - public Job issue() throws IOException, SQLException { - if (getStatus() != CertificateStatus.DRAFT) { - throw new IllegalStateException(); - } - Notary.writeUserAgreement(ownerId, "CCA", "issue certificate", "", true, 0); - - PreparedStatement inserter = DatabaseConnection.getInstance().prepare( - "INSERT INTO emailcerts SET md=?, subject=?, csr_type=?, crt_name='', memid=?"); - inserter.setString(1, md); - inserter.setString(2, dn); - inserter.setString(3, csrType.toString()); - inserter.setInt(4, ownerId); - inserter.execute(); - id = DatabaseConnection.lastInsertId(inserter); - File csrFile = KeyStorage.locateCsr(id); - csrName = csrFile.getPath(); - FileOutputStream fos = new FileOutputStream(csrFile); - fos.write(csr.getBytes()); - fos.close(); - - PreparedStatement updater = DatabaseConnection.getInstance().prepare( - "UPDATE emailcerts SET csr_name=? WHERE id=?"); - updater.setString(1, csrName); - updater.setInt(2, id); - updater.execute(); - return Job.submit(this, JobType.SIGN); - - } - - public Job revoke() throws SQLException { - if (getStatus() != CertificateStatus.ISSUED) { - throw new IllegalStateException(); - } - return Job.submit(this, JobType.REVOKE); - - } - - public X509Certificate cert() throws IOException, GeneralSecurityException, SQLException { - CertificateStatus status = getStatus(); - if (status != CertificateStatus.ISSUED) { - throw new IllegalStateException(status + " is not wanted here."); - } - InputStream is = null; - X509Certificate crt = null; - try { - is = new FileInputStream(crtName); - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - crt = (X509Certificate) cf.generateCertificate(is); - } finally { - if (is != null) { - is.close(); - } - } - return crt; - } - - public Certificate renew() { - return null; - } - - public int getId() { - return id; - } - - public String getSerial() { - try { - getStatus(); - } catch (SQLException e) { - e.printStackTrace(); - } // poll changes - return serial; - } - - public String getDistinguishedName() { - return dn; - } - - public String getMessageDigest() { - return md; - } - - public int getOwnerId() { - return ownerId; - } - - public static Certificate getBySerial(String serial) { - // TODO caching? - try { - return new Certificate(serial); - } catch (IllegalArgumentException e) { - - } - return null; - } + + public enum CSRType { + CSR, SPKAC; + } + + private int id; + + private int ownerId; + + private String serial; + + private String dn; + + private String md; + + private String csrName; + + private String crtName; + + private String csr = null; + + private CSRType csrType; + + public Certificate(int ownerId, String dn, String md, String csr, CSRType csrType) { + this.ownerId = ownerId; + this.dn = dn; + this.md = md; + this.csr = csr; + this.csrType = csrType; + } + + private Certificate(String serial) { + try { + PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id,subject, md, csr_name, crt_name,memid FROM `emailcerts` WHERE serial=?"); + ps.setString(1, serial); + ResultSet rs = ps.executeQuery(); + if ( !rs.next()) { + throw new IllegalArgumentException("Invalid mid " + serial); + } + this.id = rs.getInt(1); + dn = rs.getString(2); + md = rs.getString(3); + csrName = rs.getString(4); + crtName = rs.getString(5); + ownerId = rs.getInt(6); + this.serial = serial; + rs.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + public enum CertificateStatus { + /** + * This certificate is not in the database, has no id and only exists as + * this java object. + */ + DRAFT(), + /** + * The certificate has been signed. It is stored in the database. + * {@link Certificate#cert()} is valid. + */ + ISSUED(), + + /** + * The certificate has been revoked. + */ + REVOKED(), + + /** + * If this certificate cannot be updated because an error happened in + * the signer. + */ + ERROR(); + + private CertificateStatus() {} + + } + + public CertificateStatus getStatus() throws SQLException { + if (id == 0) { + return CertificateStatus.DRAFT; + } + PreparedStatement searcher = DatabaseConnection.getInstance().prepare("SELECT crt_name, created, revoked, serial FROM emailcerts WHERE id=?"); + searcher.setInt(1, id); + ResultSet rs = searcher.executeQuery(); + if ( !rs.next()) { + throw new IllegalStateException("Certificate not in Database"); + } + + crtName = rs.getString(1); + serial = rs.getString(4); + if (rs.getTime(2) == null) { + return CertificateStatus.DRAFT; + } + if (rs.getTime(2) != null && rs.getTime(3) == null) { + return CertificateStatus.ISSUED; + } + return CertificateStatus.REVOKED; + } + + public Job issue() throws IOException, SQLException { + if (getStatus() != CertificateStatus.DRAFT) { + throw new IllegalStateException(); + } + Notary.writeUserAgreement(ownerId, "CCA", "issue certificate", "", true, 0); + + PreparedStatement inserter = DatabaseConnection.getInstance().prepare("INSERT INTO emailcerts SET md=?, subject=?, csr_type=?, crt_name='', memid=?"); + inserter.setString(1, md); + inserter.setString(2, dn); + inserter.setString(3, csrType.toString()); + inserter.setInt(4, ownerId); + inserter.execute(); + id = DatabaseConnection.lastInsertId(inserter); + File csrFile = KeyStorage.locateCsr(id); + csrName = csrFile.getPath(); + FileOutputStream fos = new FileOutputStream(csrFile); + fos.write(csr.getBytes()); + fos.close(); + + PreparedStatement updater = DatabaseConnection.getInstance().prepare("UPDATE emailcerts SET csr_name=? WHERE id=?"); + updater.setString(1, csrName); + updater.setInt(2, id); + updater.execute(); + return Job.submit(this, JobType.SIGN); + + } + + public Job revoke() throws SQLException { + if (getStatus() != CertificateStatus.ISSUED) { + throw new IllegalStateException(); + } + return Job.submit(this, JobType.REVOKE); + + } + + public X509Certificate cert() throws IOException, GeneralSecurityException, SQLException { + CertificateStatus status = getStatus(); + if (status != CertificateStatus.ISSUED) { + throw new IllegalStateException(status + " is not wanted here."); + } + InputStream is = null; + X509Certificate crt = null; + try { + is = new FileInputStream(crtName); + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + crt = (X509Certificate) cf.generateCertificate(is); + } finally { + if (is != null) { + is.close(); + } + } + return crt; + } + + public Certificate renew() { + return null; + } + + public int getId() { + return id; + } + + public String getSerial() { + try { + getStatus(); + } catch (SQLException e) { + e.printStackTrace(); + } // poll changes + return serial; + } + + public String getDistinguishedName() { + return dn; + } + + public String getMessageDigest() { + return md; + } + + public int getOwnerId() { + return ownerId; + } + + public static Certificate getBySerial(String serial) { + // TODO caching? + try { + return new Certificate(serial); + } catch (IllegalArgumentException e) { + + } + return null; + } } diff --git a/src/org/cacert/gigi/DevelLauncher.java b/src/org/cacert/gigi/DevelLauncher.java index 3a78d628..e83ae414 100644 --- a/src/org/cacert/gigi/DevelLauncher.java +++ b/src/org/cacert/gigi/DevelLauncher.java @@ -19,66 +19,66 @@ import org.kamranzafar.jtar.TarHeader; import org.kamranzafar.jtar.TarOutputStream; public class DevelLauncher { - public static final boolean DEVEL = true; - public static void main(String[] args) throws Exception { - Properties mainProps = new Properties(); - mainProps.load(new FileInputStream("config/gigi.properties")); - for (int i = 0; i < args.length; i++) { - if (args[i].equals("--port")) { - mainProps.setProperty("port", args[i + 1]); - } - i++; - } + public static final boolean DEVEL = true; - 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")); + public static void main(String[] args) throws Exception { + Properties mainProps = new Properties(); + mainProps.load(new FileInputStream("config/gigi.properties")); + for (int i = 0; i < args.length; i++) { + if (args[i].equals("--port")) { + mainProps.setProperty("port", args[i + 1]); + } + i++; + } - 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); - BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - System.out.println("Cacert-gigi system sucessfully started."); - System.out.println("Press enter to shutdown."); - br.readLine(); - System.exit(0); - } + 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")); - 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, ""); + 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); + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Cacert-gigi system sucessfully started."); + System.out.println("Press enter to shutdown."); + br.readLine(); + System.exit(0); + } - putTarEntry(baos.toByteArray(), tos, "gigi.properties"); - putTarEntry(keystorepw, tos, "keystorepw"); - putTarEntry(truststorepw, tos, "truststorepw"); - putTarEntry(keystore, tos, "keystore.pkcs12"); - putTarEntry(cacerts, tos, "cacerts.jks"); - tos.close(); + 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, ""); - } + putTarEntry(baos.toByteArray(), tos, "gigi.properties"); + putTarEntry(keystorepw, tos, "keystorepw"); + putTarEntry(truststorepw, tos, "truststorepw"); + putTarEntry(keystore, tos, "keystore.pkcs12"); + putTarEntry(cacerts, tos, "cacerts.jks"); + tos.close(); - 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 { - dos.writeInt(chunk.length); - dos.write(chunk); - } + 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 launch(Properties props, File cacerts, File keystore) throws IOException { - ByteArrayOutputStream config = new ByteArrayOutputStream(); - props.store(config, ""); - } + 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 { + ByteArrayOutputStream config = new ByteArrayOutputStream(); + props.store(config, ""); + } } diff --git a/src/org/cacert/gigi/Digest.java b/src/org/cacert/gigi/Digest.java index e183be72..bf7cfee6 100644 --- a/src/org/cacert/gigi/Digest.java +++ b/src/org/cacert/gigi/Digest.java @@ -1,21 +1,19 @@ package org.cacert.gigi; public enum Digest { - SHA256("Currently recommended, because the other algorithms" - + " might break on some older versions of the GnuTLS library" - + " (older than 3.x) still shipped in Debian for example."), SHA384(null), SHA512( - "Highest protection against hash collision attacks of the algorithms offered here."); - final String exp; + SHA256("Currently recommended, because the other algorithms" + " might break on some older versions of the GnuTLS library" + " (older than 3.x) still shipped in Debian for example."), SHA384(null), SHA512("Highest protection against hash collision attacks of the algorithms offered here."); - private Digest(String explanation) { - exp = explanation; - } + final String exp; - public String getExp() { - return exp; - } + private Digest(String explanation) { + exp = explanation; + } - public static Digest getDefault() { - return SHA256; - } + public String getExp() { + return exp; + } + + public static Digest getDefault() { + return SHA256; + } } diff --git a/src/org/cacert/gigi/Domain.java b/src/org/cacert/gigi/Domain.java index 2aca793e..246dbc14 100644 --- a/src/org/cacert/gigi/Domain.java +++ b/src/org/cacert/gigi/Domain.java @@ -7,104 +7,101 @@ import java.sql.SQLException; import org.cacert.gigi.database.DatabaseConnection; public class Domain { - User owner; - String suffix; - int id; - - public Domain(int id) throws SQLException { - PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "SELECT memid, domain FROM `domain` WHERE id=? AND deleted IS NULL"); - ps.setInt(1, id); - - ResultSet rs = ps.executeQuery(); - if (!rs.next()) { - throw new IllegalArgumentException("Invalid email id " + id); - } - this.id = id; - owner = User.getById(rs.getInt(1)); - suffix = rs.getString(2); - rs.close(); - } - - public Domain(User owner, String suffix) throws GigiApiException { - this.owner = owner; - this.suffix = suffix; - - } - - private static void checkInsert(String suffix) throws GigiApiException { - try { - PreparedStatement ps = DatabaseConnection - .getInstance() - .prepare( - "SELECT 1 FROM `domain` WHERE (domain=RIGHT(?,LENGTH(domain)) OR RIGHT(domain,LENGTH(?))=?) AND deleted IS NULL"); - ps.setString(1, suffix); - ps.setString(2, suffix); - ps.setString(3, suffix); - ResultSet rs = ps.executeQuery(); - boolean existed = rs.next(); - rs.close(); - if (existed) { - throw new GigiApiException("Domain could not be inserted. Domain is already valid."); - } - } catch (SQLException e) { - throw new GigiApiException(e); - } - } - - public void insert() throws GigiApiException { - if (id != 0) { - throw new GigiApiException("already inserted."); - } - synchronized (Domain.class) { - checkInsert(suffix); - try { - PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "INSERT INTO `domain` SET memid=?, domain=?"); - ps.setInt(1, owner.getId()); - ps.setString(2, suffix); - ps.execute(); - id = DatabaseConnection.lastInsertId(ps); - } catch (SQLException e) { - throw new GigiApiException(e); - } - } - } - - public void delete() throws GigiApiException { - if (id == 0) { - throw new GigiApiException("not inserted."); - } - try { - PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "UPDATE `domain` SET deleted=CURRENT_TIMESTAMP WHERE id=?"); - ps.setInt(1, id); - ps.execute(); - } catch (SQLException e) { - throw new GigiApiException(e); - } - } - - public User getOwner() { - return owner; - } - - public int getId() { - return id; - } - - public String getSuffix() { - return suffix; - } - - public static Domain getById(int id) throws IllegalArgumentException { - // TODO cache - try { - Domain e = new Domain(id); - return e; - } catch (SQLException e) { - throw new IllegalArgumentException(e); - } - } + + User owner; + + String suffix; + + int id; + + public Domain(int id) throws SQLException { + PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT memid, domain FROM `domain` WHERE id=? AND deleted IS NULL"); + ps.setInt(1, id); + + ResultSet rs = ps.executeQuery(); + if ( !rs.next()) { + throw new IllegalArgumentException("Invalid email id " + id); + } + this.id = id; + owner = User.getById(rs.getInt(1)); + suffix = rs.getString(2); + rs.close(); + } + + public Domain(User owner, String suffix) throws GigiApiException { + this.owner = owner; + this.suffix = suffix; + + } + + private static void checkInsert(String suffix) throws GigiApiException { + try { + PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `domain` WHERE (domain=RIGHT(?,LENGTH(domain)) OR RIGHT(domain,LENGTH(?))=?) AND deleted IS NULL"); + ps.setString(1, suffix); + ps.setString(2, suffix); + ps.setString(3, suffix); + ResultSet rs = ps.executeQuery(); + boolean existed = rs.next(); + rs.close(); + if (existed) { + throw new GigiApiException("Domain could not be inserted. Domain is already valid."); + } + } catch (SQLException e) { + throw new GigiApiException(e); + } + } + + public void insert() throws GigiApiException { + if (id != 0) { + throw new GigiApiException("already inserted."); + } + synchronized (Domain.class) { + checkInsert(suffix); + try { + PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `domain` SET memid=?, domain=?"); + ps.setInt(1, owner.getId()); + ps.setString(2, suffix); + ps.execute(); + id = DatabaseConnection.lastInsertId(ps); + } catch (SQLException e) { + throw new GigiApiException(e); + } + } + } + + public void delete() throws GigiApiException { + if (id == 0) { + throw new GigiApiException("not inserted."); + } + try { + PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `domain` SET deleted=CURRENT_TIMESTAMP WHERE id=?"); + ps.setInt(1, id); + ps.execute(); + } catch (SQLException e) { + throw new GigiApiException(e); + } + } + + public User getOwner() { + return owner; + } + + public int getId() { + return id; + } + + public String getSuffix() { + return suffix; + } + + public static Domain getById(int id) throws IllegalArgumentException { + // TODO cache + try { + Domain e = new Domain(id); + return e; + } catch (SQLException e) { + throw new IllegalArgumentException(e); + } + } } diff --git a/src/org/cacert/gigi/EmailAddress.java b/src/org/cacert/gigi/EmailAddress.java index a2a7e580..365e9538 100644 --- a/src/org/cacert/gigi/EmailAddress.java +++ b/src/org/cacert/gigi/EmailAddress.java @@ -11,115 +11,113 @@ import org.cacert.gigi.util.RandomToken; import org.cacert.gigi.util.ServerConstants; public class EmailAddress { - private String address; - private int id; - private User owner; - private String hash = null; - - private EmailAddress(int id) throws SQLException { - PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "SELECT memid, email, hash FROM `email` WHERE id=? AND deleted=0"); - ps.setInt(1, id); - - ResultSet rs = ps.executeQuery(); - if (!rs.next()) { - throw new IllegalArgumentException("Invalid email id " + id); - } - this.id = id; - owner = User.getById(rs.getInt(1)); - address = rs.getString(2); - hash = rs.getString(3); - rs.close(); - } - - public EmailAddress(String address, User owner) { - if (!EmailProvider.MAIL.matcher(address).matches()) { - throw new IllegalArgumentException("Invalid email."); - } - this.address = address; - this.owner = owner; - this.hash = RandomToken.generateToken(16); - } - - public void insert(Language l) { - if (id != 0) { - throw new IllegalStateException("already inserted."); - } - try { - PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "INSERT INTO `email` SET memid=?, hash=?, email=?"); - ps.setInt(1, owner.getId()); - ps.setString(2, hash); - ps.setString(3, address); - ps.execute(); - id = DatabaseConnection.lastInsertId(ps); - StringBuffer body = new StringBuffer(); - body.append(l - .getTranslation("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="); - body.append(id); - body.append("&hash="); - body.append(hash); - body.append("\n\n"); - body.append(l.getTranslation("Best regards")); - body.append("\n"); - body.append(l.getTranslation("CAcert.org Support!")); - EmailProvider.getInstance().sendmail(address, "[CAcert.org] " + l.getTranslation("Mail Probe"), - body.toString(), "support@cacert.org", null, null, null, null, false); - } catch (SQLException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public int getId() { - return id; - } - - public String getAddress() { - return address; - } - - public synchronized void verify(String hash) throws GigiApiException { - if (this.hash.equals(hash)) { - - try { - PreparedStatement ps = DatabaseConnection.getInstance() - .prepare("UPDATE `email` SET hash='' WHERE id=?"); - ps.setInt(1, id); - ps.execute(); - hash = ""; - - // Verify user with that primary email - PreparedStatement ps2 = DatabaseConnection.getInstance().prepare( - "update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'"); - ps2.setInt(1, owner.getId()); - ps2.setString(2, address); - ps2.execute(); - this.hash = ""; - } catch (SQLException e) { - throw new GigiApiException(e); - } - - } else { - throw new GigiApiException("Email verification hash is invalid."); - } - } - - public static EmailAddress getById(int id) throws IllegalArgumentException { - // TODO cache - try { - EmailAddress e = new EmailAddress(id); - return e; - } catch (SQLException e) { - throw new IllegalArgumentException(e); - } - } - - public boolean isVerified() { - return hash.isEmpty(); - } + + private String address; + + private int id; + + private User owner; + + private String hash = null; + + private EmailAddress(int id) throws SQLException { + PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT memid, email, hash FROM `email` WHERE id=? AND deleted=0"); + ps.setInt(1, id); + + ResultSet rs = ps.executeQuery(); + if ( !rs.next()) { + throw new IllegalArgumentException("Invalid email id " + id); + } + this.id = id; + owner = User.getById(rs.getInt(1)); + address = rs.getString(2); + hash = rs.getString(3); + rs.close(); + } + + public EmailAddress(String address, User owner) { + if ( !EmailProvider.MAIL.matcher(address).matches()) { + throw new IllegalArgumentException("Invalid email."); + } + this.address = address; + this.owner = owner; + this.hash = RandomToken.generateToken(16); + } + + public void insert(Language l) { + if (id != 0) { + throw new IllegalStateException("already inserted."); + } + try { + PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `email` SET memid=?, hash=?, email=?"); + ps.setInt(1, owner.getId()); + ps.setString(2, hash); + ps.setString(3, address); + ps.execute(); + id = DatabaseConnection.lastInsertId(ps); + StringBuffer body = new StringBuffer(); + body.append(l.getTranslation("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="); + body.append(id); + body.append("&hash="); + body.append(hash); + body.append("\n\n"); + body.append(l.getTranslation("Best regards")); + body.append("\n"); + body.append(l.getTranslation("CAcert.org Support!")); + EmailProvider.getInstance().sendmail(address, "[CAcert.org] " + l.getTranslation("Mail Probe"), body.toString(), "support@cacert.org", null, null, null, null, false); + } catch (SQLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public int getId() { + return id; + } + + public String getAddress() { + return address; + } + + public synchronized void verify(String hash) throws GigiApiException { + if (this.hash.equals(hash)) { + + try { + PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE `email` SET hash='' WHERE id=?"); + ps.setInt(1, id); + ps.execute(); + hash = ""; + + // Verify user with that primary email + PreparedStatement ps2 = DatabaseConnection.getInstance().prepare("update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'"); + ps2.setInt(1, owner.getId()); + ps2.setString(2, address); + ps2.execute(); + this.hash = ""; + } catch (SQLException e) { + throw new GigiApiException(e); + } + + } else { + throw new GigiApiException("Email verification hash is invalid."); + } + } + + public static EmailAddress getById(int id) throws IllegalArgumentException { + // TODO cache + try { + EmailAddress e = new EmailAddress(id); + return e; + } catch (SQLException e) { + throw new IllegalArgumentException(e); + } + } + + public boolean isVerified() { + return hash.isEmpty(); + } } diff --git a/src/org/cacert/gigi/Gigi.java b/src/org/cacert/gigi/Gigi.java index 9d1bb1b9..5590663d 100644 --- a/src/org/cacert/gigi/Gigi.java +++ b/src/org/cacert/gigi/Gigi.java @@ -36,159 +36,161 @@ import org.cacert.gigi.pages.wot.AssurePage; import org.cacert.gigi.util.ServerConstants; public class Gigi extends HttpServlet { - public static final String LOGGEDIN = "loggedin"; - public static final String USER = "user"; - private static final long serialVersionUID = -6386785421902852904L; - private Template baseTemplate; - private HashMap pages = new HashMap(); - Menu m; - - public Gigi(Properties conf) { - EmailProvider.init(conf); - DatabaseConnection.init(conf); - } - - @Override - public void init() throws ServletException { - pages.put("/error", new PageNotFound()); - pages.put("/login", new LoginPage("CACert - Login")); - pages.put("/", new MainPage("CACert - Home")); - pages.put("/secure", new TestSecure()); - pages.put(Verify.PATH, new Verify()); - pages.put(AssurePage.PATH + "/*", new AssurePage()); - pages.put(MailCertificates.PATH + "/*", new MailCertificates()); - pages.put(MyDetails.PATH, new MyDetails()); - pages.put(ChangePasswordPage.PATH, new ChangePasswordPage()); - pages.put(RegisterPage.PATH, new RegisterPage()); - pages.put(MailCertificateAdd.PATH, new MailCertificateAdd()); - pages.put(MailOverview.DEFAULT_PATH, new MailOverview("My email addresses")); - baseTemplate = new Template(Gigi.class.getResource("Gigi.templ")); - m = new Menu("Certificates", "cert", new MenuItem(MailOverview.DEFAULT_PATH, "Emails"), new MenuItem("", - "Client Certificates"), new MenuItem("", "Domains"), new MenuItem("", "Server Certificates")); - super.init(); - - } - - @Override - protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, - IOException { - addXSSHeaders(resp); - // if (req.getHeader("Origin") != null) { - // resp.getWriter().println("No cross domain access allowed."); - // return; - // } - HttpSession hs = req.getSession(); - if (req.getPathInfo() != null && req.getPathInfo().equals("/logout")) { - if (hs != null) { - hs.setAttribute(LOGGEDIN, null); - hs.invalidate(); - } - resp.sendRedirect("/"); - return; - } - - final Page p = getPage(req.getPathInfo()); - if (p != null) { - - if (p.needsLogin() && hs.getAttribute("loggedin") == null) { - String request = req.getPathInfo(); - request = request.split("\\?")[0]; - hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request); - resp.sendRedirect("/login"); - return; - } - if (p.beforeTemplate(req, resp)) { - return; - } - HashMap vars = new HashMap(); - - resp.setContentType("text/html; charset=utf-8"); - Outputable content = new Outputable() { - - @Override - public void output(PrintWriter out, Language l, Map vars) { - try { - if (req.getMethod().equals("POST")) { - if (req.getQueryString() != null) { - return; - } - p.doPost(req, resp); - } else { - p.doGet(req, resp); - } - } catch (CSRFException err) { - try { - resp.sendError(500, "CSRF invalid"); - } catch (IOException e) { - e.printStackTrace(); - } - } catch (IOException e) { - e.printStackTrace(); - } - - } - }; - vars.put("menu", m); - vars.put("title", p.getTitle()); - vars.put("static", ServerConstants.getStaticHostNamePort()); - vars.put("year", Calendar.getInstance().get(Calendar.YEAR)); - vars.put("content", content); - baseTemplate.output(resp.getWriter(), Page.getLanguage(req), vars); - } else { - resp.sendError(404, "Page not found."); - } - - } - - private Page getPage(String pathInfo) { - if (pathInfo.endsWith("/") && !pathInfo.equals("/")) { - pathInfo = pathInfo.substring(0, pathInfo.length() - 1); - } - Page page = pages.get(pathInfo); - if (page != null) { - return page; - } - page = pages.get(pathInfo + "/*"); - if (page != null) { - return page; - } - int idx = pathInfo.lastIndexOf('/'); - pathInfo = pathInfo.substring(0, idx); - - page = pages.get(pathInfo + "/*"); - if (page != null) { - return page; - } - return null; - - } - - public static void addXSSHeaders(HttpServletResponse hsr) { - hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePort() + " https://" - + ServerConstants.getSecureHostNamePort()); - hsr.addHeader("Access-Control-Max-Age", "60"); - - hsr.addHeader("Content-Security-Policy", getDefaultCSP()); - hsr.addHeader("Strict-Transport-Security", "max-age=31536000"); - - } - - private static String defaultCSP = null; - - private static String getDefaultCSP() { - if (defaultCSP == null) { - StringBuffer csp = new StringBuffer(); - csp.append("default-src 'none';"); - csp.append("font-src https://" + ServerConstants.getStaticHostNamePort()); - csp.append(";img-src https://" + ServerConstants.getStaticHostNamePort()); - csp.append(";media-src 'none'; object-src 'none';"); - csp.append("script-src https://" + ServerConstants.getStaticHostNamePort()); - csp.append(";style-src https://" + ServerConstants.getStaticHostNamePort()); - csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" - + ServerConstants.getWwwHostNamePort()); - csp.append("report-url https://api.cacert.org/security/csp/report"); - defaultCSP = csp.toString(); - } - return defaultCSP; - } + + public static final String LOGGEDIN = "loggedin"; + + public static final String USER = "user"; + + private static final long serialVersionUID = -6386785421902852904L; + + private Template baseTemplate; + + private HashMap pages = new HashMap(); + + Menu m; + + public Gigi(Properties conf) { + EmailProvider.init(conf); + DatabaseConnection.init(conf); + } + + @Override + public void init() throws ServletException { + pages.put("/error", new PageNotFound()); + pages.put("/login", new LoginPage("CACert - Login")); + pages.put("/", new MainPage("CACert - Home")); + pages.put("/secure", new TestSecure()); + pages.put(Verify.PATH, new Verify()); + pages.put(AssurePage.PATH + "/*", new AssurePage()); + pages.put(MailCertificates.PATH + "/*", new MailCertificates()); + pages.put(MyDetails.PATH, new MyDetails()); + pages.put(ChangePasswordPage.PATH, new ChangePasswordPage()); + pages.put(RegisterPage.PATH, new RegisterPage()); + pages.put(MailCertificateAdd.PATH, new MailCertificateAdd()); + pages.put(MailOverview.DEFAULT_PATH, new MailOverview("My email addresses")); + baseTemplate = new Template(Gigi.class.getResource("Gigi.templ")); + m = new Menu("Certificates", "cert", new MenuItem(MailOverview.DEFAULT_PATH, "Emails"), new MenuItem("", "Client Certificates"), new MenuItem("", "Domains"), new MenuItem("", "Server Certificates")); + super.init(); + + } + + @Override + protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { + addXSSHeaders(resp); + // if (req.getHeader("Origin") != null) { + // resp.getWriter().println("No cross domain access allowed."); + // return; + // } + HttpSession hs = req.getSession(); + if (req.getPathInfo() != null && req.getPathInfo().equals("/logout")) { + if (hs != null) { + hs.setAttribute(LOGGEDIN, null); + hs.invalidate(); + } + resp.sendRedirect("/"); + return; + } + + final Page p = getPage(req.getPathInfo()); + if (p != null) { + + if (p.needsLogin() && hs.getAttribute("loggedin") == null) { + String request = req.getPathInfo(); + request = request.split("\\?")[0]; + hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request); + resp.sendRedirect("/login"); + return; + } + if (p.beforeTemplate(req, resp)) { + return; + } + HashMap vars = new HashMap(); + + resp.setContentType("text/html; charset=utf-8"); + Outputable content = new Outputable() { + + @Override + public void output(PrintWriter out, Language l, Map vars) { + try { + if (req.getMethod().equals("POST")) { + if (req.getQueryString() != null) { + return; + } + p.doPost(req, resp); + } else { + p.doGet(req, resp); + } + } catch (CSRFException err) { + try { + resp.sendError(500, "CSRF invalid"); + } catch (IOException e) { + e.printStackTrace(); + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + }; + vars.put("menu", m); + vars.put("title", p.getTitle()); + vars.put("static", ServerConstants.getStaticHostNamePort()); + vars.put("year", Calendar.getInstance().get(Calendar.YEAR)); + vars.put("content", content); + baseTemplate.output(resp.getWriter(), Page.getLanguage(req), vars); + } else { + resp.sendError(404, "Page not found."); + } + + } + + private Page getPage(String pathInfo) { + if (pathInfo.endsWith("/") && !pathInfo.equals("/")) { + pathInfo = pathInfo.substring(0, pathInfo.length() - 1); + } + Page page = pages.get(pathInfo); + if (page != null) { + return page; + } + page = pages.get(pathInfo + "/*"); + if (page != null) { + return page; + } + int idx = pathInfo.lastIndexOf('/'); + pathInfo = pathInfo.substring(0, idx); + + page = pages.get(pathInfo + "/*"); + if (page != null) { + return page; + } + return null; + + } + + public static void addXSSHeaders(HttpServletResponse hsr) { + hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePort() + " https://" + ServerConstants.getSecureHostNamePort()); + hsr.addHeader("Access-Control-Max-Age", "60"); + + hsr.addHeader("Content-Security-Policy", getDefaultCSP()); + hsr.addHeader("Strict-Transport-Security", "max-age=31536000"); + + } + + private static String defaultCSP = null; + + private static String getDefaultCSP() { + if (defaultCSP == null) { + StringBuffer csp = new StringBuffer(); + csp.append("default-src 'none';"); + csp.append("font-src https://" + ServerConstants.getStaticHostNamePort()); + csp.append(";img-src https://" + ServerConstants.getStaticHostNamePort()); + csp.append(";media-src 'none'; object-src 'none';"); + csp.append("script-src https://" + ServerConstants.getStaticHostNamePort()); + csp.append(";style-src https://" + ServerConstants.getStaticHostNamePort()); + csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort()); + csp.append("report-url https://api.cacert.org/security/csp/report"); + defaultCSP = csp.toString(); + } + return defaultCSP; + } } diff --git a/src/org/cacert/gigi/GigiApiException.java b/src/org/cacert/gigi/GigiApiException.java index 7b91d125..430c199b 100644 --- a/src/org/cacert/gigi/GigiApiException.java +++ b/src/org/cacert/gigi/GigiApiException.java @@ -5,53 +5,55 @@ import java.sql.SQLException; import java.util.LinkedList; public class GigiApiException extends Exception { - SQLException e; - LinkedList messages = new LinkedList<>(); - - public GigiApiException(SQLException e) { - super(e); - this.e = e; - } - - public GigiApiException(String message) { - super(message); - messages.add(message); - } - - public GigiApiException() { - - } - - public void mergeInto(GigiApiException e2) { - messages.addAll(e2.messages); - if (e == null) { - e = e2.e; - } - } - - public boolean isInternalError() { - return e != null; - } - - public void format(PrintWriter out, Language language) { - out.println("
"); - if (isInternalError()) { - e.printStackTrace(); - out.print("
"); - out.println(language.getTranslation("An internal error ouccured.")); - out.println("
"); - } - for (String message : messages) { - out.print("
"); - out.print(language.getTranslation(message)); - out.println("
"); - } - out.println("
"); - - } - - public boolean isEmpty() { - return e == null && messages.size() == 0; - } + + SQLException e; + + LinkedList messages = new LinkedList<>(); + + public GigiApiException(SQLException e) { + super(e); + this.e = e; + } + + public GigiApiException(String message) { + super(message); + messages.add(message); + } + + public GigiApiException() { + + } + + public void mergeInto(GigiApiException e2) { + messages.addAll(e2.messages); + if (e == null) { + e = e2.e; + } + } + + public boolean isInternalError() { + return e != null; + } + + public void format(PrintWriter out, Language language) { + out.println("
"); + if (isInternalError()) { + e.printStackTrace(); + out.print("
"); + out.println(language.getTranslation("An internal error ouccured.")); + out.println("
"); + } + for (String message : messages) { + out.print("
"); + out.print(language.getTranslation(message)); + out.println("
"); + } + out.println("
"); + + } + + public boolean isEmpty() { + return e == null && messages.size() == 0; + } } diff --git a/src/org/cacert/gigi/GigiConfig.java b/src/org/cacert/gigi/GigiConfig.java index 86738007..4c36302a 100644 --- a/src/org/cacert/gigi/GigiConfig.java +++ b/src/org/cacert/gigi/GigiConfig.java @@ -12,84 +12,89 @@ import org.kamranzafar.jtar.TarEntry; import org.kamranzafar.jtar.TarInputStream; public class GigiConfig { - public static final String GIGI_CONFIG_VERSION = "GigiConfigV1.0"; - byte[] cacerts; - byte[] keystore; - Properties mainProps = new Properties(); - private char[] keystorpw; - private char[] truststorepw; - - private GigiConfig() { - } - - public byte[] getCacerts() { - return cacerts; - } - - public byte[] getKeystore() { - return keystore; - } - - public Properties getMainProps() { - return mainProps; - } - - public static GigiConfig parse(InputStream input) throws IOException { - TarInputStream tis = new TarInputStream(input); - TarEntry t; - GigiConfig gc = new GigiConfig(); - while ((t = tis.getNextEntry()) != null) { - if (t.getName().equals("gigi.properties")) { - gc.mainProps.load(tis); - } else if (t.getName().equals("cacerts.jks")) { - gc.cacerts = readFully(tis); - } else if (t.getName().equals("keystore.pkcs12")) { - gc.keystore = readFully(tis); - } else if (t.getName().equals("keystorepw")) { - gc.keystorpw = transformSafe(readFully(tis)); - } else if (t.getName().equals("truststorepw")) { - gc.truststorepw = transformSafe(readFully(tis)); - } else { - System.out.println("Unknown config: " + t.getName()); - } - } - tis.close(); - return gc; - } - - public static byte[] readFully(InputStream is) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - int len = 0; - while ((len = is.read(buffer)) > 0) { - baos.write(buffer, 0, len); - } - 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++) { - res[i] = (char) readChunk[i]; - readChunk[i] = 0; - } - return res; - } - - 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 { - KeyStore ks1 = KeyStore.getInstance("jks"); - ks1.load(new ByteArrayInputStream(cacerts), truststorepw); - return ks1; - } - - public String getPrivateStorePw() { - return new String(keystorpw); - } + + public static final String GIGI_CONFIG_VERSION = "GigiConfigV1.0"; + + byte[] cacerts; + + byte[] keystore; + + Properties mainProps = new Properties(); + + private char[] keystorpw; + + private char[] truststorepw; + + private GigiConfig() {} + + public byte[] getCacerts() { + return cacerts; + } + + public byte[] getKeystore() { + return keystore; + } + + public Properties getMainProps() { + return mainProps; + } + + public static GigiConfig parse(InputStream input) throws IOException { + TarInputStream tis = new TarInputStream(input); + TarEntry t; + GigiConfig gc = new GigiConfig(); + while ((t = tis.getNextEntry()) != null) { + if (t.getName().equals("gigi.properties")) { + gc.mainProps.load(tis); + } else if (t.getName().equals("cacerts.jks")) { + gc.cacerts = readFully(tis); + } else if (t.getName().equals("keystore.pkcs12")) { + gc.keystore = readFully(tis); + } else if (t.getName().equals("keystorepw")) { + gc.keystorpw = transformSafe(readFully(tis)); + } else if (t.getName().equals("truststorepw")) { + gc.truststorepw = transformSafe(readFully(tis)); + } else { + System.out.println("Unknown config: " + t.getName()); + } + } + tis.close(); + return gc; + } + + public static byte[] readFully(InputStream is) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int len = 0; + while ((len = is.read(buffer)) > 0) { + baos.write(buffer, 0, len); + } + 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++) { + res[i] = (char) readChunk[i]; + readChunk[i] = 0; + } + return res; + } + + 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 { + 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 75593ccf..6c03b19c 100644 --- a/src/org/cacert/gigi/Language.java +++ b/src/org/cacert/gigi/Language.java @@ -17,61 +17,64 @@ import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class Language { - private static HashMap langs = new HashMap(); - HashMap translations = new HashMap(); - Locale l; - private Language(String language) throws ParserConfigurationException, IOException, SAXException { - if (language.contains("_")) { - String[] parts = language.split("_"); - l = new Locale(parts[0], parts[1]); - } else { - l = new Locale(language); - } + private static HashMap langs = new HashMap(); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - 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)) { - continue; - } - Element e = (Element) nl.item(i); - Element id = (Element) e.getElementsByTagName("id").item(0); - Element msg = (Element) e.getElementsByTagName("msg").item(0); - translations.put(id.getTextContent(), HTMLEncoder.encodeHTML(msg.getTextContent())); - } - System.out.println(translations.size() + " strings loaded."); - } + HashMap translations = new HashMap(); - public String getTranslation(String text) { - String string = translations.get(text); - if (string == null || string.equals("")) { - return text; - } - return string; - } + Locale l; - public static Language getInstance(String language) { - Language l = langs.get(language); - if (l == null) { - try { - l = new Language(language); - langs.put(language, l); - } catch (ParserConfigurationException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (SAXException e) { - e.printStackTrace(); - } - } - return l; - } + private Language(String language) throws ParserConfigurationException, IOException, SAXException { + if (language.contains("_")) { + String[] parts = language.split("_"); + l = new Locale(parts[0], parts[1]); + } else { + l = new Locale(language); + } - public Locale getLocale() { - return l; - } + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + 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)) { + continue; + } + Element e = (Element) nl.item(i); + Element id = (Element) e.getElementsByTagName("id").item(0); + Element msg = (Element) e.getElementsByTagName("msg").item(0); + translations.put(id.getTextContent(), HTMLEncoder.encodeHTML(msg.getTextContent())); + } + System.out.println(translations.size() + " strings loaded."); + } + + public String getTranslation(String text) { + String string = translations.get(text); + if (string == null || string.equals("")) { + return text; + } + return string; + } + + public static Language getInstance(String language) { + Language l = langs.get(language); + if (l == null) { + try { + l = new Language(language); + langs.put(language, l); + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (SAXException e) { + e.printStackTrace(); + } + } + return l; + } + + public Locale getLocale() { + return l; + } } diff --git a/src/org/cacert/gigi/Launcher.java b/src/org/cacert/gigi/Launcher.java index f34a05e5..c2e11286 100644 --- a/src/org/cacert/gigi/Launcher.java +++ b/src/org/cacert/gigi/Launcher.java @@ -38,175 +38,189 @@ import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.ssl.SslContextFactory; public class Launcher { - public static void main(String[] args) throws Exception { - GigiConfig conf = GigiConfig.parse(System.in); - ServerConstants.init(conf.getMainProps()); - - Server s = new Server(); - // === SSL HTTP Configuration === - HttpConfiguration https_config = new HttpConfiguration(); - https_config.setSendServerVersion(false); - https_config.setSendXPoweredBy(false); - - // for client-cert auth - https_config.addCustomizer(new SecureRequestCustomizer()); - - 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 }); - - HandlerList hl = new HandlerList(); - hl.setHandlers(new Handler[] { generateStaticContext(), generateGigiContexts(conf.getMainProps()), - generateAPIContext() }); - s.setHandler(hl); - s.start(); - 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!"); - } - } - } - - private static SslConnectionFactory createConnectionFactory(GigiConfig conf) throws GeneralSecurityException, - IOException { - final SslContextFactory sslContextFactory = generateSSLContextFactory(conf, "www"); - final SslContextFactory secureContextFactory = generateSSLContextFactory(conf, "secure"); - secureContextFactory.setWantClientAuth(true); - secureContextFactory.setNeedClientAuth(false); - final SslContextFactory staticContextFactory = generateSSLContextFactory(conf, "static"); - final SslContextFactory apiContextFactory = generateSSLContextFactory(conf, "api"); - try { - secureContextFactory.start(); - staticContextFactory.start(); - apiContextFactory.start(); - } catch (Exception e) { - e.printStackTrace(); - } - return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()) { - @Override - public boolean shouldRestartSSL() { - return true; - } - - @Override - public SSLEngine restartSSL(SSLSession sslSession) { - SSLEngine e2 = null; - if (sslSession instanceof ExtendedSSLSession) { - ExtendedSSLSession es = (ExtendedSSLSession) sslSession; - List names = es.getRequestedServerNames(); - for (SNIServerName sniServerName : names) { - if (sniServerName instanceof SNIHostName) { - SNIHostName host = (SNIHostName) sniServerName; - String hostname = host.getAsciiName(); - if (hostname.equals(ServerConstants.getWwwHostName())) { - e2 = sslContextFactory.newSSLEngine(); - } else if (hostname.equals(ServerConstants.getStaticHostName())) { - e2 = staticContextFactory.newSSLEngine(); - } else if (hostname.equals(ServerConstants.getSecureHostName())) { - e2 = secureContextFactory.newSSLEngine(); - } else if (hostname.equals(ServerConstants.getApiHostName())) { - e2 = apiContextFactory.newSSLEngine(); - } - break; - } - } - } - if (e2 == null) { - e2 = sslContextFactory.newSSLEngine(sslSession.getPeerHost(), sslSession.getPeerPort()); - } - e2.setUseClientMode(false); - return e2; - } - }; - } - - private static Handler generateGigiContexts(Properties conf) { - ServletHolder webAppServlet = new ServletHolder(new Gigi(conf)); - - ContextHandler ch = generateGigiServletContext(webAppServlet); - ch.setVirtualHosts(new String[] { ServerConstants.getWwwHostName() }); - ContextHandler chSecure = generateGigiServletContext(webAppServlet); - chSecure.setVirtualHosts(new String[] { ServerConstants.getSecureHostName() }); - - HandlerList hl = new HandlerList(); - hl.setHandlers(new Handler[] { ch, chSecure }); - return hl; - } - - private static ContextHandler generateGigiServletContext(ServletHolder webAppServlet) { - final ResourceHandler rh = new ResourceHandler(); - rh.setResourceBase("static/www"); - - HandlerWrapper hw = new PolicyRedirector(); - hw.setHandler(rh); - - ServletContextHandler servlet = new ServletContextHandler(ServletContextHandler.SESSIONS); - servlet.setInitParameter(SessionManager.__SessionCookieProperty, "CACert-Session"); - servlet.addServlet(webAppServlet, "/*"); - ErrorPageErrorHandler epeh = new ErrorPageErrorHandler(); - epeh.addErrorPage(404, "/error"); - servlet.setErrorHandler(epeh); - - HandlerList hl = new HandlerList(); - hl.setHandlers(new Handler[] { hw, servlet }); - - ContextHandler ch = new ContextHandler(); - ch.setHandler(hl); - return ch; - } - - private static Handler generateStaticContext() { - final ResourceHandler rh = new ResourceHandler(); - rh.setResourceBase("static/static"); - - ContextHandler ch = new ContextHandler(); - ch.setHandler(rh); - ch.setVirtualHosts(new String[] { ServerConstants.getStaticHostName() }); - - return ch; - } - - private static Handler generateAPIContext() { - ServletContextHandler sch = new ServletContextHandler(); - - 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 { - SslContextFactory scf = new SslContextFactory() { - - String[] ciphers = null; - - @Override - public void customize(SSLEngine sslEngine) { - super.customize(sslEngine); - - SSLParameters ssl = sslEngine.getSSLParameters(); - ssl.setUseCipherSuitesOrder(true); - if (ciphers == null) { - ciphers = CipherInfo.filter(sslEngine.getSupportedCipherSuites()); - } - - ssl.setCipherSuites(ciphers); - sslEngine.setSSLParameters(ssl); - - } - - }; - scf.setRenegotiationAllowed(false); - - scf.setProtocol("TLS"); - scf.setTrustStore(conf.getTrustStore()); - KeyStore privateStore = conf.getPrivateStore(); - scf.setKeyStorePassword(conf.getPrivateStorePw()); - scf.setKeyStore(privateStore); - scf.setCertAlias(alias); - return scf; - } + + public static void main(String[] args) throws Exception { + GigiConfig conf = GigiConfig.parse(System.in); + ServerConstants.init(conf.getMainProps()); + + Server s = new Server(); + // === SSL HTTP Configuration === + HttpConfiguration https_config = new HttpConfiguration(); + https_config.setSendServerVersion(false); + https_config.setSendXPoweredBy(false); + + // for client-cert auth + https_config.addCustomizer(new SecureRequestCustomizer()); + + 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 + }); + + HandlerList hl = new HandlerList(); + hl.setHandlers(new Handler[] { + generateStaticContext(), generateGigiContexts(conf.getMainProps()), generateAPIContext() + }); + s.setHandler(hl); + s.start(); + 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!"); + } + } + } + + private static SslConnectionFactory createConnectionFactory(GigiConfig conf) throws GeneralSecurityException, IOException { + final SslContextFactory sslContextFactory = generateSSLContextFactory(conf, "www"); + final SslContextFactory secureContextFactory = generateSSLContextFactory(conf, "secure"); + secureContextFactory.setWantClientAuth(true); + secureContextFactory.setNeedClientAuth(false); + final SslContextFactory staticContextFactory = generateSSLContextFactory(conf, "static"); + final SslContextFactory apiContextFactory = generateSSLContextFactory(conf, "api"); + try { + secureContextFactory.start(); + staticContextFactory.start(); + apiContextFactory.start(); + } catch (Exception e) { + e.printStackTrace(); + } + return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()) { + + @Override + public boolean shouldRestartSSL() { + return true; + } + + @Override + public SSLEngine restartSSL(SSLSession sslSession) { + SSLEngine e2 = null; + if (sslSession instanceof ExtendedSSLSession) { + ExtendedSSLSession es = (ExtendedSSLSession) sslSession; + List names = es.getRequestedServerNames(); + for (SNIServerName sniServerName : names) { + if (sniServerName instanceof SNIHostName) { + SNIHostName host = (SNIHostName) sniServerName; + String hostname = host.getAsciiName(); + if (hostname.equals(ServerConstants.getWwwHostName())) { + e2 = sslContextFactory.newSSLEngine(); + } else if (hostname.equals(ServerConstants.getStaticHostName())) { + e2 = staticContextFactory.newSSLEngine(); + } else if (hostname.equals(ServerConstants.getSecureHostName())) { + e2 = secureContextFactory.newSSLEngine(); + } else if (hostname.equals(ServerConstants.getApiHostName())) { + e2 = apiContextFactory.newSSLEngine(); + } + break; + } + } + } + if (e2 == null) { + e2 = sslContextFactory.newSSLEngine(sslSession.getPeerHost(), sslSession.getPeerPort()); + } + e2.setUseClientMode(false); + return e2; + } + }; + } + + private static Handler generateGigiContexts(Properties conf) { + ServletHolder webAppServlet = new ServletHolder(new Gigi(conf)); + + ContextHandler ch = generateGigiServletContext(webAppServlet); + ch.setVirtualHosts(new String[] { + ServerConstants.getWwwHostName() + }); + ContextHandler chSecure = generateGigiServletContext(webAppServlet); + chSecure.setVirtualHosts(new String[] { + ServerConstants.getSecureHostName() + }); + + HandlerList hl = new HandlerList(); + hl.setHandlers(new Handler[] { + ch, chSecure + }); + return hl; + } + + private static ContextHandler generateGigiServletContext(ServletHolder webAppServlet) { + final ResourceHandler rh = new ResourceHandler(); + rh.setResourceBase("static/www"); + + HandlerWrapper hw = new PolicyRedirector(); + hw.setHandler(rh); + + ServletContextHandler servlet = new ServletContextHandler(ServletContextHandler.SESSIONS); + servlet.setInitParameter(SessionManager.__SessionCookieProperty, "CACert-Session"); + servlet.addServlet(webAppServlet, "/*"); + ErrorPageErrorHandler epeh = new ErrorPageErrorHandler(); + epeh.addErrorPage(404, "/error"); + servlet.setErrorHandler(epeh); + + HandlerList hl = new HandlerList(); + hl.setHandlers(new Handler[] { + hw, servlet + }); + + ContextHandler ch = new ContextHandler(); + ch.setHandler(hl); + return ch; + } + + private static Handler generateStaticContext() { + final ResourceHandler rh = new ResourceHandler(); + rh.setResourceBase("static/static"); + + ContextHandler ch = new ContextHandler(); + ch.setHandler(rh); + ch.setVirtualHosts(new String[] { + ServerConstants.getStaticHostName() + }); + + return ch; + } + + private static Handler generateAPIContext() { + ServletContextHandler sch = new ServletContextHandler(); + + 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 { + SslContextFactory scf = new SslContextFactory() { + + String[] ciphers = null; + + @Override + public void customize(SSLEngine sslEngine) { + super.customize(sslEngine); + + SSLParameters ssl = sslEngine.getSSLParameters(); + ssl.setUseCipherSuitesOrder(true); + if (ciphers == null) { + ciphers = CipherInfo.filter(sslEngine.getSupportedCipherSuites()); + } + + ssl.setCipherSuites(ciphers); + sslEngine.setSSLParameters(ssl); + + } + + }; + scf.setRenegotiationAllowed(false); + + scf.setProtocol("TLS"); + scf.setTrustStore(conf.getTrustStore()); + KeyStore privateStore = conf.getPrivateStore(); + scf.setKeyStorePassword(conf.getPrivateStorePw()); + scf.setKeyStore(privateStore); + scf.setCertAlias(alias); + return scf; + } } diff --git a/src/org/cacert/gigi/Name.java b/src/org/cacert/gigi/Name.java index 865090f0..0c919dab 100644 --- a/src/org/cacert/gigi/Name.java +++ b/src/org/cacert/gigi/Name.java @@ -6,54 +6,58 @@ import java.util.Map; import org.cacert.gigi.output.Outputable; public class Name implements Outputable { - String fname; - String mname; - String lname; - String suffix; - - public Name(String fname, String lname, String mname, String suffix) { - this.fname = fname; - this.lname = lname; - this.mname = mname; - this.suffix = suffix; - } - - @Override - public void output(PrintWriter out, Language l, Map vars) { - out.println(""); - out.print(""); - out.print(fname); - out.print(" "); - out.print(""); - out.print(lname); - out.print(""); - out.println(""); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof Name)) { - return false; - } - Name n = (Name) obj; - if (!(n.fname.equals(fname) && n.lname.equals(lname))) { - return false; - } - if (mname == null) { - if (n.mname != null) { - return false; - } - } else if (!mname.equals(n.mname)) { - return false; - } - if (suffix == null) { - if (n.suffix != null) { - return false; - } - } else if (!suffix.equals(n.suffix)) { - return false; - } - return true; - - } + + String fname; + + String mname; + + String lname; + + String suffix; + + public Name(String fname, String lname, String mname, String suffix) { + this.fname = fname; + this.lname = lname; + this.mname = mname; + this.suffix = suffix; + } + + @Override + public void output(PrintWriter out, Language l, Map vars) { + out.println(""); + out.print(""); + out.print(fname); + out.print(" "); + out.print(""); + out.print(lname); + out.print(""); + out.println(""); + } + + @Override + public boolean equals(Object obj) { + if ( !(obj instanceof Name)) { + return false; + } + Name n = (Name) obj; + if ( !(n.fname.equals(fname) && n.lname.equals(lname))) { + return false; + } + if (mname == null) { + if (n.mname != null) { + return false; + } + } else if ( !mname.equals(n.mname)) { + return false; + } + if (suffix == null) { + if (n.suffix != null) { + return false; + } + } else if ( !suffix.equals(n.suffix)) { + return false; + } + return true; + + } } diff --git a/src/org/cacert/gigi/PolicyRedirector.java b/src/org/cacert/gigi/PolicyRedirector.java index d96ed732..c4a260e5 100644 --- a/src/org/cacert/gigi/PolicyRedirector.java +++ b/src/org/cacert/gigi/PolicyRedirector.java @@ -10,18 +10,18 @@ import org.eclipse.jetty.server.Request; 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 { - if (target.equals("/")) { - return; - } - if (target.startsWith("/policy/") && target.endsWith(".php")) { - target = target.replace(".php", ".html"); - response.sendRedirect(target); - baseRequest.setHandled(true); - return; - } - super.handle(target, baseRequest, request, response); - } + + @Override + public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { + if (target.equals("/")) { + return; + } + if (target.startsWith("/policy/") && target.endsWith(".php")) { + target = target.replace(".php", ".html"); + response.sendRedirect(target); + baseRequest.setHandled(true); + return; + } + super.handle(target, baseRequest, request, response); + } } diff --git a/src/org/cacert/gigi/User.java b/src/org/cacert/gigi/User.java index 010df4a9..949d77a4 100644 --- a/src/org/cacert/gigi/User.java +++ b/src/org/cacert/gigi/User.java @@ -12,331 +12,322 @@ import org.cacert.gigi.util.PasswordStrengthChecker; public class User { - private int id; - Name name = new Name(null, null, null, null); - - Date dob; - String email; - - public User(int id) { - this.id = id; - try { - 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)); - dob = rs.getDate(5); - email = rs.getString(6); - } - rs.close(); - } catch (SQLException e) { - 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"); - query.setString(1, email); - query.setString(2, PasswordHash.hash(password)); - query.setString(3, name.fname); - query.setString(4, name.mname); - query.setString(5, name.lname); - query.setString(6, name.suffix); - query.setDate(7, new java.sql.Date(dob.getTime())); - query.execute(); - id = DatabaseConnection.lastInsertId(query); - } - - public void changePassword(String oldPass, String newPass) throws GigiApiException { - try { - PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `password` FROM users WHERE id=?"); - ps.setInt(1, id); - ResultSet rs = ps.executeQuery(); - if (!rs.next()) { - throw new GigiApiException("User not found... very bad."); - } - if (!PasswordHash.verifyHash(oldPass, rs.getString(1))) { - throw new GigiApiException("Old password does not match."); - } - rs.close(); - PasswordStrengthChecker.assertStrongPassword(newPass, this); - ps = DatabaseConnection.getInstance().prepare("UPDATE users SET `password`=? WHERE id=?"); - ps.setString(1, PasswordHash.hash(newPass)); - ps.setInt(2, id); - if (ps.executeUpdate() != 1) { - throw new GigiApiException("Password update failed."); - } - } catch (SQLException e) { - throw new GigiApiException(e); - } - } - - public boolean canAssure() throws SQLException { - if (getAssurancePoints() < 100) { - return false; - } - - return hasPassedCATS(); - - } - - public boolean hasPassedCATS() throws SQLException { - PreparedStatement query = DatabaseConnection.getInstance().prepare( - "SELECT 1 FROM `cats_passed` where `user_id`=?"); - query.setInt(1, id); - ResultSet rs = query.executeQuery(); - if (rs.next()) { - return true; - } else { - return false; - } - } - - public int getAssurancePoints() throws SQLException { - 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; - if (rs.next()) { - points = rs.getInt(1); - } - rs.close(); - return points; - } - - public int getExperiencePoints() throws SQLException { - PreparedStatement query = DatabaseConnection.getInstance().prepare( - "SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0"); - query.setInt(1, id); - ResultSet rs = query.executeQuery(); - int points = 0; - if (rs.next()) { - points = rs.getInt(1) * 2; - } - 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 - } - - /** - * Gets the maximum allowed points NOW. Note that an assurance needs to - * re-check PoJam as it has taken place in the past. - * - * @return the maximal points - * @throws SQLException - */ - public int getMaxAssurePoints() throws SQLException { - int exp = getExperiencePoints(); - int points = 10; - Calendar c = Calendar.getInstance(); - c.setTime(dob); - int year = c.get(Calendar.YEAR); - int month = c.get(Calendar.MONTH); - int day = c.get(Calendar.DAY_OF_MONTH); - c.set(year + 18, month, day); - if (System.currentTimeMillis() < c.getTime().getTime()) { - return points; // not 18 Years old. - } - - if (exp >= 10) { - points += 5; - } - if (exp >= 20) { - points += 5; - } - if (exp >= 30) { - points += 5; - } - if (exp >= 40) { - points += 5; - } - if (exp >= 50) { - points += 5; - } - return points; - } - - public static User getById(int id) { - return new User(id); - } - - public EmailAddress[] getEmails() { - try { - PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "SELECT id FROM email WHERE memid=? AND deleted=0"); - ps.setInt(1, id); - ResultSet rs = ps.executeQuery(); - rs.last(); - int count = rs.getRow(); - EmailAddress[] data = new EmailAddress[count]; - rs.beforeFirst(); - for (int i = 0; i < data.length; i++) { - if (!rs.next()) { - throw new Error("Internal sql api violation."); - } - data[i] = EmailAddress.getById(rs.getInt(1)); - } - rs.close(); - return data; - } catch (SQLException e) { - e.printStackTrace(); - } - - return null; - } - - public Domain[] getDomains() { - try { - PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "SELECT id FROM domain WHERE memid=? AND deleted IS NULL"); - ps.setInt(1, id); - ResultSet rs = ps.executeQuery(); - rs.last(); - int count = rs.getRow(); - Domain[] data = new Domain[count]; - rs.beforeFirst(); - for (int i = 0; i < data.length; i++) { - if (!rs.next()) { - throw new Error("Internal sql api violation."); - } - data[i] = Domain.getById(rs.getInt(1)); - } - rs.close(); - return data; - } catch (SQLException e) { - e.printStackTrace(); - } - - return null; - } - - public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException { - try { - EmailAddress[] adrs = getEmails(); - for (int i = 0; i < adrs.length; i++) { - if (adrs[i].getAddress().equals(newMail.getAddress())) { - if (!adrs[i].isVerified()) { - throw new GigiApiException("Email not verified."); - } - PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "UPDATE users SET email=? WHERE id=?"); - ps.setString(1, newMail.getAddress()); - ps.setInt(2, getId()); - ps.execute(); - email = newMail.getAddress(); - return; - } - } - throw new GigiApiException("Given address not an address of the user."); - } catch (SQLException e) { - throw new GigiApiException(e); - } - } - - public void deleteEmail(EmailAddress mail) throws GigiApiException { - if (getEmail().equals(mail.getAddress())) { - throw new GigiApiException("Can't delete user's default e-mail."); - } - EmailAddress[] emails = getEmails(); - for (int i = 0; i < emails.length; i++) { - if (emails[i].getId() == mail.getId()) { - try { - PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "UPDATE email SET deleted=? WHERE id=?"); - ps.setDate(1, new Date(System.currentTimeMillis())); - ps.setInt(2, mail.getId()); - ps.execute(); - } catch (SQLException e) { - e.printStackTrace(); - throw new GigiApiException(e); - } - return; - } - } - throw new GigiApiException("Email not one user's mail addresses."); - } + private int id; + + Name name = new Name(null, null, null, null); + + Date dob; + + String email; + + public User(int id) { + this.id = id; + try { + 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)); + dob = rs.getDate(5); + email = rs.getString(6); + } + rs.close(); + } catch (SQLException e) { + 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"); + query.setString(1, email); + query.setString(2, PasswordHash.hash(password)); + query.setString(3, name.fname); + query.setString(4, name.mname); + query.setString(5, name.lname); + query.setString(6, name.suffix); + query.setDate(7, new java.sql.Date(dob.getTime())); + query.execute(); + id = DatabaseConnection.lastInsertId(query); + } + + public void changePassword(String oldPass, String newPass) throws GigiApiException { + try { + PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT `password` FROM users WHERE id=?"); + ps.setInt(1, id); + ResultSet rs = ps.executeQuery(); + if ( !rs.next()) { + throw new GigiApiException("User not found... very bad."); + } + if ( !PasswordHash.verifyHash(oldPass, rs.getString(1))) { + throw new GigiApiException("Old password does not match."); + } + rs.close(); + PasswordStrengthChecker.assertStrongPassword(newPass, this); + ps = DatabaseConnection.getInstance().prepare("UPDATE users SET `password`=? WHERE id=?"); + ps.setString(1, PasswordHash.hash(newPass)); + ps.setInt(2, id); + if (ps.executeUpdate() != 1) { + throw new GigiApiException("Password update failed."); + } + } catch (SQLException e) { + throw new GigiApiException(e); + } + } + + public boolean canAssure() throws SQLException { + if (getAssurancePoints() < 100) { + return false; + } + + return hasPassedCATS(); + + } + + public boolean hasPassedCATS() throws SQLException { + PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `cats_passed` where `user_id`=?"); + query.setInt(1, id); + ResultSet rs = query.executeQuery(); + if (rs.next()) { + return true; + } else { + return false; + } + } + + public int getAssurancePoints() throws SQLException { + 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; + if (rs.next()) { + points = rs.getInt(1); + } + rs.close(); + return points; + } + + public int getExperiencePoints() throws SQLException { + PreparedStatement query = DatabaseConnection.getInstance().prepare("SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0"); + query.setInt(1, id); + ResultSet rs = query.executeQuery(); + int points = 0; + if (rs.next()) { + points = rs.getInt(1) * 2; + } + 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 + } + + /** + * Gets the maximum allowed points NOW. Note that an assurance needs to + * re-check PoJam as it has taken place in the past. + * + * @return the maximal points + * @throws SQLException + */ + public int getMaxAssurePoints() throws SQLException { + int exp = getExperiencePoints(); + int points = 10; + Calendar c = Calendar.getInstance(); + c.setTime(dob); + int year = c.get(Calendar.YEAR); + int month = c.get(Calendar.MONTH); + int day = c.get(Calendar.DAY_OF_MONTH); + c.set(year + 18, month, day); + if (System.currentTimeMillis() < c.getTime().getTime()) { + return points; // not 18 Years old. + } + + if (exp >= 10) { + points += 5; + } + if (exp >= 20) { + points += 5; + } + if (exp >= 30) { + points += 5; + } + if (exp >= 40) { + points += 5; + } + if (exp >= 50) { + points += 5; + } + return points; + } + + public static User getById(int id) { + return new User(id); + } + + public EmailAddress[] getEmails() { + try { + PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM email WHERE memid=? AND deleted=0"); + ps.setInt(1, id); + ResultSet rs = ps.executeQuery(); + rs.last(); + int count = rs.getRow(); + EmailAddress[] data = new EmailAddress[count]; + rs.beforeFirst(); + for (int i = 0; i < data.length; i++) { + if ( !rs.next()) { + throw new Error("Internal sql api violation."); + } + data[i] = EmailAddress.getById(rs.getInt(1)); + } + rs.close(); + return data; + } catch (SQLException e) { + e.printStackTrace(); + } + + return null; + } + + public Domain[] getDomains() { + try { + PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM domain WHERE memid=? AND deleted IS NULL"); + ps.setInt(1, id); + ResultSet rs = ps.executeQuery(); + rs.last(); + int count = rs.getRow(); + Domain[] data = new Domain[count]; + rs.beforeFirst(); + for (int i = 0; i < data.length; i++) { + if ( !rs.next()) { + throw new Error("Internal sql api violation."); + } + data[i] = Domain.getById(rs.getInt(1)); + } + rs.close(); + return data; + } catch (SQLException e) { + e.printStackTrace(); + } + + return null; + } + + public void updateDefaultEmail(EmailAddress newMail) throws GigiApiException { + try { + EmailAddress[] adrs = getEmails(); + for (int i = 0; i < adrs.length; i++) { + if (adrs[i].getAddress().equals(newMail.getAddress())) { + if ( !adrs[i].isVerified()) { + throw new GigiApiException("Email not verified."); + } + PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET email=? WHERE id=?"); + ps.setString(1, newMail.getAddress()); + ps.setInt(2, getId()); + ps.execute(); + email = newMail.getAddress(); + return; + } + } + throw new GigiApiException("Given address not an address of the user."); + } catch (SQLException e) { + throw new GigiApiException(e); + } + } + + public void deleteEmail(EmailAddress mail) throws GigiApiException { + if (getEmail().equals(mail.getAddress())) { + throw new GigiApiException("Can't delete user's default e-mail."); + } + EmailAddress[] emails = getEmails(); + for (int i = 0; i < emails.length; i++) { + if (emails[i].getId() == mail.getId()) { + try { + PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE email SET deleted=? WHERE id=?"); + ps.setDate(1, new Date(System.currentTimeMillis())); + ps.setInt(2, mail.getId()); + ps.execute(); + } catch (SQLException e) { + e.printStackTrace(); + throw new GigiApiException(e); + } + return; + } + } + throw new GigiApiException("Email not one user's mail addresses."); + } } diff --git a/src/org/cacert/gigi/api/GigiAPI.java b/src/org/cacert/gigi/api/GigiAPI.java index 4104feb3..209ffe56 100644 --- a/src/org/cacert/gigi/api/GigiAPI.java +++ b/src/org/cacert/gigi/api/GigiAPI.java @@ -10,22 +10,23 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class GigiAPI extends HttpServlet { - @Override - protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String pi = req.getPathInfo(); - if (pi == null) { - return; - } - if (pi.equals("/security/csp/report")) { - ServletInputStream sis = req.getInputStream(); - InputStreamReader isr = new InputStreamReader(sis, "UTF-8"); - StringBuffer strB = new StringBuffer(); - char[] buffer = new char[4 * 1024]; - int len; - while ((len = isr.read(buffer)) > 0) { - strB.append(buffer, 0, len); - } - System.out.println(strB); - } - } + + @Override + protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + String pi = req.getPathInfo(); + if (pi == null) { + return; + } + if (pi.equals("/security/csp/report")) { + ServletInputStream sis = req.getInputStream(); + InputStreamReader isr = new InputStreamReader(sis, "UTF-8"); + StringBuffer strB = new StringBuffer(); + char[] buffer = new char[4 * 1024]; + int len; + while ((len = isr.read(buffer)) > 0) { + strB.append(buffer, 0, len); + } + System.out.println(strB); + } + } } diff --git a/src/org/cacert/gigi/database/DatabaseConnection.java b/src/org/cacert/gigi/database/DatabaseConnection.java index b52b63de..389a82cf 100644 --- a/src/org/cacert/gigi/database/DatabaseConnection.java +++ b/src/org/cacert/gigi/database/DatabaseConnection.java @@ -10,110 +10,115 @@ import java.util.Properties; import java.sql.Statement; public class DatabaseConnection { - public static final int CONNECTION_TIMEOUT = 24 * 60 * 60; - Connection c; - HashMap statements = new HashMap(); - private static Properties credentials; - Statement adHoc; - - public DatabaseConnection() { - try { - Class.forName(credentials.getProperty("sql.driver")); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - 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=?;"); - ps.setInt(1, CONNECTION_TIMEOUT); - ps.execute(); - ps.close(); - adHoc = c.createStatement(); - } catch (SQLException e) { - 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); - statements.put(query, statement); - } - return statement; - } - - long lastAction = System.currentTimeMillis(); - - private void ensureOpen() { - if (System.currentTimeMillis() - lastAction > CONNECTION_TIMEOUT * 1000L) { - try { - ResultSet rs = adHoc.executeQuery("SELECT 1"); - rs.close(); - lastAction = System.currentTimeMillis(); - return; - } catch (SQLException e) { - } - statements.clear(); - tryConnect(); - } - lastAction = System.currentTimeMillis(); - } - - public static int lastInsertId(PreparedStatement query) throws SQLException { - ResultSet rs = query.getGeneratedKeys(); - rs.next(); - int id = rs.getInt(1); - 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()) { - c.rollback(); - c.setAutoCommit(true); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } + + public static final int CONNECTION_TIMEOUT = 24 * 60 * 60; + + Connection c; + + HashMap statements = new HashMap(); + + private static Properties credentials; + + Statement adHoc; + + public DatabaseConnection() { + try { + Class.forName(credentials.getProperty("sql.driver")); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + 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=?;"); + ps.setInt(1, CONNECTION_TIMEOUT); + ps.execute(); + ps.close(); + adHoc = c.createStatement(); + } catch (SQLException e) { + 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); + statements.put(query, statement); + } + return statement; + } + + long lastAction = System.currentTimeMillis(); + + private void ensureOpen() { + if (System.currentTimeMillis() - lastAction > CONNECTION_TIMEOUT * 1000L) { + try { + ResultSet rs = adHoc.executeQuery("SELECT 1"); + rs.close(); + lastAction = System.currentTimeMillis(); + return; + } catch (SQLException e) { + } + statements.clear(); + tryConnect(); + } + lastAction = System.currentTimeMillis(); + } + + public static int lastInsertId(PreparedStatement query) throws SQLException { + ResultSet rs = query.getGeneratedKeys(); + rs.next(); + int id = rs.getInt(1); + 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()) { + c.rollback(); + c.setAutoCommit(true); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } } diff --git a/src/org/cacert/gigi/email/CommandlineEmailProvider.java b/src/org/cacert/gigi/email/CommandlineEmailProvider.java index a9149fab..108dd646 100644 --- a/src/org/cacert/gigi/email/CommandlineEmailProvider.java +++ b/src/org/cacert/gigi/email/CommandlineEmailProvider.java @@ -4,28 +4,27 @@ import java.io.IOException; import java.util.Properties; public class CommandlineEmailProvider extends EmailProvider { - public CommandlineEmailProvider(Properties p) { - } - @Override - 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); - System.out.println("Subject: " + subject); - System.out.println("From: " + from); - System.out.println("Errors-To: " + errorsto); - System.out.println("Extra: " + extra); - System.out.println(message); - } + public CommandlineEmailProvider(Properties p) {} - } + @Override + 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); + System.out.println("Subject: " + subject); + System.out.println("From: " + from); + System.out.println("Errors-To: " + errorsto); + System.out.println("Extra: " + extra); + System.out.println(message); + } - @Override - public String checkEmailServer(int forUid, String address) throws IOException { - System.out.println("checkMailBox: " + address); - return OK; - } + } + + @Override + 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 6855f398..3ccac586 100644 --- a/src/org/cacert/gigi/email/EmailProvider.java +++ b/src/org/cacert/gigi/email/EmailProvider.java @@ -14,121 +14,120 @@ 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; - - private static EmailProvider instance; - - public static EmailProvider getInstance() { - return instance; - } - - protected static void setInstance(EmailProvider instance) { - EmailProvider.instance = instance; - } - - public static void init(Properties conf) { - try { - Class c = Class.forName(conf.getProperty("emailProvider")); - instance = (EmailProvider) c.getDeclaredConstructor(Properties.class).newInstance(conf); - } catch (ReflectiveOperationException e) { - e.printStackTrace(); - } - } - - public static final String OK = "OK"; - public static final String FAIL = "FAIL"; - public static final Pattern MAIL = Pattern - .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 { - if (MAIL.matcher(address).matches()) { - String[] parts = address.split("@", 2); - String domain = parts[1]; - - LinkedList mxhosts = getMxHosts(domain); - - 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())) { - String line; - while ((line = br.readLine()) != null && line.startsWith("220-")) { - } - if (line == null || !line.startsWith("220")) { - continue; - } - - pw.print("HELO www.cacert.org\r\n"); - pw.flush(); - - while ((line = br.readLine()) != null && line.startsWith("220")) { - } - - if (line == null || !line.startsWith("250")) { - continue; - } - pw.print("MAIL FROM: \r\n"); - pw.flush(); - - line = br.readLine(); - - if (line == null || !line.startsWith("250")) { - continue; - } - pw.print("RCPT TO: <" + address + ">\r\n"); - pw.flush(); - - line = br.readLine(); - pw.print("QUIT\r\n"); - pw.flush(); - - try { - 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); - statmt.execute(); - } catch (SQLException e) { - e.printStackTrace(); - } - - if (line == null || !line.startsWith("250")) { - return line; - } else { - return OK; - } - } - - } - } - try { - 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.setInt(3, forUid); - statmt.execute(); - } catch (SQLException e) { - e.printStackTrace(); - } - return FAIL; - } - - 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()))) { - String line; - while ((line = br.readLine()) != null) { - String[] mxparts = line.split(" ", 2); - if (mxparts.length != 2) { - continue; - } - mxhosts.add(mxparts[1].substring(0, mxparts[1].length() - 1)); - } - } - return mxhosts; - } + + 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; + } + + protected static void setInstance(EmailProvider instance) { + EmailProvider.instance = instance; + } + + public static void init(Properties conf) { + try { + Class c = Class.forName(conf.getProperty("emailProvider")); + instance = (EmailProvider) c.getDeclaredConstructor(Properties.class).newInstance(conf); + } catch (ReflectiveOperationException e) { + e.printStackTrace(); + } + } + + public static final String OK = "OK"; + + public static final String FAIL = "FAIL"; + + public static final Pattern MAIL = Pattern.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 { + if (MAIL.matcher(address).matches()) { + String[] parts = address.split("@", 2); + String domain = parts[1]; + + LinkedList mxhosts = getMxHosts(domain); + + 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())) { + String line; + while ((line = br.readLine()) != null && line.startsWith("220-")) { + } + if (line == null || !line.startsWith("220")) { + continue; + } + + pw.print("HELO www.cacert.org\r\n"); + pw.flush(); + + while ((line = br.readLine()) != null && line.startsWith("220")) { + } + + if (line == null || !line.startsWith("250")) { + continue; + } + pw.print("MAIL FROM: \r\n"); + pw.flush(); + + line = br.readLine(); + + if (line == null || !line.startsWith("250")) { + continue; + } + pw.print("RCPT TO: <" + address + ">\r\n"); + pw.flush(); + + line = br.readLine(); + pw.print("QUIT\r\n"); + pw.flush(); + + try { + 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); + statmt.execute(); + } catch (SQLException e) { + e.printStackTrace(); + } + + if (line == null || !line.startsWith("250")) { + return line; + } else { + return OK; + } + } + + } + } + try { + 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.setInt(3, forUid); + statmt.execute(); + } catch (SQLException e) { + e.printStackTrace(); + } + return FAIL; + } + + 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()))) { + String line; + while ((line = br.readLine()) != null) { + String[] mxparts = line.split(" ", 2); + if (mxparts.length != 2) { + continue; + } + mxhosts.add(mxparts[1].substring(0, mxparts[1].length() - 1)); + } + } + return mxhosts; + } } diff --git a/src/org/cacert/gigi/email/Sendmail.java b/src/org/cacert/gigi/email/Sendmail.java index f47d2bc3..67c0fb5b 100644 --- a/src/org/cacert/gigi/email/Sendmail.java +++ b/src/org/cacert/gigi/email/Sendmail.java @@ -13,89 +13,87 @@ import java.util.Properties; 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 .-\\[\\]!_@]"); + protected Sendmail(Properties props) {} - @Override - public void sendmail(String to, String subject, String message, String from, String replyto, String toname, - String fromname, String errorsto, boolean extra) throws IOException { + private static final Pattern NON_ASCII = Pattern.compile("[^a-zA-Z0-9 .-\\[\\]!_@]"); - String[] bits = from.split(","); + @Override + public void sendmail(String to, String subject, String message, String from, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException { - Socket smtp = new Socket("dogcraft.de", 25); - PrintWriter out = new PrintWriter(smtp.getOutputStream()); - BufferedReader in = new BufferedReader(new InputStreamReader(smtp.getInputStream())); - readResponse(in); - out.print("HELO www.cacert.org\r\n"); - out.flush(); - readResponse(in); - out.print("MAIL FROM:\r\n"); - out.flush(); - readResponse(in); - bits = to.split(","); - for (String user : bits) { - out.print("RCPT TO:<" + user.trim() + ">\r\n"); - out.flush(); - readResponse(in); - } - out.print("DATA\r\n"); - out.flush(); - readResponse(in); - out.print("X-Mailer: CAcert.org Website\r\n"); - // if (array_key_exists("REMOTE_ADDR", $_SERVER)) { - // 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"); - out.print("Sender: " + errorsto + "\r\n"); - out.print("Errors-To: " + errorsto + "\r\n"); - if (replyto != null) { - out.print("Reply-To: " + replyto + "\r\n"); - } else { - out.print("Reply-To: " + from + "\r\n"); - } - out.print("From: " + from + "\r\n"); - out.print("To: " + to + "\r\n"); - if (NON_ASCII.matcher(subject).matches()) { + String[] bits = from.split(","); - out.print("Subject: =?utf-8?B?" + Base64.getEncoder().encodeToString(subject.getBytes()) + "?=\r\n"); - } else { - out.print("Subject: " + subject + "\r\n"); - } - out.print("Mime-Version: 1.0\r\n"); - if (!extra) { - out.print("Content-Type: text/plain; charset=\"utf-8\"\r\n"); - out.print("Content-Transfer-Encoding: 8bit\r\n"); - } else { - out.print("Content-Type: text/plain; charset=\"iso-8859-1\"\r\n"); - out.print("Content-Transfer-Encoding: quoted-printable\r\n"); - out.print("Content-Disposition: inline\r\n"); - } - // out.print("Content-Transfer-Encoding: BASE64\r\n"); - out.print("\r\n"); - // out.print(chunk_split(base64_encode(recode("html..utf-8", - // $message)))."\r\n.\r\n"); - message = message + "\r\n"; + Socket smtp = new Socket("dogcraft.de", 25); + PrintWriter out = new PrintWriter(smtp.getOutputStream()); + BufferedReader in = new BufferedReader(new InputStreamReader(smtp.getInputStream())); + readResponse(in); + out.print("HELO www.cacert.org\r\n"); + out.flush(); + readResponse(in); + out.print("MAIL FROM:\r\n"); + out.flush(); + readResponse(in); + bits = to.split(","); + for (String user : bits) { + out.print("RCPT TO:<" + user.trim() + ">\r\n"); + out.flush(); + readResponse(in); + } + out.print("DATA\r\n"); + out.flush(); + readResponse(in); + out.print("X-Mailer: CAcert.org Website\r\n"); + // if (array_key_exists("REMOTE_ADDR", $_SERVER)) { + // 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"); + out.print("Sender: " + errorsto + "\r\n"); + out.print("Errors-To: " + errorsto + "\r\n"); + if (replyto != null) { + out.print("Reply-To: " + replyto + "\r\n"); + } else { + out.print("Reply-To: " + from + "\r\n"); + } + out.print("From: " + from + "\r\n"); + out.print("To: " + to + "\r\n"); + if (NON_ASCII.matcher(subject).matches()) { - 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); - out.print("QUIT\n"); - out.flush(); - readResponse(in); - smtp.close(); - } + out.print("Subject: =?utf-8?B?" + Base64.getEncoder().encodeToString(subject.getBytes()) + "?=\r\n"); + } else { + out.print("Subject: " + subject + "\r\n"); + } + out.print("Mime-Version: 1.0\r\n"); + if ( !extra) { + out.print("Content-Type: text/plain; charset=\"utf-8\"\r\n"); + out.print("Content-Transfer-Encoding: 8bit\r\n"); + } else { + out.print("Content-Type: text/plain; charset=\"iso-8859-1\"\r\n"); + out.print("Content-Transfer-Encoding: quoted-printable\r\n"); + out.print("Content-Disposition: inline\r\n"); + } + // out.print("Content-Transfer-Encoding: BASE64\r\n"); + out.print("\r\n"); + // out.print(chunk_split(base64_encode(recode("html..utf-8", + // $message)))."\r\n.\r\n"); + message = message + "\r\n"; - private static void readResponse(BufferedReader in) throws IOException { - String line; - while ((line = in.readLine()) != null && line.matches("\\d+-")) { - } + 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); + out.print("QUIT\n"); + out.flush(); + 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 35c4b3fe..caf29661 100644 --- a/src/org/cacert/gigi/email/TestEmailProvider.java +++ b/src/org/cacert/gigi/email/TestEmailProvider.java @@ -9,75 +9,77 @@ import java.net.Socket; import java.util.Properties; class TestEmailProvider extends EmailProvider { - ServerSocket servs; - 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")); - } catch (IOException e) { - e.printStackTrace(); - } - } + ServerSocket servs; - @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 { - while (true) { - assureLocalConnection(); - try { - out.writeUTF("mail"); - write(to); - write(subject); - write(message); - write(from); - write(replyto); - out.flush(); - return; - } catch (IOException e) { - client = null; - } - } - } + Socket client; - private void assureLocalConnection() throws IOException { - if (out != null) { - try { - out.writeUTF("ping"); - } catch (IOException e) { - client = null; - } - } - if (client == null || client.isClosed()) { - client = servs.accept(); - out = new DataOutputStream(client.getOutputStream()); - in = new DataInputStream(client.getInputStream()); - } - } + DataOutputStream out; - @Override - public synchronized String checkEmailServer(int forUid, String address) throws IOException { - while (true) { - assureLocalConnection(); - try { - out.writeUTF("challengeAddrBox"); - out.writeUTF(address); - return in.readUTF(); - } catch (IOException e) { - client = null; - } - } - } + DataInputStream in; - private void write(String to) throws IOException { - if (to == null) { - out.writeUTF(""); - } else { - out.writeUTF(to); - } - } + protected TestEmailProvider(Properties props) { + try { + 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 { + while (true) { + assureLocalConnection(); + try { + out.writeUTF("mail"); + write(to); + write(subject); + write(message); + write(from); + write(replyto); + out.flush(); + return; + } catch (IOException e) { + client = null; + } + } + } + + private void assureLocalConnection() throws IOException { + if (out != null) { + try { + out.writeUTF("ping"); + } catch (IOException e) { + client = null; + } + } + if (client == null || client.isClosed()) { + client = servs.accept(); + out = new DataOutputStream(client.getOutputStream()); + in = new DataInputStream(client.getInputStream()); + } + } + + @Override + public synchronized String checkEmailServer(int forUid, String address) throws IOException { + while (true) { + assureLocalConnection(); + try { + out.writeUTF("challengeAddrBox"); + out.writeUTF(address); + return in.readUTF(); + } catch (IOException e) { + client = null; + } + } + } + + private void write(String to) throws IOException { + if (to == null) { + out.writeUTF(""); + } else { + out.writeUTF(to); + } + } } diff --git a/src/org/cacert/gigi/natives/SetUID.java b/src/org/cacert/gigi/natives/SetUID.java index e6b0f7cb..a4a5d859 100644 --- a/src/org/cacert/gigi/natives/SetUID.java +++ b/src/org/cacert/gigi/natives/SetUID.java @@ -6,31 +6,32 @@ import java.io.File; * Native to use privileged ports on unix-like hosts. * * @author janis - * */ public class SetUID { - static { - System.load(new File("natives/libsetuid.so").getAbsolutePath()); - } - public native Status setUid(int uid, int gid); + static { + System.load(new File("natives/libsetuid.so").getAbsolutePath()); + } + + public native Status setUid(int uid, int gid); + + public static class Status { - public static class Status { + private boolean success; - private boolean success; - private String message; + private String message; - public Status(boolean success, String message) { - this.success = success; - this.message = message; - } + public Status(boolean success, String message) { + this.success = success; + this.message = message; + } - public boolean getSuccess() { - return success; - } + public boolean getSuccess() { + return success; + } - public String getMessage() { - return message; - } - } + public String getMessage() { + return message; + } + } } diff --git a/src/org/cacert/gigi/output/CertificateTable.java b/src/org/cacert/gigi/output/CertificateTable.java index 826fa1b5..1b478f09 100644 --- a/src/org/cacert/gigi/output/CertificateTable.java +++ b/src/org/cacert/gigi/output/CertificateTable.java @@ -9,56 +9,58 @@ import org.cacert.gigi.Language; import org.cacert.gigi.pages.account.MailCertificates; public class CertificateTable implements Outputable { - String resultSet; - public CertificateTable(String resultSet) { - this.resultSet = resultSet; - } + String resultSet; - private static final String[] columnNames = new String[] { "Renew/Revoke/Delete", "Status", "Email Address", - "SerialNumber", "Revoked", "Expires", "Login" }; + public CertificateTable(String resultSet) { + this.resultSet = resultSet; + } - @Override - public void output(PrintWriter out, Language l, Map vars) { - ResultSet rs = (ResultSet) vars.get(resultSet); - try { - out.println("
"); - out.println(""); - out.println(""); - for (String column : columnNames) { - out.print(""); - } - out.print(""); + private static final String[] columnNames = new String[] { + "Renew/Revoke/Delete", "Status", "Email Address", "SerialNumber", "Revoked", "Expires", "Login" + }; - rs.beforeFirst(); - while (rs.next()) { - // out.println(rs.getString("id")); - out.print(""); - } - out.println("
"); - out.print(l.getTranslation(column)); - out.println(""); - out.print(l.getTranslation("Comment *")); - out.println("
 State"); - out.println(rs.getString("CN")); - out.print(""); - out.println(rs.getString("serial")); - out.print(""); - if (rs.getString("revoked") == null) { - out.println("N/A"); - } else { - out.println(rs.getString("revoked")); - } - out.print(""); - out.println(rs.getString("expire")); - out.println("aa
"); - } catch (SQLException e) { - e.printStackTrace(); - } + @Override + public void output(PrintWriter out, Language l, Map vars) { + ResultSet rs = (ResultSet) vars.get(resultSet); + try { + out.println(""); + out.println(""); + out.println(""); + for (String column : columnNames) { + out.print(""); + } + out.print(""); - } + rs.beforeFirst(); + while (rs.next()) { + // out.println(rs.getString("id")); + out.print(""); + } + out.println("
"); + out.print(l.getTranslation(column)); + out.println(""); + out.print(l.getTranslation("Comment *")); + out.println("
 State"); + out.println(rs.getString("CN")); + out.print(""); + out.println(rs.getString("serial")); + out.print(""); + if (rs.getString("revoked") == null) { + out.println("N/A"); + } else { + out.println(rs.getString("revoked")); + } + out.print(""); + out.println(rs.getString("expire")); + out.println("aa
"); + } catch (SQLException e) { + e.printStackTrace(); + } + + } } diff --git a/src/org/cacert/gigi/output/ClientCSRGenerate.java b/src/org/cacert/gigi/output/ClientCSRGenerate.java index 5b474a1e..4885440c 100644 --- a/src/org/cacert/gigi/output/ClientCSRGenerate.java +++ b/src/org/cacert/gigi/output/ClientCSRGenerate.java @@ -11,23 +11,25 @@ import org.cacert.gigi.pages.Page; import org.cacert.gigi.util.ServerConstants; public class ClientCSRGenerate { - static Template normal; - static Template IE; - static { - normal = new Template(ClientCSRGenerate.class.getResource("ClientCSRGenerate.templ")); - IE = new Template(ClientCSRGenerate.class.getResource("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()); - try { - normal.output(resp.getWriter(), Page.getLanguage(req), vars); - } catch (IOException e) { - e.printStackTrace(); - } - } + static Template normal; + + static Template IE; + static { + normal = new Template(ClientCSRGenerate.class.getResource("ClientCSRGenerate.templ")); + IE = new Template(ClientCSRGenerate.class.getResource("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()); + try { + normal.output(resp.getWriter(), Page.getLanguage(req), vars); + } catch (IOException e) { + e.printStackTrace(); + } + } } diff --git a/src/org/cacert/gigi/output/DateSelector.java b/src/org/cacert/gigi/output/DateSelector.java index 4c162cfc..45697fe0 100644 --- a/src/org/cacert/gigi/output/DateSelector.java +++ b/src/org/cacert/gigi/output/DateSelector.java @@ -12,95 +12,99 @@ import javax.servlet.http.HttpServletRequest; 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 }; - } - - int day; - int month; - int year; - - @Override - public void output(PrintWriter out, Language l, Map vars) { - out.print(""); - SimpleDateFormat sdf = new SimpleDateFormat("MMMM", l.getLocale()); - out.print(""); - out.print(""); - } - - public void update(HttpServletRequest r) { - String dayS = r.getParameter(names[0]); - if (dayS != null) { - day = parseIntSafe(dayS); - } - - String monthS = r.getParameter(names[1]); - if (monthS != null) { - month = parseIntSafe(monthS); - } - - String yearS = r.getParameter(names[2]); - if (yearS != null) { - year = parseIntSafe(yearS); - } - } - - private int parseIntSafe(String dayS) { - try { - return Integer.parseInt(dayS); - } catch (NumberFormatException e) { - - } - return 0; - } - - public boolean isValid() { - if (!(1900 < year && 1 <= month && month <= 12 && 1 <= day && day <= 32)) { - return false; - } - return true; // TODO checkdate - } - - @Override - public String toString() { - return "DateSelector [names=" + Arrays.toString(names) + ", day=" + day + ", month=" + month + ", year=" + year - + "]"; - } - - public java.sql.Date getDate() { - Calendar gc = GregorianCalendar.getInstance(); - gc.set(year, month - 1, day); - return new java.sql.Date(gc.getTime().getTime()); - } + + String[] names; + + public DateSelector(String day, String month, String 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(""); + SimpleDateFormat sdf = new SimpleDateFormat("MMMM", l.getLocale()); + out.print(""); + out.print(""); + } + + public void update(HttpServletRequest r) { + String dayS = r.getParameter(names[0]); + if (dayS != null) { + day = parseIntSafe(dayS); + } + + String monthS = r.getParameter(names[1]); + if (monthS != null) { + month = parseIntSafe(monthS); + } + + String yearS = r.getParameter(names[2]); + if (yearS != null) { + year = parseIntSafe(yearS); + } + } + + private int parseIntSafe(String dayS) { + try { + return Integer.parseInt(dayS); + } catch (NumberFormatException e) { + + } + return 0; + } + + public boolean isValid() { + if ( !(1900 < year && 1 <= month && month <= 12 && 1 <= day && day <= 32)) { + return false; + } + return true; // TODO checkdate + } + + @Override + public String toString() { + return "DateSelector [names=" + Arrays.toString(names) + ", day=" + day + ", month=" + month + ", year=" + year + "]"; + } + + public java.sql.Date getDate() { + Calendar gc = GregorianCalendar.getInstance(); + gc.set(year, month - 1, day); + return new java.sql.Date(gc.getTime().getTime()); + } } diff --git a/src/org/cacert/gigi/output/Form.java b/src/org/cacert/gigi/output/Form.java index dd244d74..063eb124 100644 --- a/src/org/cacert/gigi/output/Form.java +++ b/src/org/cacert/gigi/output/Form.java @@ -13,56 +13,58 @@ import org.cacert.gigi.pages.Page; import org.cacert.gigi.util.RandomToken; public abstract class Form implements Outputable { - public static final String CSRF_FIELD = "csrf"; - String csrf; - - public Form(HttpServletRequest hsr) { - csrf = RandomToken.generateToken(32); - HttpSession hs = hsr.getSession(); - hs.setAttribute("form/" + getClass().getName() + "/" + csrf, this); - - } - - public abstract boolean submit(PrintWriter out, HttpServletRequest req); - - @Override - public final void output(PrintWriter out, Language l, Map vars) { - out.println(""); - outputContent(out, l, vars); - out.print(""); - } - - protected abstract void outputContent(PrintWriter out, Language l, Map vars); - - protected void outputError(PrintWriter out, ServletRequest req, String text) { - out.print("
"); - out.print(Page.translate(req, text)); - out.println("
"); - } - - protected String getCSRFToken() { - return csrf; - } - - public static T getForm(HttpServletRequest req, Class target) throws CSRFException { - String csrf = req.getParameter(CSRF_FIELD); - if (csrf == null) { - throw new CSRFException(); - } - HttpSession hs = req.getSession(); - if (hs == null) { - throw new CSRFException(); - } - Form f = (Form) hs.getAttribute("form/" + target.getName() + "/" + csrf); - if (f == null) { - throw new CSRFException(); - } - return (T) f; - } - - public static class CSRFException extends IOException { - - } + + public static final String CSRF_FIELD = "csrf"; + + String csrf; + + public Form(HttpServletRequest hsr) { + csrf = RandomToken.generateToken(32); + HttpSession hs = hsr.getSession(); + hs.setAttribute("form/" + getClass().getName() + "/" + csrf, this); + + } + + public abstract boolean submit(PrintWriter out, HttpServletRequest req); + + @Override + public final void output(PrintWriter out, Language l, Map vars) { + out.println("
"); + outputContent(out, l, vars); + out.print("
"); + } + + protected abstract void outputContent(PrintWriter out, Language l, Map vars); + + protected void outputError(PrintWriter out, ServletRequest req, String text) { + out.print("
"); + out.print(Page.translate(req, text)); + out.println("
"); + } + + protected String getCSRFToken() { + return csrf; + } + + public static T getForm(HttpServletRequest req, Class target) throws CSRFException { + String csrf = req.getParameter(CSRF_FIELD); + if (csrf == null) { + throw new CSRFException(); + } + HttpSession hs = req.getSession(); + if (hs == null) { + throw new CSRFException(); + } + Form f = (Form) hs.getAttribute("form/" + target.getName() + "/" + csrf); + if (f == null) { + throw new CSRFException(); + } + return (T) f; + } + + public static class CSRFException extends IOException { + + } } diff --git a/src/org/cacert/gigi/output/Menu.java b/src/org/cacert/gigi/output/Menu.java index 09f4a21c..6e75eb90 100644 --- a/src/org/cacert/gigi/output/Menu.java +++ b/src/org/cacert/gigi/output/Menu.java @@ -6,29 +6,32 @@ import java.util.Map; import org.cacert.gigi.Language; public class Menu implements Outputable { - String menuName; - String id; - private MenuItem[] content; - - public Menu(String menuName, String id, MenuItem... content) { - this.menuName = menuName; - this.id = id; - this.content = content; - } - - @Override - public void output(PrintWriter out, Language l, Map vars) { - out.println("
"); - out.print("

+ "); - out.print(l.getTranslation(menuName)); - out.print("

"); - out.print("
    "); - for (MenuItem mi : content) { - mi.output(out, l, vars); - } - - out.println("
"); - } + + String menuName; + + String id; + + private MenuItem[] content; + + public Menu(String menuName, String id, MenuItem... content) { + this.menuName = menuName; + this.id = id; + this.content = content; + } + + @Override + public void output(PrintWriter out, Language l, Map vars) { + out.println("
"); + out.print("

+ "); + out.print(l.getTranslation(menuName)); + out.print("

"); + out.print("
    "); + for (MenuItem mi : content) { + mi.output(out, l, vars); + } + + out.println("
"); + } } diff --git a/src/org/cacert/gigi/output/MenuItem.java b/src/org/cacert/gigi/output/MenuItem.java index 66d629ff..a0c1ed80 100644 --- a/src/org/cacert/gigi/output/MenuItem.java +++ b/src/org/cacert/gigi/output/MenuItem.java @@ -6,21 +6,23 @@ import java.util.Map; import org.cacert.gigi.Language; public class MenuItem implements Outputable { - final String href; - final String name; - - public MenuItem(String href, String name) { - this.href = href; - this.name = name; - } - - @Override - public void output(PrintWriter out, Language l, Map vars) { - out.print("
  • "); - out.print(l.getTranslation(name)); - out.print("
  • "); - } + + final String href; + + final String name; + + public MenuItem(String href, String name) { + this.href = href; + this.name = name; + } + + @Override + public void output(PrintWriter out, Language l, Map vars) { + out.print("
  • "); + out.print(l.getTranslation(name)); + out.print("
  • "); + } } diff --git a/src/org/cacert/gigi/output/Outputable.java b/src/org/cacert/gigi/output/Outputable.java index 4d5978e5..d228b33d 100644 --- a/src/org/cacert/gigi/output/Outputable.java +++ b/src/org/cacert/gigi/output/Outputable.java @@ -6,5 +6,6 @@ import java.util.Map; import org.cacert.gigi.Language; public interface Outputable { - public void output(PrintWriter out, Language l, Map vars); + + public void output(PrintWriter out, Language l, Map vars); } diff --git a/src/org/cacert/gigi/output/template/ForeachStatement.java b/src/org/cacert/gigi/output/template/ForeachStatement.java index cb74f84f..6cd1e038 100644 --- a/src/org/cacert/gigi/output/template/ForeachStatement.java +++ b/src/org/cacert/gigi/output/template/ForeachStatement.java @@ -8,23 +8,25 @@ import org.cacert.gigi.Language; import org.cacert.gigi.output.Outputable; public final class ForeachStatement implements Outputable { - private final String variable; - private final TemplateBlock body; - public ForeachStatement(String variable, TemplateBlock body) { - this.variable = variable; - this.body = body; - } + private final String variable; - @Override - public void output(PrintWriter out, Language l, Map vars) { - Object o = vars.get(variable); - if (o instanceof IterableDataset) { - IterableDataset id = (IterableDataset) o; - Map subcontext = new HashMap(vars); - while (id.next(l, subcontext)) { - body.output(out, l, subcontext); - } - } - } -} \ No newline at end of file + private final TemplateBlock body; + + public ForeachStatement(String variable, TemplateBlock body) { + this.variable = variable; + this.body = body; + } + + @Override + public void output(PrintWriter out, Language l, Map vars) { + Object o = vars.get(variable); + if (o instanceof IterableDataset) { + IterableDataset id = (IterableDataset) o; + Map subcontext = new HashMap(vars); + while (id.next(l, subcontext)) { + body.output(out, l, subcontext); + } + } + } +} diff --git a/src/org/cacert/gigi/output/template/HashAlgorithms.java b/src/org/cacert/gigi/output/template/HashAlgorithms.java index 453e0d05..24e71f7f 100644 --- a/src/org/cacert/gigi/output/template/HashAlgorithms.java +++ b/src/org/cacert/gigi/output/template/HashAlgorithms.java @@ -7,24 +7,25 @@ import org.cacert.gigi.Language; public class HashAlgorithms implements IterableDataset { - int i = 0; - Digest selected; + int i = 0; - public HashAlgorithms(Digest selected) { - this.selected = selected; - } + Digest selected; - @Override - public boolean next(Language l, Map vars) { - Digest[] length = Digest.values(); - if (i >= length.length) { - return false; - } - Digest d = length[i++]; - vars.put("algorithm", d.toString()); - vars.put("name", d.toString()); - vars.put("info", l.getTranslation(d.getExp())); - vars.put("checked", selected == d ? " checked='checked'" : ""); - return true; - } + public HashAlgorithms(Digest selected) { + this.selected = selected; + } + + @Override + public boolean next(Language l, Map vars) { + Digest[] length = Digest.values(); + if (i >= length.length) { + return false; + } + Digest d = length[i++]; + vars.put("algorithm", d.toString()); + vars.put("name", d.toString()); + vars.put("info", l.getTranslation(d.getExp())); + vars.put("checked", selected == d ? " checked='checked'" : ""); + return true; + } } diff --git a/src/org/cacert/gigi/output/template/IfStatement.java b/src/org/cacert/gigi/output/template/IfStatement.java index e33cd896..bed559ed 100644 --- a/src/org/cacert/gigi/output/template/IfStatement.java +++ b/src/org/cacert/gigi/output/template/IfStatement.java @@ -7,19 +7,21 @@ import org.cacert.gigi.Language; import org.cacert.gigi.output.Outputable; public final class IfStatement implements Outputable { - private final String variable; - private final TemplateBlock body; - public IfStatement(String variable, TemplateBlock body) { - this.variable = variable; - this.body = body; - } + private final String variable; - @Override - public void output(PrintWriter out, Language l, Map vars) { - Object o = vars.get(variable); - if (!(o == Boolean.FALSE || o == null)) { - body.output(out, l, vars); - } - } -} \ No newline at end of file + private final TemplateBlock body; + + public IfStatement(String variable, TemplateBlock body) { + this.variable = variable; + this.body = body; + } + + @Override + public void output(PrintWriter out, Language l, Map vars) { + Object o = vars.get(variable); + if ( !(o == Boolean.FALSE || o == null)) { + body.output(out, l, vars); + } + } +} diff --git a/src/org/cacert/gigi/output/template/IterableDataset.java b/src/org/cacert/gigi/output/template/IterableDataset.java index bd7b99b2..3357be09 100644 --- a/src/org/cacert/gigi/output/template/IterableDataset.java +++ b/src/org/cacert/gigi/output/template/IterableDataset.java @@ -8,16 +8,17 @@ import org.cacert.gigi.Language; * Represents some kind of data, that may be iterated over in a template. */ public interface IterableDataset { - /** - * Moves to the next Dataset. - * - * @param l - * the language for l10n-ed strings - * @param vars - * the variables used in this template. They need to be updated - * for each line. - * @return true, iff there was a data-line "installed". False of this set is - * already empty. - */ - public boolean next(Language l, Map vars); + + /** + * Moves to the next Dataset. + * + * @param l + * the language for l10n-ed strings + * @param vars + * the variables used in this template. They need to be updated + * for each line. + * @return true, iff there was a data-line "installed". False of this set is + * already empty. + */ + public boolean next(Language l, Map vars); } diff --git a/src/org/cacert/gigi/output/template/OutputVariableCommand.java b/src/org/cacert/gigi/output/template/OutputVariableCommand.java index b0f78499..f3c424ab 100644 --- a/src/org/cacert/gigi/output/template/OutputVariableCommand.java +++ b/src/org/cacert/gigi/output/template/OutputVariableCommand.java @@ -7,14 +7,15 @@ import org.cacert.gigi.Language; import org.cacert.gigi.output.Outputable; public final class OutputVariableCommand implements Outputable { - private final String raw; - public OutputVariableCommand(String raw) { - this.raw = raw; - } + private final String raw; - @Override - public void output(PrintWriter out, Language l, Map vars) { - Template.outputVar(out, l, vars, raw); - } -} \ No newline at end of file + public OutputVariableCommand(String raw) { + this.raw = raw; + } + + @Override + public void output(PrintWriter out, Language l, Map vars) { + Template.outputVar(out, l, vars, raw); + } +} diff --git a/src/org/cacert/gigi/output/template/SprintfCommand.java b/src/org/cacert/gigi/output/template/SprintfCommand.java index 42ed9570..1a3c2908 100644 --- a/src/org/cacert/gigi/output/template/SprintfCommand.java +++ b/src/org/cacert/gigi/output/template/SprintfCommand.java @@ -8,22 +8,24 @@ import org.cacert.gigi.Language; import org.cacert.gigi.output.Outputable; public final class SprintfCommand implements Outputable { - private final String text; - private final LinkedList store; - public SprintfCommand(String text, LinkedList store) { - this.text = text; - this.store = store; - } + private final String text; - @Override - 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]); - for (int j = 1; j < parts.length; j++) { - Template.outputVar(out, l, vars, myvars[j - 1].substring(1)); - out.print(parts[j]); - } - } -} \ No newline at end of file + private final LinkedList store; + + public SprintfCommand(String text, LinkedList store) { + this.text = text; + this.store = store; + } + + @Override + 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]); + for (int j = 1; j < parts.length; j++) { + Template.outputVar(out, l, vars, myvars[j - 1].substring(1)); + out.print(parts[j]); + } + } +} diff --git a/src/org/cacert/gigi/output/template/Template.java b/src/org/cacert/gigi/output/template/Template.java index b8dd7424..2702f6c1 100644 --- a/src/org/cacert/gigi/output/template/Template.java +++ b/src/org/cacert/gigi/output/template/Template.java @@ -19,145 +19,147 @@ import org.cacert.gigi.Language; import org.cacert.gigi.output.Outputable; public class Template implements Outputable { - TemplateBlock data; - long lastLoaded; - File source; + TemplateBlock data; - private static final Pattern CONTROL_PATTERN = Pattern.compile(" ?([a-z]+)\\(\\$([^)]+)\\) ?\\{ ?"); + long lastLoaded; - public Template(URL u) { - try { - Reader r = new InputStreamReader(u.openStream(), "UTF-8"); - try { - if (u.getProtocol().equals("file") && DevelLauncher.DEVEL) { - source = new File(u.toURI()); - lastLoaded = source.lastModified() + 1000; - } - } catch (URISyntaxException e) { - e.printStackTrace(); - } - data = parse(r); - r.close(); - } catch (IOException e) { - throw new Error(e); - } - } + File source; - public Template(Reader r) { - try { - data = parse(r); - r.close(); - } catch (IOException e) { - throw new Error(e); - } - } + private static final Pattern CONTROL_PATTERN = Pattern.compile(" ?([a-z]+)\\(\\$([^)]+)\\) ?\\{ ?"); - private TemplateBlock parse(Reader r) throws IOException { - LinkedList splitted = new LinkedList(); - LinkedList commands = new LinkedList(); - StringBuffer buf = new StringBuffer(); - outer: while (true) { - while (!endsWith(buf, "")) { - int ch = r.read(); - if (ch == -1) { - throw new EOFException(); - } - buf.append((char) ch); - } - buf.delete(buf.length() - 2, buf.length()); - String com = buf.toString().replace("\n", ""); - buf.delete(0, buf.length()); - Matcher m = CONTROL_PATTERN.matcher(com); - if (m.matches()) { - String type = m.group(1); - String variable = m.group(2); - TemplateBlock body = parse(r); - if (type.equals("if")) { - commands.add(new IfStatement(variable, body)); - } else if (type.equals("foreach")) { - commands.add(new ForeachStatement(variable, body)); - } else { - throw new IOException("Syntax error: unknown control structure: " + type); - } - continue; - } - if (com.matches(" ?\\} ?")) { - break; - } - commands.add(parseCommand(com)); - } - splitted.add(buf.toString()); - String[] contents = splitted.toArray(new String[splitted.size()]); - Outputable[] vars = commands.toArray(new Outputable[commands.size()]); - return new TemplateBlock(contents, vars); - } + public Template(URL u) { + try { + Reader r = new InputStreamReader(u.openStream(), "UTF-8"); + try { + if (u.getProtocol().equals("file") && DevelLauncher.DEVEL) { + source = new File(u.toURI()); + lastLoaded = source.lastModified() + 1000; + } + } catch (URISyntaxException e) { + e.printStackTrace(); + } + data = parse(r); + r.close(); + } catch (IOException e) { + throw new Error(e); + } + } - private boolean endsWith(StringBuffer buf, String string) { - return buf.length() >= string.length() - && buf.substring(buf.length() - string.length(), buf.length()).equals(string); - } + public Template(Reader r) { + try { + data = parse(r); + r.close(); + } catch (IOException e) { + throw new Error(e); + } + } - private Outputable parseCommand(String s2) { - if (s2.startsWith("=_")) { - final String raw = s2.substring(2); - return new TranslateCommand(raw); - } else if (s2.startsWith("=$")) { - final String raw = s2.substring(2); - return new OutputVariableCommand(raw); - } else if (s2.startsWith("=s,")) { - String command = s2.substring(3); - final LinkedList store = new LinkedList(); - while (command.startsWith("$")) { - int idx = command.indexOf(","); - store.add(command.substring(0, idx)); - command = command.substring(idx + 1); - } - final String text = command; - return new SprintfCommand(text, store); - } else { - System.out.println("Unknown processing instruction: " + s2); - } - return null; - } + private TemplateBlock parse(Reader r) throws IOException { + LinkedList splitted = new LinkedList(); + LinkedList commands = new LinkedList(); + StringBuffer buf = new StringBuffer(); + outer: + while (true) { + while ( !endsWith(buf, "")) { + int ch = r.read(); + if (ch == -1) { + throw new EOFException(); + } + buf.append((char) ch); + } + buf.delete(buf.length() - 2, buf.length()); + String com = buf.toString().replace("\n", ""); + buf.delete(0, buf.length()); + Matcher m = CONTROL_PATTERN.matcher(com); + if (m.matches()) { + String type = m.group(1); + String variable = m.group(2); + TemplateBlock body = parse(r); + if (type.equals("if")) { + commands.add(new IfStatement(variable, body)); + } else if (type.equals("foreach")) { + commands.add(new ForeachStatement(variable, body)); + } else { + throw new IOException("Syntax error: unknown control structure: " + type); + } + continue; + } + if (com.matches(" ?\\} ?")) { + break; + } + commands.add(parseCommand(com)); + } + splitted.add(buf.toString()); + String[] contents = splitted.toArray(new String[splitted.size()]); + Outputable[] vars = commands.toArray(new Outputable[commands.size()]); + return new TemplateBlock(contents, vars); + } - public void output(PrintWriter out, Language l, Map vars) { - if (source != null && DevelLauncher.DEVEL) { - if (lastLoaded < source.lastModified()) { - try { - System.out.println("Reloading template.... " + source); - InputStreamReader r = new InputStreamReader(new FileInputStream(source), "UTF-8"); - data = parse(r); - r.close(); - lastLoaded = source.lastModified() + 1000; - } catch (IOException e) { - e.printStackTrace(); - } - } - } - data.output(out, l, vars); - } + private boolean endsWith(StringBuffer buf, String string) { + return buf.length() >= string.length() && buf.substring(buf.length() - string.length(), buf.length()).equals(string); + } - protected static void outputVar(PrintWriter out, Language l, Map vars, String varname) { - Object s = vars.get(varname); + private Outputable parseCommand(String s2) { + if (s2.startsWith("=_")) { + final String raw = s2.substring(2); + return new TranslateCommand(raw); + } else if (s2.startsWith("=$")) { + final String raw = s2.substring(2); + return new OutputVariableCommand(raw); + } else if (s2.startsWith("=s,")) { + String command = s2.substring(3); + final LinkedList store = new LinkedList(); + while (command.startsWith("$")) { + int idx = command.indexOf(","); + store.add(command.substring(0, idx)); + command = command.substring(idx + 1); + } + final String text = command; + return new SprintfCommand(text, store); + } else { + System.out.println("Unknown processing instruction: " + s2); + } + return null; + } - if (s == null) { - System.out.println("Empty variable: " + varname); - } - if (s instanceof Outputable) { - ((Outputable) s).output(out, l, vars); - } else { - out.print(s); - } - } + public void output(PrintWriter out, Language l, Map vars) { + if (source != null && DevelLauncher.DEVEL) { + if (lastLoaded < source.lastModified()) { + try { + System.out.println("Reloading template.... " + source); + InputStreamReader r = new InputStreamReader(new FileInputStream(source), "UTF-8"); + data = parse(r); + r.close(); + lastLoaded = source.lastModified() + 1000; + } catch (IOException e) { + e.printStackTrace(); + } + } + } + data.output(out, l, vars); + } + + protected static void outputVar(PrintWriter out, Language l, Map vars, String varname) { + Object s = vars.get(varname); + + if (s == null) { + System.out.println("Empty variable: " + varname); + } + if (s instanceof Outputable) { + ((Outputable) s).output(out, l, vars); + } else { + out.print(s); + } + } } diff --git a/src/org/cacert/gigi/output/template/TemplateBlock.java b/src/org/cacert/gigi/output/template/TemplateBlock.java index 8f715773..2a7f4520 100644 --- a/src/org/cacert/gigi/output/template/TemplateBlock.java +++ b/src/org/cacert/gigi/output/template/TemplateBlock.java @@ -7,22 +7,24 @@ import org.cacert.gigi.Language; import org.cacert.gigi.output.Outputable; class TemplateBlock implements Outputable { - String[] contents; - Outputable[] vars; - - public TemplateBlock(String[] contents, Outputable[] vars) { - this.contents = contents; - this.vars = vars; - } - - @Override - public void output(PrintWriter out, Language l, Map vars) { - for (int i = 0; i < contents.length; i++) { - out.print(contents[i]); - if (i < this.vars.length) { - this.vars[i].output(out, l, vars); - } - } - } - -} \ No newline at end of file + + String[] contents; + + Outputable[] vars; + + public TemplateBlock(String[] contents, Outputable[] vars) { + this.contents = contents; + this.vars = vars; + } + + @Override + public void output(PrintWriter out, Language l, Map vars) { + for (int i = 0; i < contents.length; i++) { + out.print(contents[i]); + if (i < this.vars.length) { + this.vars[i].output(out, l, vars); + } + } + } + +} diff --git a/src/org/cacert/gigi/output/template/TranslateCommand.java b/src/org/cacert/gigi/output/template/TranslateCommand.java index 377c841b..18bf4476 100644 --- a/src/org/cacert/gigi/output/template/TranslateCommand.java +++ b/src/org/cacert/gigi/output/template/TranslateCommand.java @@ -7,14 +7,15 @@ import org.cacert.gigi.Language; import org.cacert.gigi.output.Outputable; public final class TranslateCommand implements Outputable { - private final String raw; - public TranslateCommand(String raw) { - this.raw = raw; - } + private final String raw; - @Override - public void output(PrintWriter out, Language l, Map vars) { - out.print(l.getTranslation(raw)); - } -} \ No newline at end of file + public TranslateCommand(String raw) { + this.raw = raw; + } + + @Override + public void output(PrintWriter out, Language l, Map vars) { + out.print(l.getTranslation(raw)); + } +} diff --git a/src/org/cacert/gigi/pages/LoginPage.java b/src/org/cacert/gigi/pages/LoginPage.java index 7be71177..19b8853d 100644 --- a/src/org/cacert/gigi/pages/LoginPage.java +++ b/src/org/cacert/gigi/pages/LoginPage.java @@ -18,95 +18,91 @@ import org.cacert.gigi.database.DatabaseConnection; import org.cacert.gigi.util.PasswordHash; public class LoginPage extends Page { - public static final String LOGIN_RETURNPATH = "login-returnpath"; - public LoginPage(String title) { - super(title); - } + public static final String LOGIN_RETURNPATH = "login-returnpath"; - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - resp.getWriter().println( - "
    " + "" - + "
    "); - } + public LoginPage(String title) { + super(title); + } - @Override - 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"); - if (cert != null && cert[0] != null) { - tryAuthWithCertificate(req, cert[0]); - } - if (req.getMethod().equals("POST")) { - tryAuthWithUnpw(req); - } - } + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + resp.getWriter().println("
    " + "" + "
    "); + } - if (req.getSession().getAttribute("loggedin") != null) { - String s = redir; - if (s != null) { - if (!s.startsWith("/")) { - s = "/" + s; - } - resp.sendRedirect(s); - } else { - resp.sendRedirect("/"); - } - return true; - } - return false; - } + @Override + 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"); + if (cert != null && cert[0] != null) { + tryAuthWithCertificate(req, cert[0]); + } + if (req.getMethod().equals("POST")) { + tryAuthWithUnpw(req); + } + } - @Override - public boolean needsLogin() { - return false; - } + if (req.getSession().getAttribute("loggedin") != null) { + String s = redir; + if (s != null) { + if ( !s.startsWith("/")) { + s = "/" + s; + } + resp.sendRedirect(s); + } else { + resp.sendRedirect("/"); + } + return true; + } + 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'"); - ps.setString(1, un); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - if (PasswordHash.verifyHash(pw, rs.getString(1))) { - req.getSession().invalidate(); - HttpSession hs = req.getSession(); - hs.setAttribute(LOGGEDIN, true); - hs.setAttribute(USER, new User(rs.getInt(2))); - } - } - rs.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } + @Override + public boolean needsLogin() { + return false; + } - public static User getUser(HttpServletRequest req) { - return (User) req.getSession().getAttribute(USER); - } + 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'"); + ps.setString(1, un); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + if (PasswordHash.verifyHash(pw, rs.getString(1))) { + req.getSession().invalidate(); + HttpSession hs = req.getSession(); + hs.setAttribute(LOGGEDIN, true); + hs.setAttribute(USER, new User(rs.getInt(2))); + } + } + rs.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } - 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'"); - ps.setString(1, serial); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - req.getSession().invalidate(); - HttpSession hs = req.getSession(); - hs.setAttribute(LOGGEDIN, true); - hs.setAttribute(USER, new User(rs.getInt(1))); - } - rs.close(); - } catch (SQLException e) { - 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(); + try { + 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()) { + req.getSession().invalidate(); + HttpSession hs = req.getSession(); + hs.setAttribute(LOGGEDIN, true); + hs.setAttribute(USER, new User(rs.getInt(1))); + } + rs.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } } diff --git a/src/org/cacert/gigi/pages/MainPage.java b/src/org/cacert/gigi/pages/MainPage.java index 96b30aed..bb9c71c3 100644 --- a/src/org/cacert/gigi/pages/MainPage.java +++ b/src/org/cacert/gigi/pages/MainPage.java @@ -6,17 +6,18 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MainPage extends Page { - public MainPage(String title) { - super(title); - } - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - resp.getWriter().println("Access granted."); - } + public MainPage(String title) { + super(title); + } - @Override - public boolean needsLogin() { - return false; - } + @Override + 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 9a5c178a..320107f8 100644 --- a/src/org/cacert/gigi/pages/Page.java +++ b/src/org/cacert/gigi/pages/Page.java @@ -15,97 +15,99 @@ import org.cacert.gigi.output.template.Template; * class with name <className>.templ will be loaded automatically. */ public abstract class Page { - private String title; - private Template defaultTemplate; - - public Page(String title) { - this.title = title; - URL resource = getClass().getResource(getClass().getSimpleName() + ".templ"); - if (resource != null) { - defaultTemplate = new Template(resource); - } - } - - /** - * Retrieves the default template (<className>.templ) which has - * already been loaded. - * - * @return the default template. - */ - public Template getDefaultTemplate() { - return defaultTemplate; - } - - /** - * This method can be overridden to execute code and do stuff before the - * default template is applied. - * - * @param req - * the request to handle. - * @param resp - * the response to write to - * @return true, if the request is consumed and the default template should - * not be applied. - * @throws IOException - * if output goes wrong. - */ - public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException { - return false; - } - - /** - * This method is called to generate the content inside the default - * template. - * - * @param req - * the request to handle. - * @param resp - * the response to write to - * @throws IOException - * if output goes wrong. - */ - public abstract void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException; - - /** - * Same as {@link #doGet(HttpServletRequest, HttpServletResponse)} but for - * POST requests. By default they are redirected to - * {@link #doGet(HttpServletRequest, HttpServletResponse)}; - * - * @param req - * the request to handle. - * @param resp - * the response to write to - * @throws IOException - * if output goes wrong. - */ - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { - doGet(req, resp); - } - - /** - * Returns true, if this page requires login. Default is true - * - * @return if the page needs login. - */ - public boolean needsLogin() { - return true; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public static Language getLanguage(ServletRequest req) { - return Language.getInstance("de"); - } - - public static String translate(ServletRequest req, String string) { - Language l = getLanguage(req); - return l.getTranslation(string); - } + + private String title; + + private Template defaultTemplate; + + public Page(String title) { + this.title = title; + URL resource = getClass().getResource(getClass().getSimpleName() + ".templ"); + if (resource != null) { + defaultTemplate = new Template(resource); + } + } + + /** + * Retrieves the default template (<className>.templ) which has + * already been loaded. + * + * @return the default template. + */ + public Template getDefaultTemplate() { + return defaultTemplate; + } + + /** + * This method can be overridden to execute code and do stuff before the + * default template is applied. + * + * @param req + * the request to handle. + * @param resp + * the response to write to + * @return true, if the request is consumed and the default template should + * not be applied. + * @throws IOException + * if output goes wrong. + */ + public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException { + return false; + } + + /** + * This method is called to generate the content inside the default + * template. + * + * @param req + * the request to handle. + * @param resp + * the response to write to + * @throws IOException + * if output goes wrong. + */ + public abstract void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException; + + /** + * Same as {@link #doGet(HttpServletRequest, HttpServletResponse)} but for + * POST requests. By default they are redirected to + * {@link #doGet(HttpServletRequest, HttpServletResponse)}; + * + * @param req + * the request to handle. + * @param resp + * the response to write to + * @throws IOException + * if output goes wrong. + */ + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { + doGet(req, resp); + } + + /** + * Returns true, if this page requires login. Default is true + * + * @return if the page needs login. + */ + public boolean needsLogin() { + return true; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public static Language getLanguage(ServletRequest req) { + return Language.getInstance("de"); + } + + public static String translate(ServletRequest req, String string) { + Language l = getLanguage(req); + return l.getTranslation(string); + } } diff --git a/src/org/cacert/gigi/pages/TestSecure.java b/src/org/cacert/gigi/pages/TestSecure.java index 02c8ada8..5f8d38ca 100644 --- a/src/org/cacert/gigi/pages/TestSecure.java +++ b/src/org/cacert/gigi/pages/TestSecure.java @@ -7,13 +7,13 @@ import javax.servlet.http.HttpServletResponse; public class TestSecure extends Page { - public TestSecure() { - super("Secure testpage"); - } + public TestSecure() { + super("Secure testpage"); + } - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - resp.getWriter().println("This page is secure."); - } + @Override + 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 5f8aa8f9..fff62628 100644 --- a/src/org/cacert/gigi/pages/Verify.java +++ b/src/org/cacert/gigi/pages/Verify.java @@ -9,34 +9,35 @@ import org.cacert.gigi.EmailAddress; import org.cacert.gigi.GigiApiException; 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 { - PrintWriter out = resp.getWriter(); - String hash = req.getParameter("hash"); - String type = req.getParameter("type"); - String id = req.getParameter("id"); - if ("email".equals(type)) { - try { - EmailAddress ea = EmailAddress.getById(Integer.parseInt(id)); - ea.verify(hash); - out.println("Email verification completed."); - } catch (IllegalArgumentException e) { - out.println(translate(req, "The email address is invalid.")); - } catch (GigiApiException e) { - e.format(out, getLanguage(req)); - } - } - } + + 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 { + PrintWriter out = resp.getWriter(); + String hash = req.getParameter("hash"); + String type = req.getParameter("type"); + String id = req.getParameter("id"); + if ("email".equals(type)) { + try { + EmailAddress ea = EmailAddress.getById(Integer.parseInt(id)); + ea.verify(hash); + out.println("Email verification completed."); + } catch (IllegalArgumentException e) { + out.println(translate(req, "The email address is invalid.")); + } catch (GigiApiException e) { + e.format(out, getLanguage(req)); + } + } + } } diff --git a/src/org/cacert/gigi/pages/account/ChangeForm.java b/src/org/cacert/gigi/pages/account/ChangeForm.java index 5458b63d..c678cf1f 100644 --- a/src/org/cacert/gigi/pages/account/ChangeForm.java +++ b/src/org/cacert/gigi/pages/account/ChangeForm.java @@ -13,47 +13,48 @@ import org.cacert.gigi.output.template.Template; import org.cacert.gigi.pages.Page; public class ChangeForm extends Form { - User target; - - public ChangeForm(HttpServletRequest hsr, User target) { - super(hsr); - this.target = target; - } - - private static Template t; - static { - t = new Template(ChangePasswordPage.class.getResource("ChangePasswordForm.templ")); - } - - @Override - public void outputContent(PrintWriter out, Language l, Map vars) { - t.output(out, l, vars); - } - - @Override - public boolean submit(PrintWriter out, HttpServletRequest req) { - String oldpassword = req.getParameter("oldpassword"); - String p1 = req.getParameter("pword1"); - String p2 = req.getParameter("pword2"); - GigiApiException error = new GigiApiException(); - if (oldpassword == null || p1 == null || p2 == null) { - new GigiApiException("All fields are required.").format(out, Page.getLanguage(req)); - return false; - } - if (!p1.equals(p2)) { - new GigiApiException("New passwords do not match.").format(out, Page.getLanguage(req)); - return false; - } - try { - target.changePassword(oldpassword, p1); - } catch (GigiApiException e) { - error.mergeInto(e); - } - if (!error.isEmpty()) { - error.format(out, Page.getLanguage(req)); - return false; - } - return true; - } + + User target; + + public ChangeForm(HttpServletRequest hsr, User target) { + super(hsr); + this.target = target; + } + + private static Template t; + static { + t = new Template(ChangePasswordPage.class.getResource("ChangePasswordForm.templ")); + } + + @Override + public void outputContent(PrintWriter out, Language l, Map vars) { + t.output(out, l, vars); + } + + @Override + public boolean submit(PrintWriter out, HttpServletRequest req) { + String oldpassword = req.getParameter("oldpassword"); + String p1 = req.getParameter("pword1"); + String p2 = req.getParameter("pword2"); + GigiApiException error = new GigiApiException(); + if (oldpassword == null || p1 == null || p2 == null) { + new GigiApiException("All fields are required.").format(out, Page.getLanguage(req)); + return false; + } + if ( !p1.equals(p2)) { + new GigiApiException("New passwords do not match.").format(out, Page.getLanguage(req)); + return false; + } + try { + target.changePassword(oldpassword, p1); + } catch (GigiApiException e) { + error.mergeInto(e); + } + if ( !error.isEmpty()) { + error.format(out, Page.getLanguage(req)); + return false; + } + return true; + } } diff --git a/src/org/cacert/gigi/pages/account/ChangePasswordPage.java b/src/org/cacert/gigi/pages/account/ChangePasswordPage.java index 75fd6bb2..805c72d9 100644 --- a/src/org/cacert/gigi/pages/account/ChangePasswordPage.java +++ b/src/org/cacert/gigi/pages/account/ChangePasswordPage.java @@ -11,22 +11,22 @@ import org.cacert.gigi.pages.LoginPage; import org.cacert.gigi.pages.Page; public class ChangePasswordPage extends Page { - public static final String PATH = "/account/password"; - - public ChangePasswordPage() { - super("Change Password"); - } - - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - new ChangeForm(req, LoginPage.getUser(req)).output(resp.getWriter(), getLanguage(req), - new HashMap()); - } - - @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { - ChangeForm f = Form.getForm(req, ChangeForm.class); - f.submit(resp.getWriter(), req); - } + + public static final String PATH = "/account/password"; + + public ChangePasswordPage() { + super("Change Password"); + } + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + new ChangeForm(req, LoginPage.getUser(req)).output(resp.getWriter(), getLanguage(req), new HashMap()); + } + + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { + ChangeForm f = Form.getForm(req, ChangeForm.class); + f.submit(resp.getWriter(), req); + } } diff --git a/src/org/cacert/gigi/pages/account/IssueCertificateForm.java b/src/org/cacert/gigi/pages/account/IssueCertificateForm.java index da3a85b3..e470f21b 100644 --- a/src/org/cacert/gigi/pages/account/IssueCertificateForm.java +++ b/src/org/cacert/gigi/pages/account/IssueCertificateForm.java @@ -29,125 +29,128 @@ import org.cacert.gigi.pages.LoginPage; import sun.security.pkcs10.PKCS10; /** - * This class represents a form that is used for issuing certificates. - * - * This class uses "sun.security" and therefore needs "-XDignore.symbol.file" - * + * This class represents a form that is used for issuing certificates. This + * class uses "sun.security" and therefore needs "-XDignore.symbol.file" */ public class IssueCertificateForm extends Form { - User u; - Digest selectedDigest = Digest.getDefault(); - boolean login; - String csr; - - private final static Template t = new Template(IssueCertificateForm.class.getResource("IssueCertificateForm.templ")); - - public IssueCertificateForm(HttpServletRequest hsr) { - super(hsr); - u = LoginPage.getUser(hsr); - } - - Certificate result; - private CSRType csrType; - - public Certificate getResult() { - return result; - } - - @Override - public boolean submit(PrintWriter out, HttpServletRequest req) { - String csr = req.getParameter("CSR"); - String spkac = req.getParameter("SPKAC"); - try { - if (csr != null) { - PKCS10 parsed = parseCSR(csr); - out.println(parsed.getSubjectName().getCommonName()); - out.println(parsed.getSubjectName().getCountry()); - out.println("CSR DN: " + parsed.getSubjectName() + "
    "); - PublicKey pk = parsed.getSubjectPublicKeyInfo(); - out.println("Type: " + pk.getAlgorithm() + "
    "); - if (pk instanceof RSAPublicKey) { - out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "
    "); - out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength()); - } else if (pk instanceof DSAPublicKey) { - DSAPublicKey dpk = (DSAPublicKey) pk; - out.println("Length: " + dpk.getY().bitLength() + "
    "); - out.println(dpk.getParams()); - } else if (pk instanceof ECPublicKey) { - ECPublicKey epk = (ECPublicKey) pk; - out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "
    "); - out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "
    "); - out.println(epk.getParams().getCurve()); - } - out.println("
    digest: sha256
    "); - this.csr = csr; - this.csrType = CSRType.CSR; - } else if (spkac != null) { - this.csr = "SPKAC=" + spkac.replaceAll("[\r\n]", ""); - this.csrType = CSRType.SPKAC; - } else { - login = "1".equals(req.getParameter("login")); - String hashAlg = req.getParameter("hash_alg"); - if (hashAlg != null) { - selectedDigest = Digest.valueOf(hashAlg); - } - if (req.getParameter("CCA") == null) { - outputError(out, req, "You need to accept the CCA."); - return false; - } - System.out.println("issuing " + selectedDigest); - result = new Certificate(LoginPage.getUser(req).getId(), "/commonName=CAcert WoT User", - selectedDigest.toString(), this.csr, this.csrType); - try { - result.issue().waitFor(60000); - return true; - } catch (SQLException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return false; - } - } catch (IOException e) { - e.printStackTrace(); - } catch (GeneralSecurityException e) { - e.printStackTrace(); - } - return false; - } - - private PKCS10 parseCSR(String csr) throws IOException, GeneralSecurityException { - csr = csr.replaceFirst("-----BEGIN (NEW )?CERTIFICATE REQUEST-----", ""); - csr = csr.replaceFirst("-----END (NEW )?CERTIFICATE REQUEST-----", ""); - csr = csr.replace("\r", ""); - csr = csr.replace("\n", ""); - byte[] b = Base64.getDecoder().decode(csr); - // Also checks signature validity - return new PKCS10(b); - } - - @Override - protected void outputContent(PrintWriter out, Language l, Map vars) { - HashMap vars2 = new HashMap(vars); - vars2.put("CCA", "CCA"); - - final EmailAddress[] ea = u.getEmails(); - vars2.put("emails", new IterableDataset() { - int count; - - @Override - public boolean next(Language l, Map vars) { - if (count >= ea.length) { - return false; - } - vars.put("id", ea[count].getId()); - vars.put("value", ea[count].getAddress()); - count++; - return true; - } - }); - vars2.put("hashs", new HashAlgorithms(selectedDigest)); - t.output(out, l, vars2); - } + + User u; + + Digest selectedDigest = Digest.getDefault(); + + boolean login; + + String csr; + + private final static Template t = new Template(IssueCertificateForm.class.getResource("IssueCertificateForm.templ")); + + public IssueCertificateForm(HttpServletRequest hsr) { + super(hsr); + u = LoginPage.getUser(hsr); + } + + Certificate result; + + private CSRType csrType; + + public Certificate getResult() { + return result; + } + + @Override + public boolean submit(PrintWriter out, HttpServletRequest req) { + String csr = req.getParameter("CSR"); + String spkac = req.getParameter("SPKAC"); + try { + if (csr != null) { + PKCS10 parsed = parseCSR(csr); + out.println(parsed.getSubjectName().getCommonName()); + out.println(parsed.getSubjectName().getCountry()); + out.println("CSR DN: " + parsed.getSubjectName() + "
    "); + PublicKey pk = parsed.getSubjectPublicKeyInfo(); + out.println("Type: " + pk.getAlgorithm() + "
    "); + if (pk instanceof RSAPublicKey) { + out.println("Exponent: " + ((RSAPublicKey) pk).getPublicExponent() + "
    "); + out.println("Length: " + ((RSAPublicKey) pk).getModulus().bitLength()); + } else if (pk instanceof DSAPublicKey) { + DSAPublicKey dpk = (DSAPublicKey) pk; + out.println("Length: " + dpk.getY().bitLength() + "
    "); + out.println(dpk.getParams()); + } else if (pk instanceof ECPublicKey) { + ECPublicKey epk = (ECPublicKey) pk; + out.println("Length-x: " + epk.getW().getAffineX().bitLength() + "
    "); + out.println("Length-y: " + epk.getW().getAffineY().bitLength() + "
    "); + out.println(epk.getParams().getCurve()); + } + out.println("
    digest: sha256
    "); + this.csr = csr; + this.csrType = CSRType.CSR; + } else if (spkac != null) { + this.csr = "SPKAC=" + spkac.replaceAll("[\r\n]", ""); + this.csrType = CSRType.SPKAC; + } else { + login = "1".equals(req.getParameter("login")); + String hashAlg = req.getParameter("hash_alg"); + if (hashAlg != null) { + selectedDigest = Digest.valueOf(hashAlg); + } + if (req.getParameter("CCA") == null) { + outputError(out, req, "You need to accept the CCA."); + return false; + } + System.out.println("issuing " + selectedDigest); + result = new Certificate(LoginPage.getUser(req).getId(), "/commonName=CAcert WoT User", selectedDigest.toString(), this.csr, this.csrType); + try { + result.issue().waitFor(60000); + return true; + } catch (SQLException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return false; + } + } catch (IOException e) { + e.printStackTrace(); + } catch (GeneralSecurityException e) { + e.printStackTrace(); + } + return false; + } + + private PKCS10 parseCSR(String csr) throws IOException, GeneralSecurityException { + csr = csr.replaceFirst("-----BEGIN (NEW )?CERTIFICATE REQUEST-----", ""); + csr = csr.replaceFirst("-----END (NEW )?CERTIFICATE REQUEST-----", ""); + csr = csr.replace("\r", ""); + csr = csr.replace("\n", ""); + byte[] b = Base64.getDecoder().decode(csr); + // Also checks signature validity + return new PKCS10(b); + } + + @Override + protected void outputContent(PrintWriter out, Language l, Map vars) { + HashMap vars2 = new HashMap(vars); + vars2.put("CCA", "CCA"); + + final EmailAddress[] ea = u.getEmails(); + vars2.put("emails", new IterableDataset() { + + int count; + + @Override + public boolean next(Language l, Map vars) { + if (count >= ea.length) { + return false; + } + vars.put("id", ea[count].getId()); + vars.put("value", ea[count].getAddress()); + count++; + return true; + } + }); + vars2.put("hashs", new HashAlgorithms(selectedDigest)); + t.output(out, l, vars2); + } } diff --git a/src/org/cacert/gigi/pages/account/MailAddForm.java b/src/org/cacert/gigi/pages/account/MailAddForm.java index 14f5ddba..99af485d 100644 --- a/src/org/cacert/gigi/pages/account/MailAddForm.java +++ b/src/org/cacert/gigi/pages/account/MailAddForm.java @@ -13,35 +13,38 @@ import org.cacert.gigi.output.template.Template; import org.cacert.gigi.pages.Page; public class MailAddForm extends Form { - private static Template t; - private String mail; - static { - t = new Template(ChangePasswordPage.class.getResource("MailAddForm.templ")); - } - User target; - - public MailAddForm(HttpServletRequest hsr, User target) { - super(hsr); - this.target = target; - } - - @Override - public boolean submit(PrintWriter out, HttpServletRequest req) { - String formMail = req.getParameter("newemail"); - mail = formMail; - try { - EmailAddress addr = new EmailAddress(mail, target); - addr.insert(Page.getLanguage(req)); - } catch (IllegalArgumentException e) { - out.println("
    Error: Invalid address!
    "); - return false; - } - return true; - } - - @Override - protected void outputContent(PrintWriter out, Language l, Map vars) { - t.output(out, l, vars); - } + + private static Template t; + + private String mail; + static { + t = new Template(ChangePasswordPage.class.getResource("MailAddForm.templ")); + } + + User target; + + public MailAddForm(HttpServletRequest hsr, User target) { + super(hsr); + this.target = target; + } + + @Override + public boolean submit(PrintWriter out, HttpServletRequest req) { + String formMail = req.getParameter("newemail"); + mail = formMail; + try { + EmailAddress addr = new EmailAddress(mail, target); + addr.insert(Page.getLanguage(req)); + } catch (IllegalArgumentException e) { + out.println("
    Error: Invalid address!
    "); + return false; + } + return true; + } + + @Override + protected void outputContent(PrintWriter out, Language l, Map vars) { + t.output(out, l, vars); + } } diff --git a/src/org/cacert/gigi/pages/account/MailCertificateAdd.java b/src/org/cacert/gigi/pages/account/MailCertificateAdd.java index c25db15f..9541a5ad 100644 --- a/src/org/cacert/gigi/pages/account/MailCertificateAdd.java +++ b/src/org/cacert/gigi/pages/account/MailCertificateAdd.java @@ -12,36 +12,38 @@ import org.cacert.gigi.output.template.Template; import org.cacert.gigi.pages.Page; public class MailCertificateAdd extends Page { - public static final String PATH = "/account/certs/email/new"; - Template t = new Template(MailCertificateAdd.class.getResource("RequestCertificate.templ")); - - public MailCertificateAdd() { - super("Create Email certificate"); - } - - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - HashMap vars = new HashMap(); - vars.put("CCA", "CCA"); - - t.output(resp.getWriter(), getLanguage(req), vars); - } - - @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { - IssueCertificateForm f; - if (req.getParameter(Form.CSRF_FIELD) != null) { - f = Form.getForm(req, IssueCertificateForm.class); - if (f.submit(resp.getWriter(), req)) { - Certificate c = f.getResult(); - String ser = c.getSerial(); - resp.sendRedirect(MailCertificates.PATH + "/" + ser); - } - } else { - f = new IssueCertificateForm(req); - f.submit(resp.getWriter(), req); - } - f.output(resp.getWriter(), getLanguage(req), Collections. emptyMap()); - - } + + public static final String PATH = "/account/certs/email/new"; + + Template t = new Template(MailCertificateAdd.class.getResource("RequestCertificate.templ")); + + public MailCertificateAdd() { + super("Create Email certificate"); + } + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + HashMap vars = new HashMap(); + vars.put("CCA", "CCA"); + + t.output(resp.getWriter(), getLanguage(req), vars); + } + + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { + IssueCertificateForm f; + if (req.getParameter(Form.CSRF_FIELD) != null) { + f = Form.getForm(req, IssueCertificateForm.class); + if (f.submit(resp.getWriter(), req)) { + Certificate c = f.getResult(); + String ser = c.getSerial(); + resp.sendRedirect(MailCertificates.PATH + "/" + ser); + } + } else { + f = new IssueCertificateForm(req); + f.submit(resp.getWriter(), req); + } + f.output(resp.getWriter(), getLanguage(req), Collections.emptyMap()); + + } } diff --git a/src/org/cacert/gigi/pages/account/MailCertificates.java b/src/org/cacert/gigi/pages/account/MailCertificates.java index de8c1ca0..d65a3ef0 100644 --- a/src/org/cacert/gigi/pages/account/MailCertificates.java +++ b/src/org/cacert/gigi/pages/account/MailCertificates.java @@ -22,127 +22,128 @@ import org.cacert.gigi.pages.LoginPage; import org.cacert.gigi.pages.Page; public class MailCertificates extends Page { - CertificateTable myTable = new CertificateTable("mailcerts"); - public static final String PATH = "/account/certs/email"; - - public MailCertificates() { - super("Email Certificates"); - } - - @Override - public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException { - - String pi = req.getPathInfo().substring(PATH.length()); - if (pi.length() == 0) { - return false; - } - pi = pi.substring(1); - boolean crt = false; - boolean cer = false; - resp.setContentType("application/pkix-cert"); - if (pi.endsWith(".crt")) { - crt = true; - pi = pi.substring(0, pi.length() - 4); - } else if (pi.endsWith(".cer")) { - if (req.getParameter("install") != null) { - resp.setContentType("application/x-x509-user-cert"); - } - cer = true; - pi = pi.substring(0, pi.length() - 4); - } else if (pi.endsWith(".cer")) { - cer = true; - pi = pi.substring(0, pi.length() - 4); - } - String serial = pi; - try { - Certificate c = Certificate.getBySerial(serial); - if (c == null || LoginPage.getUser(req).getId() != c.getOwnerId()) { - resp.sendError(404); - return true; - } - X509Certificate cert = c.cert(); - if (!crt && !cer) { - return false; - } - ServletOutputStream out = resp.getOutputStream(); - if (crt) { - out.println("-----BEGIN CERTIFICATE-----"); - String block = Base64.getEncoder().encodeToString(cert.getEncoded()).replaceAll("(.{64})(?=.)", "$1\n"); - out.println(block); - out.println("-----END CERTIFICATE-----"); - } else if (cer) { - out.write(cert.getEncoded()); - } - } catch (IllegalArgumentException e) { - resp.sendError(404); - return true; - } catch (GeneralSecurityException e) { - resp.sendError(404); - return true; - } catch (SQLException e) { - resp.sendError(404); - return true; - } - - return true; - } - - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - PrintWriter out = resp.getWriter(); - String pi = req.getPathInfo().substring(PATH.length()); - if (pi.length() != 0) { - pi = pi.substring(1); - - String serial = pi; - Certificate c = Certificate.getBySerial(serial); - if (c == null || LoginPage.getUser(req).getId() != c.getOwnerId()) { - resp.sendError(404); - return; - } - out.print(""); - out.print(translate(req, "PEM encoded Certificate")); - out.println("
    "); - - out.print(""); - out.print(translate(req, "DER encoded Certificate")); - out.println("
    "); - out.print(""); - out.print(translate(req, "Install into browser.")); - out.println("
    "); - - out.println("
    ");
    -			try {
    -				X509Certificate cert = c.cert();
    -				out.print(cert);
    -			} catch (GeneralSecurityException e) {
    -				e.printStackTrace();
    -			} catch (SQLException e) {
    -				e.printStackTrace();
    -			}
    -			out.println("
    "); - return; - } - - 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`=?"); - ps.setInt(1, us.getId()); - ResultSet rs = ps.executeQuery(); - vars.put("mailcerts", rs); - myTable.output(out, getLanguage(req), vars); - rs.close(); - } catch (SQLException e) { - e.printStackTrace(); - } - } + + CertificateTable myTable = new CertificateTable("mailcerts"); + + public static final String PATH = "/account/certs/email"; + + public MailCertificates() { + super("Email Certificates"); + } + + @Override + public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException { + + String pi = req.getPathInfo().substring(PATH.length()); + if (pi.length() == 0) { + return false; + } + pi = pi.substring(1); + boolean crt = false; + boolean cer = false; + resp.setContentType("application/pkix-cert"); + if (pi.endsWith(".crt")) { + crt = true; + pi = pi.substring(0, pi.length() - 4); + } else if (pi.endsWith(".cer")) { + if (req.getParameter("install") != null) { + resp.setContentType("application/x-x509-user-cert"); + } + cer = true; + pi = pi.substring(0, pi.length() - 4); + } else if (pi.endsWith(".cer")) { + cer = true; + pi = pi.substring(0, pi.length() - 4); + } + String serial = pi; + try { + Certificate c = Certificate.getBySerial(serial); + if (c == null || LoginPage.getUser(req).getId() != c.getOwnerId()) { + resp.sendError(404); + return true; + } + X509Certificate cert = c.cert(); + if ( !crt && !cer) { + return false; + } + ServletOutputStream out = resp.getOutputStream(); + if (crt) { + out.println("-----BEGIN CERTIFICATE-----"); + String block = Base64.getEncoder().encodeToString(cert.getEncoded()).replaceAll("(.{64})(?=.)", "$1\n"); + out.println(block); + out.println("-----END CERTIFICATE-----"); + } else if (cer) { + out.write(cert.getEncoded()); + } + } catch (IllegalArgumentException e) { + resp.sendError(404); + return true; + } catch (GeneralSecurityException e) { + resp.sendError(404); + return true; + } catch (SQLException e) { + resp.sendError(404); + return true; + } + + return true; + } + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + PrintWriter out = resp.getWriter(); + String pi = req.getPathInfo().substring(PATH.length()); + if (pi.length() != 0) { + pi = pi.substring(1); + + String serial = pi; + Certificate c = Certificate.getBySerial(serial); + if (c == null || LoginPage.getUser(req).getId() != c.getOwnerId()) { + resp.sendError(404); + return; + } + out.print(""); + out.print(translate(req, "PEM encoded Certificate")); + out.println("
    "); + + out.print(""); + out.print(translate(req, "DER encoded Certificate")); + out.println("
    "); + out.print(""); + out.print(translate(req, "Install into browser.")); + out.println("
    "); + + out.println("
    ");
    +            try {
    +                X509Certificate cert = c.cert();
    +                out.print(cert);
    +            } catch (GeneralSecurityException e) {
    +                e.printStackTrace();
    +            } catch (SQLException e) {
    +                e.printStackTrace();
    +            }
    +            out.println("
    "); + return; + } + + 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`=?"); + ps.setInt(1, us.getId()); + ResultSet rs = ps.executeQuery(); + vars.put("mailcerts", rs); + myTable.output(out, getLanguage(req), vars); + rs.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } } diff --git a/src/org/cacert/gigi/pages/account/MailManagementForm.java b/src/org/cacert/gigi/pages/account/MailManagementForm.java index 3e82bd2a..ffadc63f 100644 --- a/src/org/cacert/gigi/pages/account/MailManagementForm.java +++ b/src/org/cacert/gigi/pages/account/MailManagementForm.java @@ -14,54 +14,56 @@ import org.cacert.gigi.output.template.Template; import org.cacert.gigi.pages.Page; public class MailManagementForm extends Form { - private static Template t; - private User target; - static { - t = new Template(ChangePasswordPage.class.getResource("MailManagementForm.templ")); - } - public MailManagementForm(HttpServletRequest hsr, User target) { - super(hsr); - this.target = target; - } + private static Template t; - @Override - public boolean submit(PrintWriter out, HttpServletRequest req) { - if (req.getParameter("makedefault") != null) { - try { - String mailid = req.getParameter("emailid"); - if (mailid == null) { - return false; - } - target.updateDefaultEmail(EmailAddress.getById(Integer.parseInt(mailid.trim()))); - } catch (GigiApiException e) { - e.format(out, Page.getLanguage(req)); - return false; - } - return true; - } - if (req.getParameter("delete") != null) { - String[] toDel = req.getParameterValues("delid[]"); - if (toDel == null) { - return false; - } - for (int i = 0; i < toDel.length; i++) { - try { - target.deleteEmail(EmailAddress.getById(Integer.parseInt(toDel[i].trim()))); - } catch (GigiApiException e) { - e.format(out, Page.getLanguage(req)); - return false; - } - } - return true; + private User target; + static { + t = new Template(ChangePasswordPage.class.getResource("MailManagementForm.templ")); + } - } - return false; - } + public MailManagementForm(HttpServletRequest hsr, User target) { + super(hsr); + this.target = target; + } - @Override - protected void outputContent(PrintWriter out, Language l, Map vars) { - t.output(out, l, vars); - } + @Override + public boolean submit(PrintWriter out, HttpServletRequest req) { + if (req.getParameter("makedefault") != null) { + try { + String mailid = req.getParameter("emailid"); + if (mailid == null) { + return false; + } + target.updateDefaultEmail(EmailAddress.getById(Integer.parseInt(mailid.trim()))); + } catch (GigiApiException e) { + e.format(out, Page.getLanguage(req)); + return false; + } + return true; + } + if (req.getParameter("delete") != null) { + String[] toDel = req.getParameterValues("delid[]"); + if (toDel == null) { + return false; + } + for (int i = 0; i < toDel.length; i++) { + try { + target.deleteEmail(EmailAddress.getById(Integer.parseInt(toDel[i].trim()))); + } catch (GigiApiException e) { + e.format(out, Page.getLanguage(req)); + return false; + } + } + return true; + + } + return false; + } + + @Override + protected void outputContent(PrintWriter out, Language l, Map vars) { + t.output(out, l, vars); + } } diff --git a/src/org/cacert/gigi/pages/account/MailOverview.java b/src/org/cacert/gigi/pages/account/MailOverview.java index 8547303e..9ce150f8 100644 --- a/src/org/cacert/gigi/pages/account/MailOverview.java +++ b/src/org/cacert/gigi/pages/account/MailOverview.java @@ -17,88 +17,91 @@ import org.cacert.gigi.pages.LoginPage; import org.cacert.gigi.pages.Page; public class MailOverview extends Page { - public static final String DEFAULT_PATH = "/account/mails"; - private MailTable t; - public MailOverview(String title) { - super(title); - t = new MailTable("us"); - } + public static final String DEFAULT_PATH = "/account/mails"; - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - final User us = LoginPage.getUser(req); - Language lang = Page.getLanguage(req); - HashMap vars = new HashMap<>(); - vars.put("mailData", t); - vars.put("us", us); - vars.put("addForm", new MailAddForm(req, us)); - vars.put("manForm", new MailManagementForm(req, us)); - getDefaultTemplate().output(resp.getWriter(), lang, vars); - } + private MailTable t; - @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { - PrintWriter out = resp.getWriter(); - if (req.getParameter("addmail") != null) { - MailAddForm f = Form.getForm(req, MailAddForm.class); - if (f.submit(out, req)) { - resp.sendRedirect(MailOverview.DEFAULT_PATH); - } - } else if (req.getParameter("makedefault") != null || req.getParameter("delete") != null) { - MailManagementForm f = Form.getForm(req, MailManagementForm.class); - if (f.submit(out, req)) { - resp.sendRedirect(MailOverview.DEFAULT_PATH); - } - } - super.doPost(req, resp); - } + public MailOverview(String title) { + super(title); + t = new MailTable("us"); + } - private class MailTable implements Outputable { - private String user; + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + final User us = LoginPage.getUser(req); + Language lang = Page.getLanguage(req); + HashMap vars = new HashMap<>(); + vars.put("mailData", t); + vars.put("us", us); + vars.put("addForm", new MailAddForm(req, us)); + vars.put("manForm", new MailManagementForm(req, us)); + getDefaultTemplate().output(resp.getWriter(), lang, vars); + } - public MailTable(String user) { - this.user = user; - } + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { + PrintWriter out = resp.getWriter(); + if (req.getParameter("addmail") != null) { + MailAddForm f = Form.getForm(req, MailAddForm.class); + if (f.submit(out, req)) { + resp.sendRedirect(MailOverview.DEFAULT_PATH); + } + } else if (req.getParameter("makedefault") != null || req.getParameter("delete") != null) { + MailManagementForm f = Form.getForm(req, MailManagementForm.class); + if (f.submit(out, req)) { + resp.sendRedirect(MailOverview.DEFAULT_PATH); + } + } + super.doPost(req, resp); + } - @Override - public void output(PrintWriter out, Language l, Map vars) { - User us = (User) vars.get(user); - String usM = us.getEmail(); - EmailAddress[] emails = us.getEmails(); + private class MailTable implements Outputable { - for (int i = 0; i < emails.length; i++) { - out.println(""); - out.println(""); - out.println(""); - if (emails[i].isVerified()) { - out.print(l.getTranslation("Verified")); - } else { - out.print(l.getTranslation("Unverified")); - } - out.print(""); - out.println(""); - String address = emails[i].getAddress(); - if (usM.equals(address)) { - out.print(l.getTranslation("N/A")); - } else { - out.print(""); - } - out.print(""); - out.println(""); - out.print(address); - out.print(""); - out.println(""); - } - } - } + private String user; + + public MailTable(String user) { + this.user = user; + } + + @Override + public void output(PrintWriter out, Language l, Map vars) { + User us = (User) vars.get(user); + String usM = us.getEmail(); + EmailAddress[] emails = us.getEmails(); + + for (int i = 0; i < emails.length; i++) { + out.println(""); + out.println(""); + out.println(""); + if (emails[i].isVerified()) { + out.print(l.getTranslation("Verified")); + } else { + out.print(l.getTranslation("Unverified")); + } + out.print(""); + out.println(""); + String address = emails[i].getAddress(); + if (usM.equals(address)) { + out.print(l.getTranslation("N/A")); + } else { + out.print(""); + } + out.print(""); + out.println(""); + out.print(address); + out.print(""); + out.println(""); + } + } + } } diff --git a/src/org/cacert/gigi/pages/account/MyDetails.java b/src/org/cacert/gigi/pages/account/MyDetails.java index 753bdb2b..abb88d69 100644 --- a/src/org/cacert/gigi/pages/account/MyDetails.java +++ b/src/org/cacert/gigi/pages/account/MyDetails.java @@ -16,26 +16,26 @@ import org.cacert.gigi.util.HTMLEncoder; public class MyDetails extends Page { - public MyDetails() { - super("My Details"); - } - - public static final String PATH = "/account/details"; - - @Override - 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("lname", HTMLEncoder.encodeHTML(u.getLname())); - map.put("suffix", u.getSuffix() == null ? "" : HTMLEncoder.encodeHTML(u.getSuffix())); - DateSelector ds = new DateSelector("day", "month", "year"); - map.put("DoB", ds); - map.put("details", ""); - getDefaultTemplate().output(out, getLanguage(req), map); - - } + public MyDetails() { + super("My Details"); + } + + public static final String PATH = "/account/details"; + + @Override + 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("lname", HTMLEncoder.encodeHTML(u.getLname())); + map.put("suffix", u.getSuffix() == null ? "" : HTMLEncoder.encodeHTML(u.getSuffix())); + DateSelector ds = new DateSelector("day", "month", "year"); + map.put("DoB", ds); + map.put("details", ""); + getDefaultTemplate().output(out, getLanguage(req), map); + + } } diff --git a/src/org/cacert/gigi/pages/error/PageNotFound.java b/src/org/cacert/gigi/pages/error/PageNotFound.java index 179908c1..0d53524f 100644 --- a/src/org/cacert/gigi/pages/error/PageNotFound.java +++ b/src/org/cacert/gigi/pages/error/PageNotFound.java @@ -9,18 +9,18 @@ import org.cacert.gigi.pages.Page; public class PageNotFound extends Page { - public PageNotFound() { - super(""); - } - - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - getDefaultTemplate().output(resp.getWriter(), Page.getLanguage(req), null); - } - - @Override - public boolean needsLogin() { - return false; - } + public PageNotFound() { + super(""); + } + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + getDefaultTemplate().output(resp.getWriter(), Page.getLanguage(req), null); + } + + @Override + public boolean needsLogin() { + return false; + } } diff --git a/src/org/cacert/gigi/pages/main/RegisterPage.java b/src/org/cacert/gigi/pages/main/RegisterPage.java index e243c287..e2e2a493 100644 --- a/src/org/cacert/gigi/pages/main/RegisterPage.java +++ b/src/org/cacert/gigi/pages/main/RegisterPage.java @@ -13,47 +13,44 @@ import org.cacert.gigi.pages.Page; public class RegisterPage extends Page { - private static final String SIGNUP_PROCESS = "signupProcess"; - public static final String PATH = "/register"; - - public RegisterPage() { - super("Register"); - } - - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - Signup s = new Signup(req); - outputGet(req, resp, s); - } - - private void outputGet(HttpServletRequest req, HttpServletResponse resp, Signup s) throws IOException { - PrintWriter out = resp.getWriter(); - HashMap vars = new HashMap(); - getDefaultTemplate().output(out, getLanguage(req), vars); - s.output(out, getLanguage(req), vars); - } - - @Override - public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { - Signup s = Form.getForm(req, Signup.class); - if (s == null) { - resp.getWriter().println(translate(req, "CSRF token check failed.")); - } else 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!")); - return; - } - - outputGet(req, resp, s); - } - - @Override - public boolean needsLogin() { - return false; - } + private static final String SIGNUP_PROCESS = "signupProcess"; + + public static final String PATH = "/register"; + + public RegisterPage() { + super("Register"); + } + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + Signup s = new Signup(req); + outputGet(req, resp, s); + } + + private void outputGet(HttpServletRequest req, HttpServletResponse resp, Signup s) throws IOException { + PrintWriter out = resp.getWriter(); + HashMap vars = new HashMap(); + getDefaultTemplate().output(out, getLanguage(req), vars); + s.output(out, getLanguage(req), vars); + } + + @Override + public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { + Signup s = Form.getForm(req, Signup.class); + if (s == null) { + resp.getWriter().println(translate(req, "CSRF token check failed.")); + } else 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!")); + return; + } + + outputGet(req, resp, s); + } + + @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 1847d9c2..f2ed2ff5 100644 --- a/src/org/cacert/gigi/pages/main/Signup.java +++ b/src/org/cacert/gigi/pages/main/Signup.java @@ -25,198 +25,191 @@ import org.cacert.gigi.util.Notary; import org.cacert.gigi.util.PasswordStrengthChecker; public class Signup extends Form { - User buildup = new User(); - Template t; - boolean general = true, country = true, regional = true, radius = true; - - public Signup(HttpServletRequest hsr) { - super(hsr); - t = new Template(Signup.class.getResource("Signup.templ")); - buildup.setFname(""); - buildup.setMname(""); - buildup.setLname(""); - buildup.setSuffix(""); - buildup.setEmail(""); - buildup.setDob(new Date(0)); - } - - DateSelector myDoB = new DateSelector("day", "month", "year"); - - @Override - 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())); - vars.put("lname", HTMLEncoder.encodeHTML(buildup.getLname())); - vars.put("suffix", HTMLEncoder.encodeHTML(buildup.getSuffix())); - vars.put("dob", myDoB); - vars.put("email", HTMLEncoder.encodeHTML(buildup.getEmail())); - vars.put("general", general ? " checked=\"checked\"" : ""); - 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("csrf", getCSRFToken()); - t.output(out, l, vars); - } - - private void update(HttpServletRequest r) { - if (r.getParameter("fname") != null) { - buildup.setFname(r.getParameter("fname")); - } - if (r.getParameter("lname") != null) { - buildup.setLname(r.getParameter("lname")); - } - if (r.getParameter("mname") != null) { - buildup.setMname(r.getParameter("mname")); - } - if (r.getParameter("suffix") != null) { - buildup.setSuffix(r.getParameter("suffix")); - } - if (r.getParameter("email") != null) { - buildup.setEmail(r.getParameter("email")); - } - general = "1".equals(r.getParameter("general")); - country = "1".equals(r.getParameter("country")); - regional = "1".equals(r.getParameter("regional")); - radius = "1".equals(r.getParameter("radius")); - myDoB.update(r); - } - - @Override - public synchronized boolean submit(PrintWriter out, HttpServletRequest req) { - update(req); - boolean failed = false; - out.println("
    "); - if (buildup.getFname().equals("") || buildup.getLname().equals("")) { - outputError(out, req, "First and/or last names were blank."); - failed = true; - } - if (!myDoB.isValid()) { - outputError(out, req, "Invalid date of birth"); - failed = true; - } - if (!"1".equals(req.getParameter("cca_agree"))) { - outputError(out, req, "You have to agree to the CAcert Community agreement."); - failed = true; - } - if (buildup.getEmail().equals("")) { - outputError(out, req, "Email Address was blank"); - failed = true; - } - String pw1 = req.getParameter("pword1"); - String pw2 = req.getParameter("pword2"); - if (pw1 == null || pw1.equals("")) { - outputError(out, req, "Pass Phrases were blank"); - failed = true; - } else if (!pw1.equals(pw2)) { - outputError(out, req, "Pass Phrases don't match"); - failed = true; - } - 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."); - failed = true; - } - if (failed) { - out.println("
    "); - return false; - } - try { - PreparedStatement q1 = DatabaseConnection.getInstance().prepare( - "select * from `email` where `email`=? and `deleted`=0"); - PreparedStatement q2 = DatabaseConnection.getInstance().prepare( - "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."); - failed = true; - } - r1.close(); - r2.close(); - PreparedStatement q3 = DatabaseConnection.getInstance().prepare( - "select `domain` from `baddomains` where `domain`=RIGHT(?, LENGTH(`domain`))"); - q3.setString(1, buildup.getEmail()); - - ResultSet r3 = q3.executeQuery(); - if (r3.next()) { - 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)); - out.println("
    "); - failed = true; - } - r3.close(); - } catch (SQLException e) { - e.printStackTrace(); - failed = true; - } - String mailResult = EmailProvider.FAIL; - try { - 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."); - } 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"); - } - if (mailResult.equals(EmailProvider.FAIL)) { - outputError(out, req, "Failed to make a connection to the mail server"); - } else { - out.print("
    "); - out.print(mailResult); - out.println("
    "); - } - failed = true; - } - - out.println(""); - if (failed) { - return false; - } - try { - run(req, pw1); - } catch (SQLException e) { - e.printStackTrace(); - } - return true; - } - - private void run(HttpServletRequest req, String password) throws SQLException { - try { - DatabaseConnection.getInstance().beginTransaction(); - - buildup.setDob(myDoB.getDate()); - buildup.insert(password); - int memid = buildup.getId(); - EmailAddress ea = new EmailAddress(buildup.getEmail(), buildup); - ea.insert(Page.getLanguage(req)); - - PreparedStatement 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); - - DatabaseConnection.getInstance().commitTransaction(); - } finally { - DatabaseConnection.getInstance().quitTransaction(); - } - - } + + User buildup = new User(); + + Template t; + + boolean general = true, country = true, regional = true, radius = true; + + public Signup(HttpServletRequest hsr) { + super(hsr); + t = new Template(Signup.class.getResource("Signup.templ")); + buildup.setFname(""); + buildup.setMname(""); + buildup.setLname(""); + buildup.setSuffix(""); + buildup.setEmail(""); + buildup.setDob(new Date(0)); + } + + DateSelector myDoB = new DateSelector("day", "month", "year"); + + @Override + 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())); + vars.put("lname", HTMLEncoder.encodeHTML(buildup.getLname())); + vars.put("suffix", HTMLEncoder.encodeHTML(buildup.getSuffix())); + vars.put("dob", myDoB); + vars.put("email", HTMLEncoder.encodeHTML(buildup.getEmail())); + vars.put("general", general ? " checked=\"checked\"" : ""); + 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("csrf", getCSRFToken()); + t.output(out, l, vars); + } + + private void update(HttpServletRequest r) { + if (r.getParameter("fname") != null) { + buildup.setFname(r.getParameter("fname")); + } + if (r.getParameter("lname") != null) { + buildup.setLname(r.getParameter("lname")); + } + if (r.getParameter("mname") != null) { + buildup.setMname(r.getParameter("mname")); + } + if (r.getParameter("suffix") != null) { + buildup.setSuffix(r.getParameter("suffix")); + } + if (r.getParameter("email") != null) { + buildup.setEmail(r.getParameter("email")); + } + general = "1".equals(r.getParameter("general")); + country = "1".equals(r.getParameter("country")); + regional = "1".equals(r.getParameter("regional")); + radius = "1".equals(r.getParameter("radius")); + myDoB.update(r); + } + + @Override + public synchronized boolean submit(PrintWriter out, HttpServletRequest req) { + update(req); + boolean failed = false; + out.println("
    "); + if (buildup.getFname().equals("") || buildup.getLname().equals("")) { + outputError(out, req, "First and/or last names were blank."); + failed = true; + } + if ( !myDoB.isValid()) { + outputError(out, req, "Invalid date of birth"); + failed = true; + } + if ( !"1".equals(req.getParameter("cca_agree"))) { + outputError(out, req, "You have to agree to the CAcert Community agreement."); + failed = true; + } + if (buildup.getEmail().equals("")) { + outputError(out, req, "Email Address was blank"); + failed = true; + } + String pw1 = req.getParameter("pword1"); + String pw2 = req.getParameter("pword2"); + if (pw1 == null || pw1.equals("")) { + outputError(out, req, "Pass Phrases were blank"); + failed = true; + } else if ( !pw1.equals(pw2)) { + outputError(out, req, "Pass Phrases don't match"); + failed = true; + } + 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."); + failed = true; + } + if (failed) { + out.println("
    "); + return false; + } + try { + PreparedStatement q1 = DatabaseConnection.getInstance().prepare("select * from `email` where `email`=? and `deleted`=0"); + PreparedStatement q2 = DatabaseConnection.getInstance().prepare("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."); + failed = true; + } + r1.close(); + r2.close(); + PreparedStatement q3 = DatabaseConnection.getInstance().prepare("select `domain` from `baddomains` where `domain`=RIGHT(?, LENGTH(`domain`))"); + q3.setString(1, buildup.getEmail()); + + ResultSet r3 = q3.executeQuery(); + if (r3.next()) { + 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)); + out.println("
    "); + failed = true; + } + r3.close(); + } catch (SQLException e) { + e.printStackTrace(); + failed = true; + } + String mailResult = EmailProvider.FAIL; + try { + 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."); + } 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"); + } + if (mailResult.equals(EmailProvider.FAIL)) { + outputError(out, req, "Failed to make a connection to the mail server"); + } else { + out.print("
    "); + out.print(mailResult); + out.println("
    "); + } + failed = true; + } + + out.println(""); + if (failed) { + return false; + } + try { + run(req, pw1); + } catch (SQLException e) { + e.printStackTrace(); + } + return true; + } + + private void run(HttpServletRequest req, String password) throws SQLException { + try { + DatabaseConnection.getInstance().beginTransaction(); + + buildup.setDob(myDoB.getDate()); + buildup.insert(password); + int memid = buildup.getId(); + EmailAddress ea = new EmailAddress(buildup.getEmail(), buildup); + ea.insert(Page.getLanguage(req)); + + PreparedStatement 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); + + DatabaseConnection.getInstance().commitTransaction(); + } finally { + DatabaseConnection.getInstance().quitTransaction(); + } + + } } diff --git a/src/org/cacert/gigi/pages/wot/AssuranceForm.java b/src/org/cacert/gigi/pages/wot/AssuranceForm.java index e1c36886..97dac246 100644 --- a/src/org/cacert/gigi/pages/wot/AssuranceForm.java +++ b/src/org/cacert/gigi/pages/wot/AssuranceForm.java @@ -19,92 +19,91 @@ import org.cacert.gigi.util.Notary; import org.cacert.gigi.util.Notary.AssuranceResult; public class AssuranceForm extends Form { - User assuree; - static final Template templ; - static { - templ = new Template(AssuranceForm.class.getResource("AssuranceForm.templ")); - } - public AssuranceForm(HttpServletRequest hsr, int assuree) { - super(hsr); - this.assuree = new User(assuree); - } + User assuree; - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + static final Template templ; + static { + templ = new Template(AssuranceForm.class.getResource("AssuranceForm.templ")); + } - @Override - public void outputContent(PrintWriter out, Language l, Map vars) { - HashMap res = new HashMap(); - res.putAll(vars); - res.put("name", assuree.getName()); - try { - res.put("maxpoints", assuree.getMaxAssurePoints()); - } catch (SQLException e) { - e.printStackTrace(); - } - res.put("dob", sdf.format(assuree.getDob())); - templ.output(out, l, res); - } + public AssuranceForm(HttpServletRequest hsr, int assuree) { + super(hsr); + this.assuree = new User(assuree); + } - @Override - public boolean submit(PrintWriter out, HttpServletRequest req) { - out.println("
    "); - boolean failed = false; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - 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"); - failed = true; + @Override + public void outputContent(PrintWriter out, Language l, Map vars) { + HashMap res = new HashMap(); + res.putAll(vars); + res.put("name", assuree.getName()); + try { + res.put("maxpoints", assuree.getMaxAssurePoints()); + } catch (SQLException e) { + e.printStackTrace(); + } + res.put("dob", sdf.format(assuree.getDob())); + templ.output(out, l, res); + } - } - 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."); - failed = true; - } - } catch (ParseException e) { - 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."); - 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."); - failed = true; - } - // TODO checkPoints - String points = req.getParameter("points"); - if (points == null || "".equals(points)) { - // TODO message - failed = true; - } - if (failed) { - out.println("
    "); - return false; - } - try { - 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()); - } - out.println(""); - return success == AssuranceResult.ASSURANCE_SUCCEDED; - } catch (SQLException e) { - e.printStackTrace(); - } + @Override + public boolean submit(PrintWriter out, HttpServletRequest req) { + out.println("
    "); + boolean failed = false; - out.println("
    "); - return false; - } + 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"); + failed = true; + + } + 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."); + failed = true; + } + } catch (ParseException e) { + 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."); + 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."); + failed = true; + } + // TODO checkPoints + String points = req.getParameter("points"); + if (points == null || "".equals(points)) { + // TODO message + failed = true; + } + if (failed) { + out.println(""); + return false; + } + try { + 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()); + } + out.println(""); + return success == AssuranceResult.ASSURANCE_SUCCEDED; + } catch (SQLException e) { + e.printStackTrace(); + } + + out.println(""); + return false; + } } diff --git a/src/org/cacert/gigi/pages/wot/AssurePage.java b/src/org/cacert/gigi/pages/wot/AssurePage.java index 464afd97..1dae379c 100644 --- a/src/org/cacert/gigi/pages/wot/AssurePage.java +++ b/src/org/cacert/gigi/pages/wot/AssurePage.java @@ -21,111 +21,112 @@ import org.cacert.gigi.util.Notary; import org.cacert.gigi.util.Notary.AssuranceResult; public class AssurePage extends Page { - public static final String PATH = "/wot/assure"; - DateSelector ds = new DateSelector("day", "month", "year"); - Template t; - - public AssurePage() { - super("Assure someone"); - t = new Template(AssuranceForm.class.getResource("AssureeSearch.templ")); - - } - - @Override - public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { - - PrintWriter out = resp.getWriter(); - String pi = req.getPathInfo().substring(PATH.length()); - if (pi.length() > 1) { - int mid = Integer.parseInt(pi.substring(1)); - AssuranceForm form = new AssuranceForm(req, mid); - outputForm(req, out, mid, form); - - } else { - HashMap vars = new HashMap(); - vars.put("DoB", ds); - t.output(out, getLanguage(req), vars); - } - } - - private void outputForm(HttpServletRequest req, PrintWriter out, int mid, AssuranceForm form) { - User myself = LoginPage.getUser(req); - AssuranceResult check = Notary.checkAssuranceIsPossible(myself, new User(mid)); - if (check != AssuranceResult.ASSURANCE_SUCCEDED) { - out.println(translate(req, check.getMessage())); - return; - } - if (form == null || form.assuree.getId() != mid) { - form = new AssuranceForm(req, mid); - } - - form.output(out, getLanguage(req), new HashMap()); - } - - @Override - public void doPost(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)); - if (mid == myself.getId()) { - out.println(translate(req, "Cannot assure myself.")); - return; - } - - AssuranceForm form = Form.getForm(req, AssuranceForm.class); - if (mid != form.assuree.getId()) { - return; - } - if (form.submit(out, req)) { - out.println(translate(req, "Assurance complete.")); - } else { - outputForm(req, resp.getWriter(), mid, form); - } - - return; - } - - ResultSet rs = null; - try { - 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"); - ps.setString(2, day); - rs = ps.executeQuery(); - int id = 0; - if (rs.next()) { - id = rs.getInt(1); - int verified = rs.getInt(2); - if (rs.next()) { - 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!")); - } - 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.print("
    "); - } - - rs.close(); - } catch (SQLException e) { - e.printStackTrace(); - } finally { - try { - if (rs != null) { - rs.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - } + + public static final String PATH = "/wot/assure"; + + DateSelector ds = new DateSelector("day", "month", "year"); + + Template t; + + public AssurePage() { + super("Assure someone"); + t = new Template(AssuranceForm.class.getResource("AssureeSearch.templ")); + + } + + @Override + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { + + PrintWriter out = resp.getWriter(); + String pi = req.getPathInfo().substring(PATH.length()); + if (pi.length() > 1) { + int mid = Integer.parseInt(pi.substring(1)); + AssuranceForm form = new AssuranceForm(req, mid); + outputForm(req, out, mid, form); + + } else { + HashMap vars = new HashMap(); + vars.put("DoB", ds); + t.output(out, getLanguage(req), vars); + } + } + + private void outputForm(HttpServletRequest req, PrintWriter out, int mid, AssuranceForm form) { + User myself = LoginPage.getUser(req); + AssuranceResult check = Notary.checkAssuranceIsPossible(myself, new User(mid)); + if (check != AssuranceResult.ASSURANCE_SUCCEDED) { + out.println(translate(req, check.getMessage())); + return; + } + if (form == null || form.assuree.getId() != mid) { + form = new AssuranceForm(req, mid); + } + + form.output(out, getLanguage(req), new HashMap()); + } + + @Override + public void doPost(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)); + if (mid == myself.getId()) { + out.println(translate(req, "Cannot assure myself.")); + return; + } + + AssuranceForm form = Form.getForm(req, AssuranceForm.class); + if (mid != form.assuree.getId()) { + return; + } + if (form.submit(out, req)) { + out.println(translate(req, "Assurance complete.")); + } else { + outputForm(req, resp.getWriter(), mid, form); + } + + return; + } + + ResultSet rs = null; + try { + 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"); + ps.setString(2, day); + rs = ps.executeQuery(); + int id = 0; + if (rs.next()) { + id = rs.getInt(1); + int verified = rs.getInt(2); + if (rs.next()) { + 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!")); + } + 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.print("
    "); + } + + rs.close(); + } catch (SQLException e) { + e.printStackTrace(); + } finally { + try { + if (rs != null) { + rs.close(); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } + } } diff --git a/src/org/cacert/gigi/ping/DNSPinger.java b/src/org/cacert/gigi/ping/DNSPinger.java index 3b459389..ece3d1b9 100644 --- a/src/org/cacert/gigi/ping/DNSPinger.java +++ b/src/org/cacert/gigi/ping/DNSPinger.java @@ -8,57 +8,62 @@ import java.util.LinkedList; 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())); - String line; - LinkedList nameservers = new LinkedList(); - while ((line = br.readLine()) != null) { - nameservers.add(line); - } - p.destroy(); - 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 }; - System.out.println(Arrays.toString(call)); - p = Runtime.getRuntime().exec(call); - br = new BufferedReader(new InputStreamReader(p.getInputStream())); - String token = null; - boolean found = false; - while ((line = br.readLine()) != null) { - if (line.isEmpty()) { - continue; - } - found = true; - token = line.substring(1, line.length() - 1); - if (token.equals(expToken)) { - continue nameservers; - } - } - p.destroy(); - result.append(NS); - if (found) { - result.append(" DIFFER;"); - } else { - result.append(" EMPTY;"); - } - failed = true; + @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())); + String line; + LinkedList nameservers = new LinkedList(); + while ((line = br.readLine()) != null) { + nameservers.add(line); + } + p.destroy(); + 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 + }; + System.out.println(Arrays.toString(call)); + p = Runtime.getRuntime().exec(call); + br = new BufferedReader(new InputStreamReader(p.getInputStream())); + String token = null; + boolean found = false; + while ((line = br.readLine()) != null) { + if (line.isEmpty()) { + continue; + } + found = true; + token = line.substring(1, line.length() - 1); + if (token.equals(expToken)) { + continue nameservers; + } + } + p.destroy(); + result.append(NS); + if (found) { + result.append(" DIFFER;"); + } else { + result.append(" EMPTY;"); + } + failed = true; - } - if (!failed) { - // Success - return; - } - System.out.println(result.toString()); - } catch (IOException e) { - e.printStackTrace(); - // FAIL - } - // FAIL - } + } + if ( !failed) { + // Success + return; + } + System.out.println(result.toString()); + } catch (IOException e) { + e.printStackTrace(); + // FAIL + } + // FAIL + } } diff --git a/src/org/cacert/gigi/ping/DomainPinger.java b/src/org/cacert/gigi/ping/DomainPinger.java index 8be4c2bf..c9c1584d 100644 --- a/src/org/cacert/gigi/ping/DomainPinger.java +++ b/src/org/cacert/gigi/ping/DomainPinger.java @@ -1,5 +1,6 @@ package org.cacert.gigi.ping; public abstract class DomainPinger { - public abstract void ping(String domain, String configuration, String token); + + public abstract void ping(String domain, String configuration, String token); } diff --git a/src/org/cacert/gigi/ping/HTTPFetch.java b/src/org/cacert/gigi/ping/HTTPFetch.java index b4e88ea4..de4990fc 100644 --- a/src/org/cacert/gigi/ping/HTTPFetch.java +++ b/src/org/cacert/gigi/ping/HTTPFetch.java @@ -7,23 +7,23 @@ import java.net.URL; public class HTTPFetch extends DomainPinger { - @Override - 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")); - String line = br.readLine(); - if (line == null) { - // empty - return; - } - if (line.equals(expToken)) { - // found - } - // differ - } catch (IOException e) { - e.printStackTrace(); - // error - } - } + @Override + 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")); + String line = br.readLine(); + if (line == null) { + // empty + return; + } + if (line.equals(expToken)) { + // found + } + // differ + } catch (IOException e) { + e.printStackTrace(); + // error + } + } } diff --git a/src/org/cacert/gigi/ping/SSLPinger.java b/src/org/cacert/gigi/ping/SSLPinger.java index 78adc12a..d6ebe71c 100644 --- a/src/org/cacert/gigi/ping/SSLPinger.java +++ b/src/org/cacert/gigi/ping/SSLPinger.java @@ -22,173 +22,171 @@ import javax.security.cert.X509Certificate; public class SSLPinger extends DomainPinger { - @Override - public void ping(String domain, String configuration, String expToken) { - try { - SocketChannel sch = SocketChannel.open(); - String[] parts = configuration.split(":", 2); - 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; + @Override + public void ping(String domain, String configuration, String expToken) { + try { + SocketChannel sch = SocketChannel.open(); + String[] parts = configuration.split(":", 2); + 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; - } - } - test(sch, domain); - } catch (IOException e) { - e.printStackTrace(); - } + } + } + test(sch, domain); + } catch (IOException e) { + e.printStackTrace(); + } - } + } - private void startIMAP(SocketChannel sch) throws IOException { - Socket s = sch.socket(); - InputStream is = s.getInputStream(); - OutputStream os = s.getOutputStream(); - scanFor(is, "\n"); - os.write("ENABLE STARTTLS\r\n".getBytes()); - os.flush(); - scanFor(is, "\n"); - } + private void startIMAP(SocketChannel sch) throws IOException { + Socket s = sch.socket(); + InputStream is = s.getInputStream(); + OutputStream os = s.getOutputStream(); + scanFor(is, "\n"); + os.write("ENABLE STARTTLS\r\n".getBytes()); + os.flush(); + scanFor(is, "\n"); + } - 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.flush(); - os.write("".getBytes()); - os.flush(); - scanFor(is, ""); + 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.flush(); + os.write("".getBytes()); + os.flush(); + scanFor(is, ""); - } + } - private void scanFor(InputStream is, String scanFor) throws IOException { - int pos = 0; - while (pos < scanFor.length()) { - if (is.read() == scanFor.charAt(pos)) { - pos++; - } else { - pos = 0; - } - } - } + private void scanFor(InputStream is, String scanFor) throws IOException { + int pos = 0; + while (pos < scanFor.length()) { + if (is.read() == scanFor.charAt(pos)) { + pos++; + } else { + pos = 0; + } + } + } - private void startSMTP(SocketChannel sch) throws IOException { - Socket s = sch.socket(); - InputStream is = s.getInputStream(); - readSMTP(is); - s.getOutputStream().write("EHLO ssl.pinger\r\n".getBytes()); - s.getOutputStream().flush(); - readSMTP(is); - s.getOutputStream().write("HELP\r\n".getBytes()); - s.getOutputStream().flush(); - readSMTP(is); - s.getOutputStream().write("STARTTLS\r\n".getBytes()); - s.getOutputStream().flush(); - readSMTP(is); - } + private void startSMTP(SocketChannel sch) throws IOException { + Socket s = sch.socket(); + InputStream is = s.getInputStream(); + readSMTP(is); + s.getOutputStream().write("EHLO ssl.pinger\r\n".getBytes()); + s.getOutputStream().flush(); + readSMTP(is); + s.getOutputStream().write("HELP\r\n".getBytes()); + s.getOutputStream().flush(); + readSMTP(is); + s.getOutputStream().write("STARTTLS\r\n".getBytes()); + s.getOutputStream().flush(); + readSMTP(is); + } - private void readSMTP(InputStream is) throws IOException { - int counter = 0; - boolean finish = true; - while (true) { - char c = (char) is.read(); - if (counter == 3) { - if (c == ' ') { - finish = true; - } else if (c == '-') { - finish = false; - } else { - throw new Error("Invalid smtp: " + c); - } - } - if (c == '\n') { - if (finish) { - return; - } - counter = 0; - } else { - counter++; - } - } - } + private void readSMTP(InputStream is) throws IOException { + int counter = 0; + boolean finish = true; + while (true) { + char c = (char) is.read(); + if (counter == 3) { + if (c == ' ') { + finish = true; + } else if (c == '-') { + finish = false; + } else { + throw new Error("Invalid smtp: " + c); + } + } + if (c == '\n') { + if (finish) { + return; + } + counter = 0; + } else { + counter++; + } + } + } - 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()); - se.setUseClientMode(true); - SSLParameters sp = se.getSSLParameters(); - 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) { - 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(); - enc_in.flip(); - break; - case NEED_TASK: - se.getDelegatedTask().run(); - break; - case NOT_HANDSHAKING: - case FINISHED: + 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()); + se.setUseClientMode(true); + SSLParameters sp = se.getSSLParameters(); + 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) { + 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(); + 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(); - for (X509Certificate x509Certificate : peerCertificateChain) { - System.out.println(x509Certificate.getSubjectDN().getName()); - } - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } catch (SSLException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } + } + System.out.println("completed"); + System.out.println(se.getSession().getCipherSuite()); + X509Certificate[] peerCertificateChain = se.getSession().getPeerCertificateChain(); + for (X509Certificate x509Certificate : peerCertificateChain) { + System.out.println(x509Certificate.getSubjectDN().getName()); + } + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (SSLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } } diff --git a/src/org/cacert/gigi/util/CipherInfo.java b/src/org/cacert/gigi/util/CipherInfo.java index 4c20710a..2508fae7 100644 --- a/src/org/cacert/gigi/util/CipherInfo.java +++ b/src/org/cacert/gigi/util/CipherInfo.java @@ -10,281 +10,298 @@ import java.util.TreeSet; import sun.security.ssl.SSLContextImpl; public class CipherInfo implements Comparable { - private static class CipherInfoGenerator { - private Class cipherSuite; - private Field cipherSuiteNameMap; - private Field exchange; - private Field cipher; - private Field keySize; - private Field algortihm; - private Field transformation; - private HashMap names; - private Field macAlg; - private Field macName; - private Field macSize; - - public CipherInfoGenerator() throws ReflectiveOperationException { - SSLContextImpl sc = new SSLContextImpl.TLS12Context(); - Method m = SSLContextImpl.class.getDeclaredMethod("getSupportedCipherSuiteList"); - m.setAccessible(true); - Object o = m.invoke(sc); - Class cipherSuiteList = o.getClass(); - Method collection = cipherSuiteList.getDeclaredMethod("collection"); - collection.setAccessible(true); - Collection suites = (Collection) collection.invoke(o); - Object oneSuite = suites.iterator().next(); - cipherSuite = oneSuite.getClass(); - cipherSuiteNameMap = cipherSuite.getDeclaredField("nameMap"); - cipherSuiteNameMap.setAccessible(true); - names = (HashMap) cipherSuiteNameMap.get(null); - exchange = cipherSuite.getDeclaredField("keyExchange"); - exchange.setAccessible(true); - cipher = cipherSuite.getDeclaredField("cipher"); - cipher.setAccessible(true); - Class bulkCipher = cipher.getType(); - keySize = bulkCipher.getDeclaredField("keySize"); - keySize.setAccessible(true); - algortihm = bulkCipher.getDeclaredField("algorithm"); - algortihm.setAccessible(true); - transformation = bulkCipher.getDeclaredField("transformation"); - transformation.setAccessible(true); - - macAlg = cipherSuite.getDeclaredField("macAlg"); - macAlg.setAccessible(true); - Class mac = macAlg.getType(); - macName = mac.getDeclaredField("name"); - macName.setAccessible(true); - macSize = mac.getDeclaredField("size"); - macSize.setAccessible(true); - } - - public CipherInfo generateInfo(String suiteName) throws IllegalArgumentException, IllegalAccessException { - Object suite = names.get(suiteName); - String keyExchange = exchange.get(suite).toString(); - Object bulkCipher = cipher.get(suite); - Object mac = macAlg.get(suite); - - String transform = (String) transformation.get(bulkCipher); - String[] transformationParts = transform.split("/"); - int keysize = keySize.getInt(bulkCipher); - - String macNam = (String) macName.get(mac); - int macSiz = macSize.getInt(mac); - - String chaining = null; - String padding = null; - if (transformationParts.length > 1) { - chaining = transformationParts[1]; - padding = transformationParts[2]; - } - - return new CipherInfo(suiteName, keyExchange, transformationParts[0], keysize * 8, chaining, padding, - macNam, macSiz * 8); - - } - } - - String keyExchange; - String cipher; - int keySize; - String cipherChaining; - String cipherPadding; - String macName; - int macSize; - String suiteName; - - 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; - this.keySize = keySize; - this.cipherChaining = cipherChaining; - this.cipherPadding = cipherPadding; - this.macName = macName; - this.macSize = macSize; - } - - static CipherInfoGenerator cig; - static { - try { - cig = new CipherInfoGenerator(); - } catch (ReflectiveOperationException e) { - e.printStackTrace(); - } - } - - public static CipherInfo generateInfo(String name) { - if (cig == null) { - return null; - } - try { - return cig.generateInfo(name); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - return null; - } - - public String getSuiteName() { - return suiteName; - } - - /** - * 5: ECDHE, AES||CAMELLIA, keysize >=256
    - * 4: DHE, AES||CAMELLIA, keysize >= 256
    - * 3: ECDHE|| DHE, AES||CAMELLIA
    - * 2: ECDHE||DHE
    - * 1: RSA||DSA
    - * 0: Others - * - * @return the strength - */ - public int getStrength() { - if (cipher.equals("NULL") || cipher.equals("RC4") || cipher.contains("DES")) { - return 0; - } - boolean ecdhe = keyExchange.startsWith("ECDHE"); - boolean dhe = keyExchange.startsWith("DHE"); - boolean pfs = ecdhe || dhe; - boolean goodCipher = cipher.equals("AES") || cipher.equals("CAMELLIA"); - if (ecdhe && goodCipher && keySize >= 256) { - return 5; - } - if (dhe && goodCipher && keySize >= 256) { - return 4; - } - if (pfs && goodCipher) { - return 3; - } - if (pfs) { - return 2; - } - if (keyExchange.equals("RSA") || keyExchange.equals("DSA")) { - return 1; - } - return 0; - } - - 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 + "]"; - } - - /** - * ECDHE
    - * GCM
    - * Cipher {@link #CIPHER_RANKING}
    - * Cipher {@link #keySize}
    - * HMAC
    - * HMAC size
    - * - * @return - */ - @Override - public int compareTo(CipherInfo o) { - int myStrength = getStrength(); - int oStrength = o.getStrength(); - if (myStrength > oStrength) { - return -1; - } - if (myStrength < oStrength) { - return 1; - } - // TODO sort SSL/TLS - boolean myEcdhe = keyExchange.startsWith("ECDHE"); - boolean oEcdhe = o.keyExchange.startsWith("ECDHE"); - if (myEcdhe && !oEcdhe) { - return -1; - } - if (!myEcdhe && oEcdhe) { - return 1; - } - boolean myGCM = "GCM".equals(cipherChaining); - boolean oGCM = "GCM".equals(o.cipherChaining); - if (myGCM && !oGCM) { - return -1; - } - if (!myGCM && oGCM) { - return 1; - } - if (!cipher.equals(o.cipher)) { - - for (String testCipher : CIPHER_RANKING) { - if (cipher.equals(testCipher)) { - return -1; - } - if (o.cipher.equals(testCipher)) { - return 1; - } - } - if (cipher.equals("NULL")) { - return 1; - } - if (o.cipher.equals("NULL")) { - return -1; - } - } - if (keySize > o.keySize) { - return -1; - } - if (keySize < o.keySize) { - return 1; - } - boolean mySHA = macName.startsWith("SHA"); - boolean oSHA = o.macName.startsWith("SHA"); - if (mySHA && !oSHA) { - return -1; - } - if (mySHA && !oSHA) { - return 1; - } - if (macSize > o.macSize) { - return -1; - } - if (macSize < o.macSize) { - return 1; - } - - return suiteName.compareTo(o.suiteName); - } - - static String[] cipherRanking = null; - - public static String[] getCompleteRanking() { - if (cipherRanking == null) { - 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) { - String s = o; - CipherInfo info = CipherInfo.generateInfo(s); - if (info != null) { - if (info.getStrength() > 1) { - chosenCiphers.add(info); - } - } - } - String[] ciphers = new String[chosenCiphers.size()]; - int counter = 0; - for (CipherInfo i : chosenCiphers) { - ciphers[counter++] = i.getSuiteName(); - } - return ciphers; - } - - public static String[] filter(String[] supportedCipherSuites) { - return filterCiphers(Arrays.asList(supportedCipherSuites)); - } + + private static class CipherInfoGenerator { + + private Class cipherSuite; + + private Field cipherSuiteNameMap; + + private Field exchange; + + private Field cipher; + + private Field keySize; + + private Field algortihm; + + private Field transformation; + + private HashMap names; + + private Field macAlg; + + private Field macName; + + private Field macSize; + + public CipherInfoGenerator() throws ReflectiveOperationException { + SSLContextImpl sc = new SSLContextImpl.TLS12Context(); + Method m = SSLContextImpl.class.getDeclaredMethod("getSupportedCipherSuiteList"); + m.setAccessible(true); + Object o = m.invoke(sc); + Class cipherSuiteList = o.getClass(); + Method collection = cipherSuiteList.getDeclaredMethod("collection"); + collection.setAccessible(true); + Collection suites = (Collection) collection.invoke(o); + Object oneSuite = suites.iterator().next(); + cipherSuite = oneSuite.getClass(); + cipherSuiteNameMap = cipherSuite.getDeclaredField("nameMap"); + cipherSuiteNameMap.setAccessible(true); + names = (HashMap) cipherSuiteNameMap.get(null); + exchange = cipherSuite.getDeclaredField("keyExchange"); + exchange.setAccessible(true); + cipher = cipherSuite.getDeclaredField("cipher"); + cipher.setAccessible(true); + Class bulkCipher = cipher.getType(); + keySize = bulkCipher.getDeclaredField("keySize"); + keySize.setAccessible(true); + algortihm = bulkCipher.getDeclaredField("algorithm"); + algortihm.setAccessible(true); + transformation = bulkCipher.getDeclaredField("transformation"); + transformation.setAccessible(true); + + macAlg = cipherSuite.getDeclaredField("macAlg"); + macAlg.setAccessible(true); + Class mac = macAlg.getType(); + macName = mac.getDeclaredField("name"); + macName.setAccessible(true); + macSize = mac.getDeclaredField("size"); + macSize.setAccessible(true); + } + + public CipherInfo generateInfo(String suiteName) throws IllegalArgumentException, IllegalAccessException { + Object suite = names.get(suiteName); + String keyExchange = exchange.get(suite).toString(); + Object bulkCipher = cipher.get(suite); + Object mac = macAlg.get(suite); + + String transform = (String) transformation.get(bulkCipher); + String[] transformationParts = transform.split("/"); + int keysize = keySize.getInt(bulkCipher); + + String macNam = (String) macName.get(mac); + int macSiz = macSize.getInt(mac); + + String chaining = null; + String padding = null; + if (transformationParts.length > 1) { + chaining = transformationParts[1]; + padding = transformationParts[2]; + } + + return new CipherInfo(suiteName, keyExchange, transformationParts[0], keysize * 8, chaining, padding, macNam, macSiz * 8); + + } + } + + String keyExchange; + + String cipher; + + int keySize; + + String cipherChaining; + + String cipherPadding; + + String macName; + + int macSize; + + String suiteName; + + 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; + this.keySize = keySize; + this.cipherChaining = cipherChaining; + this.cipherPadding = cipherPadding; + this.macName = macName; + this.macSize = macSize; + } + + static CipherInfoGenerator cig; + static { + try { + cig = new CipherInfoGenerator(); + } catch (ReflectiveOperationException e) { + e.printStackTrace(); + } + } + + public static CipherInfo generateInfo(String name) { + if (cig == null) { + return null; + } + try { + return cig.generateInfo(name); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + return null; + } + + public String getSuiteName() { + return suiteName; + } + + /** + * 5: ECDHE, AES||CAMELLIA, keysize >=256
    + * 4: DHE, AES||CAMELLIA, keysize >= 256
    + * 3: ECDHE|| DHE, AES||CAMELLIA
    + * 2: ECDHE||DHE
    + * 1: RSA||DSA
    + * 0: Others + * + * @return the strength + */ + public int getStrength() { + if (cipher.equals("NULL") || cipher.equals("RC4") || cipher.contains("DES")) { + return 0; + } + boolean ecdhe = keyExchange.startsWith("ECDHE"); + boolean dhe = keyExchange.startsWith("DHE"); + boolean pfs = ecdhe || dhe; + boolean goodCipher = cipher.equals("AES") || cipher.equals("CAMELLIA"); + if (ecdhe && goodCipher && keySize >= 256) { + return 5; + } + if (dhe && goodCipher && keySize >= 256) { + return 4; + } + if (pfs && goodCipher) { + return 3; + } + if (pfs) { + return 2; + } + if (keyExchange.equals("RSA") || keyExchange.equals("DSA")) { + return 1; + } + return 0; + } + + 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 + "]"; + } + + /** + * ECDHE
    + * GCM
    + * Cipher {@link #CIPHER_RANKING}
    + * Cipher {@link #keySize}
    + * HMAC
    + * HMAC size
    + * + * @return + */ + @Override + public int compareTo(CipherInfo o) { + int myStrength = getStrength(); + int oStrength = o.getStrength(); + if (myStrength > oStrength) { + return -1; + } + if (myStrength < oStrength) { + return 1; + } + // TODO sort SSL/TLS + boolean myEcdhe = keyExchange.startsWith("ECDHE"); + boolean oEcdhe = o.keyExchange.startsWith("ECDHE"); + if (myEcdhe && !oEcdhe) { + return -1; + } + if ( !myEcdhe && oEcdhe) { + return 1; + } + boolean myGCM = "GCM".equals(cipherChaining); + boolean oGCM = "GCM".equals(o.cipherChaining); + if (myGCM && !oGCM) { + return -1; + } + if ( !myGCM && oGCM) { + return 1; + } + if ( !cipher.equals(o.cipher)) { + + for (String testCipher : CIPHER_RANKING) { + if (cipher.equals(testCipher)) { + return -1; + } + if (o.cipher.equals(testCipher)) { + return 1; + } + } + if (cipher.equals("NULL")) { + return 1; + } + if (o.cipher.equals("NULL")) { + return -1; + } + } + if (keySize > o.keySize) { + return -1; + } + if (keySize < o.keySize) { + return 1; + } + boolean mySHA = macName.startsWith("SHA"); + boolean oSHA = o.macName.startsWith("SHA"); + if (mySHA && !oSHA) { + return -1; + } + if (mySHA && !oSHA) { + return 1; + } + if (macSize > o.macSize) { + return -1; + } + if (macSize < o.macSize) { + return 1; + } + + return suiteName.compareTo(o.suiteName); + } + + static String[] cipherRanking = null; + + public static String[] getCompleteRanking() { + if (cipherRanking == null) { + 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) { + String s = o; + CipherInfo info = CipherInfo.generateInfo(s); + if (info != null) { + if (info.getStrength() > 1) { + chosenCiphers.add(info); + } + } + } + String[] ciphers = new String[chosenCiphers.size()]; + int counter = 0; + for (CipherInfo i : chosenCiphers) { + ciphers[counter++] = i.getSuiteName(); + } + return ciphers; + } + + public static String[] filter(String[] supportedCipherSuites) { + return filterCiphers(Arrays.asList(supportedCipherSuites)); + } } diff --git a/src/org/cacert/gigi/util/HTMLEncoder.java b/src/org/cacert/gigi/util/HTMLEncoder.java index 9303d8d9..ed943cbe 100644 --- a/src/org/cacert/gigi/util/HTMLEncoder.java +++ b/src/org/cacert/gigi/util/HTMLEncoder.java @@ -1,12 +1,13 @@ package org.cacert.gigi.util; public class HTMLEncoder { - public static String encodeHTML(String s) { - s = s.replace("&", "&"); - s = s.replace("<", "<"); - s = s.replace(">", ">"); - s = s.replace("\"", """); - s = s.replace("'", "'"); - return s; - } + + public static String encodeHTML(String s) { + s = s.replace("&", "&"); + s = s.replace("<", "<"); + s = s.replace(">", ">"); + s = s.replace("\"", """); + s = s.replace("'", "'"); + return s; + } } diff --git a/src/org/cacert/gigi/util/Job.java b/src/org/cacert/gigi/util/Job.java index 70c9d569..13e6c7e0 100644 --- a/src/org/cacert/gigi/util/Job.java +++ b/src/org/cacert/gigi/util/Job.java @@ -8,48 +8,49 @@ import org.cacert.gigi.Certificate; import org.cacert.gigi.database.DatabaseConnection; public class Job { - int id; - - private Job(int id) { - this.id = id; - } - - public static enum JobType { - SIGN("sign"), REVOKE("revoke"); - private final String name; - - private JobType(String name) { - this.name = name; - } - - public String getName() { - return name; - } - } - - public static Job submit(Certificate targetId, JobType type) throws SQLException { - PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `jobs` SET targetId=?, task=?"); - ps.setInt(1, targetId.getId()); - ps.setString(2, type.getName()); - ps.execute(); - return new Job(DatabaseConnection.lastInsertId(ps)); - } - - public boolean waitFor(int max) throws SQLException, InterruptedException { - long start = System.currentTimeMillis(); - PreparedStatement ps = DatabaseConnection.getInstance().prepare( - "SELECT 1 FROM `jobs` WHERE id=? AND state='open'"); - ps.setInt(1, id); - ResultSet rs = ps.executeQuery(); - while (rs.next()) { - rs.close(); - if (max != 0 && System.currentTimeMillis() - start > max) { - return false; - } - Thread.sleep((long) (2000 + Math.random() * 2000)); - rs = ps.executeQuery(); - } - rs.close(); - return true; - } + + int id; + + private Job(int id) { + this.id = id; + } + + public static enum JobType { + SIGN("sign"), REVOKE("revoke"); + + private final String name; + + private JobType(String name) { + this.name = name; + } + + public String getName() { + return name; + } + } + + public static Job submit(Certificate targetId, JobType type) throws SQLException { + PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `jobs` SET targetId=?, task=?"); + ps.setInt(1, targetId.getId()); + ps.setString(2, type.getName()); + ps.execute(); + return new Job(DatabaseConnection.lastInsertId(ps)); + } + + public boolean waitFor(int max) throws SQLException, InterruptedException { + long start = System.currentTimeMillis(); + PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `jobs` WHERE id=? AND state='open'"); + ps.setInt(1, id); + ResultSet rs = ps.executeQuery(); + while (rs.next()) { + rs.close(); + if (max != 0 && System.currentTimeMillis() - start > max) { + return false; + } + Thread.sleep((long) (2000 + Math.random() * 2000)); + rs = ps.executeQuery(); + } + rs.close(); + return true; + } } diff --git a/src/org/cacert/gigi/util/KeyStorage.java b/src/org/cacert/gigi/util/KeyStorage.java index 6bac57c0..9b3f11eb 100644 --- a/src/org/cacert/gigi/util/KeyStorage.java +++ b/src/org/cacert/gigi/util/KeyStorage.java @@ -3,18 +3,20 @@ package org.cacert.gigi.util; import java.io.File; public class KeyStorage { - private static final File csr = new File("keys/csr"); - private static final File crt = new File("keys/crt"); - public static File locateCrt(int id) { - File parent = new File(crt, (id / 1000) + ""); - parent.mkdirs(); - return new File(parent, id + ".crt"); - } + private static final File csr = new File("keys/csr"); - public static File locateCsr(int id) { - File parent = new File(csr, (id / 1000) + ""); - parent.mkdirs(); - return new File(parent, id + ".csr"); - } + private static final File crt = new File("keys/crt"); + + public static File locateCrt(int id) { + File parent = new File(crt, (id / 1000) + ""); + parent.mkdirs(); + return new File(parent, id + ".crt"); + } + + public static File locateCsr(int id) { + File parent = new File(csr, (id / 1000) + ""); + parent.mkdirs(); + return new File(parent, id + ".csr"); + } } diff --git a/src/org/cacert/gigi/util/Notary.java b/src/org/cacert/gigi/util/Notary.java index 7cd38e37..89fb5bc0 100644 --- a/src/org/cacert/gigi/util/Notary.java +++ b/src/org/cacert/gigi/util/Notary.java @@ -8,81 +8,75 @@ 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`=?"); - q.setInt(1, memid); - q.setInt(2, secmemid); - q.setString(3, document); - q.setInt(4, active ? 1 : 0); - q.setString(5, method); - q.setString(6, comment); - q.execute(); - } - 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"); - ps.setInt(1, target.getId()); - ps.setInt(2, assurer.getId()); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - rs.close(); - return AssuranceResult.ALREADY_ASSUREED; - } - rs.close(); - if (!assurer.canAssure()) { - return AssuranceResult.CANNOT_ASSURE; - } - } catch (SQLException e) { - e.printStackTrace(); - } - return AssuranceResult.ASSURANCE_SUCCEDED; - } + 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); + q.setInt(4, active ? 1 : 0); + q.setString(5, method); + q.setString(6, comment); + q.execute(); + } - 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."); - private final String message; + 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"); + ps.setInt(1, target.getId()); + ps.setInt(2, assurer.getId()); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + rs.close(); + return AssuranceResult.ALREADY_ASSUREED; + } + rs.close(); + if ( !assurer.canAssure()) { + return AssuranceResult.CANNOT_ASSURE; + } + } catch (SQLException e) { + e.printStackTrace(); + } + return AssuranceResult.ASSURANCE_SUCCEDED; + } - private AssuranceResult(String message) { - this.message = message; - } + 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."); - public String getMessage() { - return message; - } - } + private final String message; - 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; - } - User u = new User(target.getId()); - if (!u.equals(target)) { - return AssuranceResult.ASSUREE_CHANGED; - } - if (awarded > assurer.getMaxAssurePoints() || awarded < 0) { - return AssuranceResult.POINTS_OUT_OF_RANGE; - } + private AssuranceResult(String message) { + this.message = message; + } - 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); - ps.setString(4, location); - ps.setString(5, date); - ps.execute(); - return AssuranceResult.ASSURANCE_SUCCEDED; - } + public String getMessage() { + return message; + } + } + + 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; + } + User u = new User(target.getId()); + if ( !u.equals(target)) { + return AssuranceResult.ASSUREE_CHANGED; + } + if (awarded > assurer.getMaxAssurePoints() || awarded < 0) { + return AssuranceResult.POINTS_OUT_OF_RANGE; + } + + 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); + ps.setString(4, location); + ps.setString(5, date); + ps.execute(); + return AssuranceResult.ASSURANCE_SUCCEDED; + } } diff --git a/src/org/cacert/gigi/util/PasswordHash.java b/src/org/cacert/gigi/util/PasswordHash.java index 71f75479..aaff2268 100644 --- a/src/org/cacert/gigi/util/PasswordHash.java +++ b/src/org/cacert/gigi/util/PasswordHash.java @@ -4,34 +4,35 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class PasswordHash { - public static boolean verifyHash(String password, String hash) { - String newhash = sha1(password); - boolean match = true; - if (newhash.length() != hash.length()) { - match = false; - } - for (int i = 0; i < newhash.length(); i++) { - match &= newhash.charAt(i) == hash.charAt(i); - } - return match; - } - private static String sha1(String password) { - try { - MessageDigest md = MessageDigest.getInstance("SHA1"); - byte[] digest = md.digest(password.getBytes()); - StringBuffer res = new StringBuffer(digest.length * 2); - for (int i = 0; i < digest.length; i++) { - res.append(Integer.toHexString((digest[i] & 0xF0) >> 4)); - res.append(Integer.toHexString(digest[i] & 0xF)); - } - return res.toString(); - } catch (NoSuchAlgorithmException e) { - throw new Error(e); - } - } + public static boolean verifyHash(String password, String hash) { + String newhash = sha1(password); + boolean match = true; + if (newhash.length() != hash.length()) { + match = false; + } + for (int i = 0; i < newhash.length(); i++) { + match &= newhash.charAt(i) == hash.charAt(i); + } + return match; + } - public static String hash(String password) { - return sha1(password); - } + private static String sha1(String password) { + try { + MessageDigest md = MessageDigest.getInstance("SHA1"); + byte[] digest = md.digest(password.getBytes()); + StringBuffer res = new StringBuffer(digest.length * 2); + for (int i = 0; i < digest.length; i++) { + res.append(Integer.toHexString((digest[i] & 0xF0) >> 4)); + res.append(Integer.toHexString(digest[i] & 0xF)); + } + return res.toString(); + } catch (NoSuchAlgorithmException e) { + throw new Error(e); + } + } + + public static String hash(String password) { + return sha1(password); + } } diff --git a/src/org/cacert/gigi/util/PasswordStrengthChecker.java b/src/org/cacert/gigi/util/PasswordStrengthChecker.java index 3e4760bb..e52c1dd0 100644 --- a/src/org/cacert/gigi/util/PasswordStrengthChecker.java +++ b/src/org/cacert/gigi/util/PasswordStrengthChecker.java @@ -6,88 +6,91 @@ import org.cacert.gigi.GigiApiException; import org.cacert.gigi.User; public class PasswordStrengthChecker { - static Pattern digits = Pattern.compile("\\d"); - static Pattern lower = Pattern.compile("[a-z]"); - static Pattern upper = Pattern.compile("[A-Z]"); - static Pattern whitespace = Pattern.compile("\\s"); - static Pattern special = Pattern.compile("(?!\\s)\\W"); - private PasswordStrengthChecker() { - } + static Pattern digits = Pattern.compile("\\d"); - private static int checkpwlight(String pw) { - int points = 0; - if (pw.length() > 15) { - points++; - } - if (pw.length() > 20) { - points++; - } - if (pw.length() > 25) { - points++; - } - if (pw.length() > 30) { - points++; - } - if (digits.matcher(pw).find()) { - points++; - } - if (lower.matcher(pw).find()) { - points++; - } - if (upper.matcher(pw).find()) { - points++; - } - if (special.matcher(pw).find()) { - points++; - } - if (whitespace.matcher(pw).find()) { - points++; - } - return points; - } + static Pattern lower = Pattern.compile("[a-z]"); - public static int checkpw(String pw, User u) { - if (pw == null) { - return 0; - } - int light = checkpwlight(pw); - if (contained(pw, u.getEmail())) { - light -= 2; - } - if (contained(pw, u.getFname())) { - light -= 2; - } - if (contained(pw, u.getLname())) { - light -= 2; - } - if (contained(pw, u.getMname())) { - light -= 2; - } - if (contained(pw, u.getSuffix())) { - light -= 2; - } - // TODO dictionary check - return light; - } + static Pattern upper = Pattern.compile("[A-Z]"); - public static void assertStrongPassword(String pw, User u) throws GigiApiException { - if (checkpw(pw, u) < 3) { - throw new GigiApiException("The Pass Phrase you submitted failed to contain enough" - + " differing characters and/or contained words from" + " your name and/or email address."); - } - } + static Pattern whitespace = Pattern.compile("\\s"); - private static boolean contained(String pw, String check) { - if (check == null || check.equals("")) { - return false; - } - if (pw.contains(check)) { - return true; - } - if (check.contains(pw)) { - return true; - } - return false; - } + static Pattern special = Pattern.compile("(?!\\s)\\W"); + + private PasswordStrengthChecker() {} + + private static int checkpwlight(String pw) { + int points = 0; + if (pw.length() > 15) { + points++; + } + if (pw.length() > 20) { + points++; + } + if (pw.length() > 25) { + points++; + } + if (pw.length() > 30) { + points++; + } + if (digits.matcher(pw).find()) { + points++; + } + if (lower.matcher(pw).find()) { + points++; + } + if (upper.matcher(pw).find()) { + points++; + } + if (special.matcher(pw).find()) { + points++; + } + if (whitespace.matcher(pw).find()) { + points++; + } + return points; + } + + public static int checkpw(String pw, User u) { + if (pw == null) { + return 0; + } + int light = checkpwlight(pw); + if (contained(pw, u.getEmail())) { + light -= 2; + } + if (contained(pw, u.getFname())) { + light -= 2; + } + if (contained(pw, u.getLname())) { + light -= 2; + } + if (contained(pw, u.getMname())) { + light -= 2; + } + if (contained(pw, u.getSuffix())) { + light -= 2; + } + // TODO dictionary check + return light; + } + + public static void assertStrongPassword(String pw, User u) throws GigiApiException { + if (checkpw(pw, u) < 3) { + throw new GigiApiException("The Pass Phrase you submitted failed to contain enough" + " differing characters and/or contained words from" + " your name and/or email address."); + } + } + + private static boolean contained(String pw, String check) { + if (check == null || check.equals("")) { + return false; + } + if (pw.contains(check)) { + return true; + } + if (check.contains(pw)) { + return true; + } + return false; + } } diff --git a/src/org/cacert/gigi/util/RandomToken.java b/src/org/cacert/gigi/util/RandomToken.java index b84ee037..0c1035d6 100644 --- a/src/org/cacert/gigi/util/RandomToken.java +++ b/src/org/cacert/gigi/util/RandomToken.java @@ -3,24 +3,25 @@ package org.cacert.gigi.util; 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++) { - int rand = sr.nextInt(26 * 2 + 10); - if (rand < 10) { - token.append((char) ('0' + rand)); - continue; - } - rand -= 10; - if (rand < 26) { - token.append((char) ('a' + rand)); - continue; - } - rand -= 26; - token.append((char) ('A' + rand)); - } - return token.toString(); - } + static SecureRandom sr = new SecureRandom(); + + public static String generateToken(int length) { + StringBuffer token = new StringBuffer(); + for (int i = 0; i < length; i++) { + int rand = sr.nextInt(26 * 2 + 10); + if (rand < 10) { + token.append((char) ('0' + rand)); + continue; + } + rand -= 10; + if (rand < 26) { + token.append((char) ('a' + rand)); + continue; + } + rand -= 26; + token.append((char) ('A' + rand)); + } + return token.toString(); + } } diff --git a/src/org/cacert/gigi/util/ServerConstants.java b/src/org/cacert/gigi/util/ServerConstants.java index eafe9393..49f5d050 100644 --- a/src/org/cacert/gigi/util/ServerConstants.java +++ b/src/org/cacert/gigi/util/ServerConstants.java @@ -3,53 +3,58 @@ package org.cacert.gigi.util; import java.util.Properties; public class ServerConstants { - private static String wwwHostName = "www.cacert.local"; - private static String secureHostName = "secure.cacert.local"; - 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")) { - port = ":" + conf.getProperty("port"); - } - wwwHostName = conf.getProperty("name.www"); - secureHostName = conf.getProperty("name.secure"); - 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; - } + + private static String wwwHostName = "www.cacert.local"; + + private static String secureHostName = "secure.cacert.local"; + + 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")) { + port = ":" + conf.getProperty("port"); + } + wwwHostName = conf.getProperty("name.www"); + secureHostName = conf.getProperty("name.secure"); + 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 e8353acc..940664fa 100644 --- a/tests/org/cacert/gigi/LoginTest.java +++ b/tests/org/cacert/gigi/LoginTest.java @@ -7,21 +7,21 @@ import org.junit.Test; public class LoginTest extends ManagedTest { - @Test - public void testLoginUnverified() throws IOException { - long uniq = System.currentTimeMillis(); - String email = "system" + uniq + "@testmail.org"; - registerUser("an", "bn", email, TEST_PASSWORD); - waitForMail(); - assertFalse(isLoggedin(login(email, TEST_PASSWORD))); - } + @Test + public void testLoginUnverified() throws IOException { + long uniq = System.currentTimeMillis(); + String email = "system" + uniq + "@testmail.org"; + registerUser("an", "bn", email, TEST_PASSWORD); + waitForMail(); + assertFalse(isLoggedin(login(email, TEST_PASSWORD))); + } - @Test - public void testLoginVerified() throws IOException { - long uniq = System.currentTimeMillis(); - String email = "system2" + uniq + "@testmail.org"; - createVerifiedUser("an", "bn", email, TEST_PASSWORD); - assertTrue(isLoggedin(login(email, TEST_PASSWORD))); - } + @Test + public void testLoginVerified() throws IOException { + long uniq = System.currentTimeMillis(); + String email = "system2" + uniq + "@testmail.org"; + createVerifiedUser("an", "bn", email, TEST_PASSWORD); + assertTrue(isLoggedin(login(email, TEST_PASSWORD))); + } } diff --git a/tests/org/cacert/gigi/TestCertificate.java b/tests/org/cacert/gigi/TestCertificate.java index f6864989..5784e2ca 100644 --- a/tests/org/cacert/gigi/TestCertificate.java +++ b/tests/org/cacert/gigi/TestCertificate.java @@ -15,62 +15,61 @@ import org.junit.Test; import static org.junit.Assert.*; public class TestCertificate extends ManagedTest { - @Test - public void testClientCertLoginStates() throws IOException, GeneralSecurityException, SQLException, - InterruptedException { - String[] key1 = generateCSR("/CN=testmail@example.com"); - Certificate c = new Certificate(1, "/CN=testmail@example.com", "sha256", key1[1], CSRType.CSR); - final PrivateKey pk = PemKey.parsePEMPrivateKey(key1[0]); - c.issue().waitFor(60000); - final X509Certificate ce = c.cert(); - assertNotNull(login(pk, ce)); - } - @Test - public void testCertLifeCycle() throws IOException, GeneralSecurityException, SQLException, InterruptedException { - String[] key1 = generateCSR("/CN=testmail@example.com"); - Certificate c = new Certificate(1, "/CN=testmail@example.com", "sha256", key1[1], CSRType.CSR); - final PrivateKey pk = PemKey.parsePEMPrivateKey(key1[0]); + @Test + public void testClientCertLoginStates() throws IOException, GeneralSecurityException, SQLException, InterruptedException { + String[] key1 = generateCSR("/CN=testmail@example.com"); + Certificate c = new Certificate(1, "/CN=testmail@example.com", "sha256", key1[1], CSRType.CSR); + final PrivateKey pk = PemKey.parsePEMPrivateKey(key1[0]); + c.issue().waitFor(60000); + final X509Certificate ce = c.cert(); + assertNotNull(login(pk, ce)); + } - testFails(CertificateStatus.DRAFT, c); - c.issue().waitFor(60000); + @Test + public void testCertLifeCycle() throws IOException, GeneralSecurityException, SQLException, InterruptedException { + String[] key1 = generateCSR("/CN=testmail@example.com"); + Certificate c = new Certificate(1, "/CN=testmail@example.com", "sha256", key1[1], CSRType.CSR); + final PrivateKey pk = PemKey.parsePEMPrivateKey(key1[0]); - testFails(CertificateStatus.ISSUED, c); - X509Certificate cert = c.cert(); - assertNotNull(login(pk, cert)); - c.revoke().waitFor(60000); + testFails(CertificateStatus.DRAFT, c); + c.issue().waitFor(60000); - testFails(CertificateStatus.REVOKED, c); - assertNull(login(pk, cert)); + testFails(CertificateStatus.ISSUED, c); + X509Certificate cert = c.cert(); + assertNotNull(login(pk, cert)); + c.revoke().waitFor(60000); - } + testFails(CertificateStatus.REVOKED, c); + assertNull(login(pk, cert)); - private void testFails(CertificateStatus status, Certificate c) throws IOException, GeneralSecurityException, - SQLException { - assertEquals(status, c.getStatus()); - if (status != CertificateStatus.ISSUED) { - try { - c.revoke(); - fail(status + " is in invalid state"); - } catch (IllegalStateException ise) { + } - } - } - if (status != CertificateStatus.DRAFT) { - try { - c.issue(); - fail(status + " is in invalid state"); - } catch (IllegalStateException ise) { + private void testFails(CertificateStatus status, Certificate c) throws IOException, GeneralSecurityException, SQLException { + assertEquals(status, c.getStatus()); + if (status != CertificateStatus.ISSUED) { + try { + c.revoke(); + fail(status + " is in invalid state"); + } catch (IllegalStateException ise) { - } - } - if (status != CertificateStatus.ISSUED) { - try { - c.cert(); - fail(status + " is in invalid state"); - } catch (IllegalStateException ise) { + } + } + if (status != CertificateStatus.DRAFT) { + try { + c.issue(); + fail(status + " is in invalid state"); + } catch (IllegalStateException ise) { - } - } - } + } + } + if (status != CertificateStatus.ISSUED) { + try { + c.cert(); + fail(status + " is in invalid state"); + } catch (IllegalStateException ise) { + + } + } + } } diff --git a/tests/org/cacert/gigi/TestDomain.java b/tests/org/cacert/gigi/TestDomain.java index 3eecd03f..936395db 100644 --- a/tests/org/cacert/gigi/TestDomain.java +++ b/tests/org/cacert/gigi/TestDomain.java @@ -6,94 +6,95 @@ import org.cacert.gigi.testUtils.ManagedTest; import org.junit.Test; public class TestDomain extends ManagedTest { - private User us; - public TestDomain() { - int uid = createVerifiedUser("fn", "ln", createUniqueName() + "pr@test-email.de", TEST_PASSWORD); - us = User.getById(uid); - } + private User us; - @Test - public void testDomain() throws InterruptedException, GigiApiException { - assertEquals(0, us.getDomains().length); - Domain d = new Domain(us, "v1.example.org"); - assertEquals(0, d.getId()); - d.insert(); - Domain[] domains = us.getDomains(); - assertEquals(1, domains.length); - assertEquals("v1.example.org", domains[0].getSuffix()); - assertEquals(domains[0].getOwner().getId(), us.getId()); - assertNotEquals(0, domains[0].getId()); - assertNotEquals(0, d.getId()); - assertEquals(d.getId(), domains[0].getId()); + public TestDomain() { + int uid = createVerifiedUser("fn", "ln", createUniqueName() + "pr@test-email.de", TEST_PASSWORD); + us = User.getById(uid); + } - Domain d2 = new Domain(us, "v2.example.org"); - assertEquals(0, d2.getId()); - d2.insert(); + @Test + public void testDomain() throws InterruptedException, GigiApiException { + assertEquals(0, us.getDomains().length); + Domain d = new Domain(us, "v1.example.org"); + assertEquals(0, d.getId()); + d.insert(); + Domain[] domains = us.getDomains(); + assertEquals(1, domains.length); + assertEquals("v1.example.org", domains[0].getSuffix()); + assertEquals(domains[0].getOwner().getId(), us.getId()); + assertNotEquals(0, domains[0].getId()); + assertNotEquals(0, d.getId()); + assertEquals(d.getId(), domains[0].getId()); - domains = us.getDomains(); - assertEquals(2, domains.length); - assertEquals("v2.example.org", domains[1].getSuffix()); - assertEquals(domains[0].getOwner().getId(), us.getId()); - assertEquals(domains[1].getOwner().getId(), us.getId()); - assertNotEquals(0, domains[0].getId()); - assertNotEquals(0, d.getId()); - assertEquals(d.getId(), domains[0].getId()); + Domain d2 = new Domain(us, "v2.example.org"); + assertEquals(0, d2.getId()); + d2.insert(); - } + domains = us.getDomains(); + assertEquals(2, domains.length); + assertEquals("v2.example.org", domains[1].getSuffix()); + assertEquals(domains[0].getOwner().getId(), us.getId()); + assertEquals(domains[1].getOwner().getId(), us.getId()); + assertNotEquals(0, domains[0].getId()); + assertNotEquals(0, d.getId()); + assertEquals(d.getId(), domains[0].getId()); - @Test - public void testDoubleDomain() throws InterruptedException, GigiApiException { - Domain d = new Domain(us, "dub.example.org"); - d.insert(); - try { - Domain d2 = new Domain(us, "dub.example.org"); - d2.insert(); - fail("expected exception"); - } catch (GigiApiException e) { - // expected - } - } + } - @Test - public void testDoubleDomainDelete() throws InterruptedException, GigiApiException { - Domain d = new Domain(us, "del.example.org"); - d.insert(); - d.delete(); - Domain d2 = new Domain(us, "del.example.org"); - d2.insert(); - } + @Test + public void testDoubleDomain() throws InterruptedException, GigiApiException { + Domain d = new Domain(us, "dub.example.org"); + d.insert(); + try { + Domain d2 = new Domain(us, "dub.example.org"); + d2.insert(); + fail("expected exception"); + } catch (GigiApiException e) { + // expected + } + } - @Test - public void testDoubleDomainPrefix() throws InterruptedException, GigiApiException { - Domain d = new Domain(us, "pref.aexample.org"); - d.insert(); - Domain d2 = new Domain(us, "a.pref.aexample.org"); - try { - d2.insert(); - fail("expected exception"); - } catch (GigiApiException e) { - // expected - } - Domain d3 = new Domain(us, "aexample.org"); - try { - d3.insert(); - fail("expected exception"); - } catch (GigiApiException e) { - // expected - } - } + @Test + public void testDoubleDomainDelete() throws InterruptedException, GigiApiException { + Domain d = new Domain(us, "del.example.org"); + d.insert(); + d.delete(); + Domain d2 = new Domain(us, "del.example.org"); + d2.insert(); + } - @Test - public void testDoubleInsertDomain() throws InterruptedException, GigiApiException { - Domain d = new Domain(us, "dins.example.org"); - d.insert(); - try { - d.insert(); - fail("expected exception"); - } catch (GigiApiException e) { - // expected - } - } + @Test + public void testDoubleDomainPrefix() throws InterruptedException, GigiApiException { + Domain d = new Domain(us, "pref.aexample.org"); + d.insert(); + Domain d2 = new Domain(us, "a.pref.aexample.org"); + try { + d2.insert(); + fail("expected exception"); + } catch (GigiApiException e) { + // expected + } + Domain d3 = new Domain(us, "aexample.org"); + try { + d3.insert(); + fail("expected exception"); + } catch (GigiApiException e) { + // expected + } + } + + @Test + public void testDoubleInsertDomain() throws InterruptedException, GigiApiException { + Domain d = new Domain(us, "dins.example.org"); + d.insert(); + try { + d.insert(); + fail("expected exception"); + } catch (GigiApiException e) { + // expected + } + } } diff --git a/tests/org/cacert/gigi/TestSSL.java b/tests/org/cacert/gigi/TestSSL.java index c39b20f5..83bc7f69 100644 --- a/tests/org/cacert/gigi/TestSSL.java +++ b/tests/org/cacert/gigi/TestSSL.java @@ -18,88 +18,91 @@ import org.cacert.gigi.testUtils.ManagedTest; import org.junit.Test; public class TestSSL extends ManagedTest { - private ByteBuffer in; - private ByteBuffer inC; - private ByteBuffer outC; - private ByteBuffer out; - static { - InitTruststore.run(); - } - - @Test - 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]))); - - in = ByteBuffer.allocate(se.getSession().getApplicationBufferSize()); - inC = ByteBuffer.allocate(se.getSession().getPacketBufferSize()); - inC.limit(0); - out = ByteBuffer.allocate(se.getSession().getApplicationBufferSize()); - outC = ByteBuffer.allocate(se.getSession().getPacketBufferSize()); - outC.limit(0); - se.setUseClientMode(true); - se.beginHandshake(); - - work(se, s); - se.beginHandshake(); - try { - work(se, s); - 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 { - while (se.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING - && 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()); - } - } - } - - private SSLEngineResult unwrap(SSLEngine se, SocketChannel s) throws IOException, SSLException { - if (inC.remaining() == 0) { - inC.clear(); - s.read(inC); - inC.flip(); - } - SSLEngineResult result = se.unwrap(inC, in); - if (result.getStatus() == javax.net.ssl.SSLEngineResult.Status.BUFFER_UNDERFLOW) { - int pos = inC.position(); - int limit = inC.limit(); - inC.limit(inC.capacity()); - inC.position(limit); - int read = s.read(inC); - if (read <= 0) { - throw new EOFException(); - } - inC.limit(inC.position()); - inC.position(pos); - } - return result; - } - - private SSLEngineResult wrap(SSLEngine se, SocketChannel s) throws SSLException, IOException { - outC.clear(); - SSLEngineResult result = se.wrap(out, outC); - outC.flip(); - s.write(outC); - - return result; - } + + private ByteBuffer in; + + private ByteBuffer inC; + + private ByteBuffer outC; + + private ByteBuffer out; + static { + InitTruststore.run(); + } + + @Test + 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]))); + + in = ByteBuffer.allocate(se.getSession().getApplicationBufferSize()); + inC = ByteBuffer.allocate(se.getSession().getPacketBufferSize()); + inC.limit(0); + out = ByteBuffer.allocate(se.getSession().getApplicationBufferSize()); + outC = ByteBuffer.allocate(se.getSession().getPacketBufferSize()); + outC.limit(0); + se.setUseClientMode(true); + se.beginHandshake(); + + work(se, s); + se.beginHandshake(); + try { + work(se, s); + 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 { + while (se.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING && 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()); + } + } + } + + private SSLEngineResult unwrap(SSLEngine se, SocketChannel s) throws IOException, SSLException { + if (inC.remaining() == 0) { + inC.clear(); + s.read(inC); + inC.flip(); + } + SSLEngineResult result = se.unwrap(inC, in); + if (result.getStatus() == javax.net.ssl.SSLEngineResult.Status.BUFFER_UNDERFLOW) { + int pos = inC.position(); + int limit = inC.limit(); + inC.limit(inC.capacity()); + inC.position(limit); + int read = s.read(inC); + if (read <= 0) { + throw new EOFException(); + } + inC.limit(inC.position()); + inC.position(pos); + } + return result; + } + + private SSLEngineResult wrap(SSLEngine se, SocketChannel s) throws SSLException, IOException { + outC.clear(); + SSLEngineResult result = se.wrap(out, outC); + outC.flip(); + s.write(outC); + + return result; + } } diff --git a/tests/org/cacert/gigi/TestSecurityHeaders.java b/tests/org/cacert/gigi/TestSecurityHeaders.java index 75675c66..ddff38ee 100644 --- a/tests/org/cacert/gigi/TestSecurityHeaders.java +++ b/tests/org/cacert/gigi/TestSecurityHeaders.java @@ -10,20 +10,21 @@ import org.junit.Test; import static org.junit.Assert.*; public class TestSecurityHeaders extends ManagedTest { - @Test - public void testSTS() throws IOException { - 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(); - assertNotNull(uc.getHeaderField("Content-Security-Policy")); - } - - public void testAllowOrigin() throws IOException { - HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection(); - assertNotNull(uc.getHeaderField("Access-Control-Allow-Origin")); - - } + + @Test + public void testSTS() throws IOException { + 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(); + assertNotNull(uc.getHeaderField("Content-Security-Policy")); + } + + public void testAllowOrigin() throws IOException { + HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection(); + assertNotNull(uc.getHeaderField("Access-Control-Allow-Origin")); + + } } diff --git a/tests/org/cacert/gigi/TestSeparateSessionScope.java b/tests/org/cacert/gigi/TestSeparateSessionScope.java index a28def7c..e676e51b 100644 --- a/tests/org/cacert/gigi/TestSeparateSessionScope.java +++ b/tests/org/cacert/gigi/TestSeparateSessionScope.java @@ -17,31 +17,31 @@ import org.junit.Test; public class TestSeparateSessionScope extends ManagedTest { - @Test - public void testSeparateScope() throws IOException, GeneralSecurityException, SQLException, InterruptedException { - String mail = "thisgo" + createUniqueName() + "@example.com"; - int user = createAssuranceUser("test", "tugo", mail, TEST_PASSWORD); - String cookie = login(mail, TEST_PASSWORD); - String[] csr = generateCSR("/CN=felix@dogcraft.de"); - Certificate c = new Certificate(user, "/CN=testmail@example.com", "sha256", csr[1], CSRType.CSR); - final PrivateKey pk = PemKey.parsePEMPrivateKey(csr[0]); - c.issue().waitFor(60000); - final X509Certificate ce = c.cert(); - String scookie = login(pk, ce); - - assertTrue(isLoggedin(cookie)); - assertFalse(isLoggedin(scookie)); - - URL u = new URL("https://" + getServerName().replaceAll("^www", "secure") + SECURE_REFERENCE); - HttpURLConnection huc = (HttpURLConnection) u.openConnection(); - authenticateClientCert(pk, ce, huc); - huc.setRequestProperty("Cookie", scookie); - assertEquals(200, huc.getResponseCode()); - - HttpURLConnection huc2 = (HttpURLConnection) u.openConnection(); - authenticateClientCert(pk, ce, huc2); - huc2.setRequestProperty("Cookie", cookie); - assertEquals(302, huc2.getResponseCode()); - - } + @Test + public void testSeparateScope() throws IOException, GeneralSecurityException, SQLException, InterruptedException { + String mail = "thisgo" + createUniqueName() + "@example.com"; + int user = createAssuranceUser("test", "tugo", mail, TEST_PASSWORD); + String cookie = login(mail, TEST_PASSWORD); + String[] csr = generateCSR("/CN=felix@dogcraft.de"); + Certificate c = new Certificate(user, "/CN=testmail@example.com", "sha256", csr[1], CSRType.CSR); + final PrivateKey pk = PemKey.parsePEMPrivateKey(csr[0]); + c.issue().waitFor(60000); + final X509Certificate ce = c.cert(); + String scookie = login(pk, ce); + + assertTrue(isLoggedin(cookie)); + assertFalse(isLoggedin(scookie)); + + URL u = new URL("https://" + getServerName().replaceAll("^www", "secure") + SECURE_REFERENCE); + HttpURLConnection huc = (HttpURLConnection) u.openConnection(); + authenticateClientCert(pk, ce, huc); + huc.setRequestProperty("Cookie", scookie); + assertEquals(200, huc.getResponseCode()); + + HttpURLConnection huc2 = (HttpURLConnection) u.openConnection(); + authenticateClientCert(pk, ce, huc2); + huc2.setRequestProperty("Cookie", cookie); + assertEquals(302, huc2.getResponseCode()); + + } } diff --git a/tests/org/cacert/gigi/TestUser.java b/tests/org/cacert/gigi/TestUser.java index ed854498..2b783daa 100644 --- a/tests/org/cacert/gigi/TestUser.java +++ b/tests/org/cacert/gigi/TestUser.java @@ -7,48 +7,49 @@ import org.junit.Test; import static org.junit.Assert.*; public class TestUser extends ManagedTest { - @Test - public void testStoreAndLoad() throws SQLException { - User u = new User(); - u.setFname("user"); - u.setLname("last"); - u.setMname(""); - u.setSuffix(""); - long dob = System.currentTimeMillis(); - dob -= dob % (1000 * 60 * 60 * 24); - u.setDob(new java.sql.Date(dob)); - u.setEmail(createUniqueName() + "a@email.org"); - u.insert("password"); - int id = u.getId(); - User u2 = new User(id); - assertEquals(u, u2); - } - - @Test - public void testWebStoreAndLoad() throws SQLException { - int id = createVerifiedUser("aä", "b", createUniqueName() + "a@email.org", TEST_PASSWORD); - - User u = new User(id); - assertEquals("aä", u.getFname()); - assertEquals("b", u.getLname()); - assertEquals("", u.getMname()); - } - - @Test - public void testAssurerUtilMethods() throws SQLException { - int id = createAssuranceUser("aä", "b", createUniqueName() + "a@email.org", TEST_PASSWORD); - - User u = new User(id); - assertTrue(u.canAssure()); - int assurancePoints = u.getAssurancePoints(); - int expPoints = u.getExperiencePoints(); - assertEquals(100, assurancePoints); - assertEquals(2, expPoints); - assertTrue(u.hasPassedCATS()); - assertEquals(10, u.getMaxAssurePoints()); - - assertEquals("aä", u.getFname()); - assertEquals("b", u.getLname()); - assertEquals("", u.getMname()); - } + + @Test + public void testStoreAndLoad() throws SQLException { + User u = new User(); + u.setFname("user"); + u.setLname("last"); + u.setMname(""); + u.setSuffix(""); + long dob = System.currentTimeMillis(); + dob -= dob % (1000 * 60 * 60 * 24); + u.setDob(new java.sql.Date(dob)); + u.setEmail(createUniqueName() + "a@email.org"); + u.insert("password"); + int id = u.getId(); + User u2 = new User(id); + assertEquals(u, u2); + } + + @Test + public void testWebStoreAndLoad() throws SQLException { + int id = createVerifiedUser("aä", "b", createUniqueName() + "a@email.org", TEST_PASSWORD); + + User u = new User(id); + assertEquals("aä", u.getFname()); + assertEquals("b", u.getLname()); + assertEquals("", u.getMname()); + } + + @Test + public void testAssurerUtilMethods() throws SQLException { + int id = createAssuranceUser("aä", "b", createUniqueName() + "a@email.org", TEST_PASSWORD); + + User u = new User(id); + assertTrue(u.canAssure()); + int assurancePoints = u.getAssurancePoints(); + int expPoints = u.getExperiencePoints(); + assertEquals(100, assurancePoints); + assertEquals(2, expPoints); + assertTrue(u.hasPassedCATS()); + assertEquals(10, u.getMaxAssurePoints()); + + assertEquals("aä", u.getFname()); + assertEquals("b", u.getLname()); + assertEquals("", u.getMname()); + } } diff --git a/tests/org/cacert/gigi/pages/account/TestChangePassword.java b/tests/org/cacert/gigi/pages/account/TestChangePassword.java index 4b9e48d7..119df79f 100644 --- a/tests/org/cacert/gigi/pages/account/TestChangePassword.java +++ b/tests/org/cacert/gigi/pages/account/TestChangePassword.java @@ -11,98 +11,96 @@ import org.cacert.gigi.testUtils.ManagedTest; import org.junit.Test; public class TestChangePassword extends ManagedTest { - User u = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@example.org", TEST_PASSWORD)); - String cookie; - String path = ChangePasswordPage.PATH; - - public TestChangePassword() throws IOException { - cookie = login(u.getEmail(), TEST_PASSWORD); - assertTrue(isLoggedin(cookie)); - } - - @Test - public void testChangePasswordInternal() throws IOException, GigiApiException { - try { - u.changePassword(TEST_PASSWORD + "wrong", TEST_PASSWORD + "v2"); - fail("Password change must not succeed if old password is wrong."); - } catch (GigiApiException e) { - // expected - } - ; - assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); - u.changePassword(TEST_PASSWORD, TEST_PASSWORD + "v2"); - assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); - } - - @Test - public void testChangePasswordWeb() throws IOException { - String error = executeBasicWebInteraction(cookie, path, - "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") // - + "&pword1=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")// - + "&pword2=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")); - assertNull(error); - assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); - assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); - - } - - @Test - public void testChangePasswordWebOldWrong() throws IOException { - String error = executeBasicWebInteraction(cookie, path, - "oldpassword=a" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") // - + "&pword1=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")// - + "&pword2=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")); - assertNotNull(error); - assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); - assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); - - } - - @Test - public void testChangePasswordWebNewWrong() throws IOException { - String error = executeBasicWebInteraction(cookie, path, - "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") // - + "&pword1=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")// - + "&pword2=a" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")); - assertNotNull(error); - assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); - assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); - - } - - @Test - public void testChangePasswordWebNewEasy() throws IOException { - String error = executeBasicWebInteraction(cookie, path, - "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") // - + "&pword1=a&pword2=a"); - assertNotNull(error); - assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); - assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); - - } - - @Test - public void testChangePasswordWebMissingFields() throws IOException { - String np = URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8"); - assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); - String error = executeBasicWebInteraction(cookie, path, - "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") // - + "&pword1=" + np); - assertNotNull(error); - assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); - assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); - - error = executeBasicWebInteraction(cookie, path, "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") // - + "&pword2=" + np); - assertNotNull(error); - assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); - assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); - - error = executeBasicWebInteraction(cookie, path, "pword1=" + np + "&pword2=" + np); - assertNotNull(error); - assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); - assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); - - } + + User u = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@example.org", TEST_PASSWORD)); + + String cookie; + + String path = ChangePasswordPage.PATH; + + public TestChangePassword() throws IOException { + cookie = login(u.getEmail(), TEST_PASSWORD); + assertTrue(isLoggedin(cookie)); + } + + @Test + public void testChangePasswordInternal() throws IOException, GigiApiException { + try { + u.changePassword(TEST_PASSWORD + "wrong", TEST_PASSWORD + "v2"); + fail("Password change must not succeed if old password is wrong."); + } catch (GigiApiException e) { + // expected + } + ; + assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); + u.changePassword(TEST_PASSWORD, TEST_PASSWORD + "v2"); + assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); + } + + @Test + public void testChangePasswordWeb() throws IOException { + String error = executeBasicWebInteraction(cookie, path, "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") // + + "&pword1=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")// + + "&pword2=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")); + assertNull(error); + assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); + assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); + + } + + @Test + public void testChangePasswordWebOldWrong() throws IOException { + String error = executeBasicWebInteraction(cookie, path, "oldpassword=a" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") // + + "&pword1=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")// + + "&pword2=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")); + assertNotNull(error); + assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); + assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); + + } + + @Test + public void testChangePasswordWebNewWrong() throws IOException { + String error = executeBasicWebInteraction(cookie, path, "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") // + + "&pword1=" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")// + + "&pword2=a" + URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8")); + assertNotNull(error); + assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); + assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); + + } + + @Test + public void testChangePasswordWebNewEasy() throws IOException { + String error = executeBasicWebInteraction(cookie, path, "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") // + + "&pword1=a&pword2=a"); + assertNotNull(error); + assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); + assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); + + } + + @Test + public void testChangePasswordWebMissingFields() throws IOException { + String np = URLEncoder.encode(TEST_PASSWORD + "v2", "UTF-8"); + assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); + String error = executeBasicWebInteraction(cookie, path, "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") // + + "&pword1=" + np); + assertNotNull(error); + assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); + assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); + + error = executeBasicWebInteraction(cookie, path, "oldpassword=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") // + + "&pword2=" + np); + assertNotNull(error); + assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); + assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); + + error = executeBasicWebInteraction(cookie, path, "pword1=" + np + "&pword2=" + np); + assertNotNull(error); + assertFalse(isLoggedin(login(u.getEmail(), TEST_PASSWORD + "v2"))); + assertTrue(isLoggedin(login(u.getEmail(), TEST_PASSWORD))); + + } } diff --git a/tests/org/cacert/gigi/pages/account/TestMailManagement.java b/tests/org/cacert/gigi/pages/account/TestMailManagement.java index 053aa32f..2adbf106 100644 --- a/tests/org/cacert/gigi/pages/account/TestMailManagement.java +++ b/tests/org/cacert/gigi/pages/account/TestMailManagement.java @@ -15,125 +15,121 @@ import org.cacert.gigi.testUtils.ManagedTest; import org.junit.Test; public class TestMailManagement extends ManagedTest { - private User u = User - .getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@example.org", TEST_PASSWORD)); - private String cookie; - private String path = MailOverview.DEFAULT_PATH; - - public TestMailManagement() throws IOException { - cookie = login(u.getEmail(), TEST_PASSWORD); - assertTrue(isLoggedin(cookie)); - } - - @Test - public void testMailAddInternal() throws InterruptedException, GigiApiException { - createVerifiedEmail(u); - } - - @Test - public void testMailAddInternalFaulty() { - try { - new EmailAddress("kurti ", u); - fail(); - } catch (IllegalArgumentException e) { - // Intended. - } - } - - @Test - public void testMailAddWeb() throws MalformedURLException, UnsupportedEncodingException, IOException { - String newMail = createUniqueName() + "uni@example.org"; - assertNull(executeBasicWebInteraction(cookie, path, "addmail&newemail=" + URLEncoder.encode(newMail, "UTF-8"), - 1)); - EmailAddress[] addrs = u.getEmails(); - for (int i = 0; i < addrs.length; i++) { - if (addrs[i].getAddress().equals(newMail)) { - return; - } - } - fail(); - } - - @Test - public void testMailAddWebFaulty() throws MalformedURLException, UnsupportedEncodingException, IOException { - String newMail = createUniqueName() + "uniexample.org"; - assertNotNull(executeBasicWebInteraction(cookie, path, - "addmail&newemail=" + URLEncoder.encode(newMail, "UTF-8"), 1)); - EmailAddress[] addrs = u.getEmails(); - for (int i = 0; i < addrs.length; i++) { - if (addrs[i].getAddress().equals(newMail)) { - fail(); - } - } - } - - @Test - public void testMailSetDefaultWeb() throws MalformedURLException, UnsupportedEncodingException, IOException, - InterruptedException, GigiApiException { - EmailAddress adrr = createVerifiedEmail(u); - assertNull(executeBasicWebInteraction(cookie, path, "makedefault&emailid=" + adrr.getId())); - assertEquals(User.getById(u.getId()).getEmail(), adrr.getAddress()); - } - - @Test - public void testMailSetDefaultWebUnverified() throws MalformedURLException, UnsupportedEncodingException, - IOException, InterruptedException, GigiApiException { - EmailAddress adrr = new EmailAddress(createUniqueName() + "test@test.tld", u); - adrr.insert(Language.getInstance("en")); - assertNotNull(executeBasicWebInteraction(cookie, path, "makedefault&emailid=" + adrr.getId())); - assertNotEquals(User.getById(u.getId()).getEmail(), adrr.getAddress()); - getMailReciever().clearMails(); - } - - @Test - public void testMailSetDefaultWebInvalidID() throws MalformedURLException, UnsupportedEncodingException, - IOException, InterruptedException, GigiApiException { - User u2 = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@example.org", TEST_PASSWORD)); - int id = -1; - EmailAddress[] emails = u2.getEmails(); - for (int i = 0; i < emails.length; i++) { - if (emails[i].getAddress().equals(u2.getEmail())) { - id = emails[i].getId(); - } - } - assertNotEquals(id, -1); - assertNotNull(executeBasicWebInteraction(cookie, path, "makedefault&emailid=" + id)); - assertNotEquals(User.getById(u.getId()).getEmail(), u2.getEmail()); - getMailReciever().clearMails(); - } - - @Test - public void testMailDeleteWeb() throws InterruptedException, GigiApiException, MalformedURLException, - UnsupportedEncodingException, IOException { - EmailAddress addr = createVerifiedEmail(u); - assertNull(executeBasicWebInteraction(cookie, path, "delete&delid[]=" + addr.getId(), 0)); - User u = User.getById(this.u.getId()); - EmailAddress[] addresses = u.getEmails(); - for (int i = 0; i < addresses.length; i++) { - assertNotEquals(addresses[i].getAddress(), addr.getAddress()); - } - } - - @Test - public void testMailDeleteWebMulti() throws InterruptedException, GigiApiException, MalformedURLException, - UnsupportedEncodingException, IOException { - EmailAddress[] addr = new EmailAddress[] { createVerifiedEmail(u), createVerifiedEmail(u) }; - assertNull(executeBasicWebInteraction(cookie, path, - "delete&delid[]=" + addr[0].getId() + "&delid[]=" + addr[1].getId(), 0)); - User u = User.getById(this.u.getId()); - EmailAddress[] addresses = u.getEmails(); - for (int i = 0; i < addresses.length; i++) { - assertNotEquals(addresses[i].getAddress(), addr[0].getAddress()); - assertNotEquals(addresses[i].getAddress(), addr[1].getAddress()); - } - } - - @Test - public void testMailDeleteWebFaulty() throws MalformedURLException, UnsupportedEncodingException, IOException { - User u2 = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@test.tld", TEST_PASSWORD)); - EmailAddress em = u2.getEmails()[0]; - assertNotNull(executeBasicWebInteraction(cookie, path, "delete&delid[]=" + em.getId(), 0)); - u2 = User.getById(u2.getId()); - assertNotEquals(u2.getEmails().length, 0); - } + + private User u = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@example.org", TEST_PASSWORD)); + + private String cookie; + + private String path = MailOverview.DEFAULT_PATH; + + public TestMailManagement() throws IOException { + cookie = login(u.getEmail(), TEST_PASSWORD); + assertTrue(isLoggedin(cookie)); + } + + @Test + public void testMailAddInternal() throws InterruptedException, GigiApiException { + createVerifiedEmail(u); + } + + @Test + public void testMailAddInternalFaulty() { + try { + new EmailAddress("kurti ", u); + fail(); + } catch (IllegalArgumentException e) { + // Intended. + } + } + + @Test + public void testMailAddWeb() throws MalformedURLException, UnsupportedEncodingException, IOException { + String newMail = createUniqueName() + "uni@example.org"; + assertNull(executeBasicWebInteraction(cookie, path, "addmail&newemail=" + URLEncoder.encode(newMail, "UTF-8"), 1)); + EmailAddress[] addrs = u.getEmails(); + for (int i = 0; i < addrs.length; i++) { + if (addrs[i].getAddress().equals(newMail)) { + return; + } + } + fail(); + } + + @Test + public void testMailAddWebFaulty() throws MalformedURLException, UnsupportedEncodingException, IOException { + String newMail = createUniqueName() + "uniexample.org"; + assertNotNull(executeBasicWebInteraction(cookie, path, "addmail&newemail=" + URLEncoder.encode(newMail, "UTF-8"), 1)); + EmailAddress[] addrs = u.getEmails(); + for (int i = 0; i < addrs.length; i++) { + if (addrs[i].getAddress().equals(newMail)) { + fail(); + } + } + } + + @Test + public void testMailSetDefaultWeb() throws MalformedURLException, UnsupportedEncodingException, IOException, InterruptedException, GigiApiException { + EmailAddress adrr = createVerifiedEmail(u); + assertNull(executeBasicWebInteraction(cookie, path, "makedefault&emailid=" + adrr.getId())); + assertEquals(User.getById(u.getId()).getEmail(), adrr.getAddress()); + } + + @Test + public void testMailSetDefaultWebUnverified() throws MalformedURLException, UnsupportedEncodingException, IOException, InterruptedException, GigiApiException { + EmailAddress adrr = new EmailAddress(createUniqueName() + "test@test.tld", u); + adrr.insert(Language.getInstance("en")); + assertNotNull(executeBasicWebInteraction(cookie, path, "makedefault&emailid=" + adrr.getId())); + assertNotEquals(User.getById(u.getId()).getEmail(), adrr.getAddress()); + getMailReciever().clearMails(); + } + + @Test + public void testMailSetDefaultWebInvalidID() throws MalformedURLException, UnsupportedEncodingException, IOException, InterruptedException, GigiApiException { + User u2 = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@example.org", TEST_PASSWORD)); + int id = -1; + EmailAddress[] emails = u2.getEmails(); + for (int i = 0; i < emails.length; i++) { + if (emails[i].getAddress().equals(u2.getEmail())) { + id = emails[i].getId(); + } + } + assertNotEquals(id, -1); + assertNotNull(executeBasicWebInteraction(cookie, path, "makedefault&emailid=" + id)); + assertNotEquals(User.getById(u.getId()).getEmail(), u2.getEmail()); + getMailReciever().clearMails(); + } + + @Test + public void testMailDeleteWeb() throws InterruptedException, GigiApiException, MalformedURLException, UnsupportedEncodingException, IOException { + EmailAddress addr = createVerifiedEmail(u); + assertNull(executeBasicWebInteraction(cookie, path, "delete&delid[]=" + addr.getId(), 0)); + User u = User.getById(this.u.getId()); + EmailAddress[] addresses = u.getEmails(); + for (int i = 0; i < addresses.length; i++) { + assertNotEquals(addresses[i].getAddress(), addr.getAddress()); + } + } + + @Test + public void testMailDeleteWebMulti() throws InterruptedException, GigiApiException, MalformedURLException, UnsupportedEncodingException, IOException { + EmailAddress[] addr = new EmailAddress[] { + createVerifiedEmail(u), createVerifiedEmail(u) + }; + assertNull(executeBasicWebInteraction(cookie, path, "delete&delid[]=" + addr[0].getId() + "&delid[]=" + addr[1].getId(), 0)); + User u = User.getById(this.u.getId()); + EmailAddress[] addresses = u.getEmails(); + for (int i = 0; i < addresses.length; i++) { + assertNotEquals(addresses[i].getAddress(), addr[0].getAddress()); + assertNotEquals(addresses[i].getAddress(), addr[1].getAddress()); + } + } + + @Test + public void testMailDeleteWebFaulty() throws MalformedURLException, UnsupportedEncodingException, IOException { + User u2 = User.getById(createVerifiedUser("fn", "ln", createUniqueName() + "uni@test.tld", TEST_PASSWORD)); + EmailAddress em = u2.getEmails()[0]; + assertNotNull(executeBasicWebInteraction(cookie, path, "delete&delid[]=" + em.getId(), 0)); + u2 = User.getById(u2.getId()); + assertNotEquals(u2.getEmails().length, 0); + } } diff --git a/tests/org/cacert/gigi/pages/main/RegisterPageTest.java b/tests/org/cacert/gigi/pages/main/RegisterPageTest.java index dd53ec50..be0124a7 100644 --- a/tests/org/cacert/gigi/pages/main/RegisterPageTest.java +++ b/tests/org/cacert/gigi/pages/main/RegisterPageTest.java @@ -14,171 +14,165 @@ import org.junit.Before; import org.junit.Test; public class RegisterPageTest extends ManagedTest { - static { - InitTruststore.run(); - HttpURLConnection.setFollowRedirects(false); - } - - @Before - public void setUp() throws Exception { - } - - @Test - public void testSuccess() throws IOException, InterruptedException { - long uniq = System.currentTimeMillis(); - registerUser("ab", "b", "correct" + uniq + "@email.de", TEST_PASSWORD); - assertSuccessfullRegMail(); - - String defaultSignup = "fname=" + URLEncoder.encode("ab", "UTF-8") + "&lname=" - + URLEncoder.encode("b", "UTF-8") + "&pword1=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") + "&pword2=" - + URLEncoder.encode(TEST_PASSWORD, "UTF-8") - + "&day=1&month=1&year=1910&cca_agree=1&mname=mn&suffix=sf&email="; - - String query = defaultSignup + URLEncoder.encode("correct3_" + uniq + "@email.de", "UTF-8") - + "&general=1&country=1®ional=1&radius=1"; - String data = fetchStartErrorMessage(runRegister(query)); - assertTrue(data, data.startsWith("")); - assertSuccessfullRegMail(); - - getMailReciever().setEmailCheckError("400 Greylisted"); - getMailReciever().setApproveRegex(Pattern.compile("a")); - query = defaultSignup + URLEncoder.encode("correct4_" + uniq + "@email.de", "UTF-8") - + "&general=1&country=1®ional=1&radius=1"; - data = fetchStartErrorMessage(runRegister(query)); - assertFalse(data, data.startsWith("")); - - assertNull(getMailReciever().recieve()); - - } - - private void assertSuccessfullRegMail() { - TestMail tm = waitForMail(); - 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"); - } - - @Test - public void testNoPword() throws IOException { - testFailedForm("fname=a&lname=b&email=e&pword2=ap&day=1&month=1&year=1910&cca_agree=1"); - } - - @Test - public void testDiffPword() throws IOException { - testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap2&day=1&month=1&year=1910&cca_agree=1"); - } - - @Test - 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"); - testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=0&year=1910&cca_agree=1"); - 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"); - testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=100&cca_agree=1"); - 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"); - } - - @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"); - assertTrue(run.contains("fn" + uniq)); - assertTrue(run.contains("ln" + uniq)); - assertTrue(run.contains("ma" + uniq + "@cacert.org")); - assertTrue(!run.contains("pas" + uniq)); - assertTrue(!run.contains("pas2" + uniq)); - - } - - @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=\"country\" value=\"1\">")); - 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=\"regional\" value=\"1\">")); - 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", TEST_PASSWORD); - try { - registerUser("RegisterTest", "User", "testmail" + uniq + "@cacert.org", TEST_PASSWORD); - 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", TEST_PASSWORD); - 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("")); - } + + static { + InitTruststore.run(); + HttpURLConnection.setFollowRedirects(false); + } + + @Before + public void setUp() throws Exception {} + + @Test + public void testSuccess() throws IOException, InterruptedException { + long uniq = System.currentTimeMillis(); + registerUser("ab", "b", "correct" + uniq + "@email.de", TEST_PASSWORD); + assertSuccessfullRegMail(); + + String defaultSignup = "fname=" + URLEncoder.encode("ab", "UTF-8") + "&lname=" + URLEncoder.encode("b", "UTF-8") + "&pword1=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") + "&pword2=" + URLEncoder.encode(TEST_PASSWORD, "UTF-8") + "&day=1&month=1&year=1910&cca_agree=1&mname=mn&suffix=sf&email="; + + String query = defaultSignup + URLEncoder.encode("correct3_" + uniq + "@email.de", "UTF-8") + "&general=1&country=1®ional=1&radius=1"; + String data = fetchStartErrorMessage(runRegister(query)); + assertTrue(data, data.startsWith("")); + assertSuccessfullRegMail(); + + getMailReciever().setEmailCheckError("400 Greylisted"); + getMailReciever().setApproveRegex(Pattern.compile("a")); + query = defaultSignup + URLEncoder.encode("correct4_" + uniq + "@email.de", "UTF-8") + "&general=1&country=1®ional=1&radius=1"; + data = fetchStartErrorMessage(runRegister(query)); + assertFalse(data, data.startsWith("")); + + assertNull(getMailReciever().recieve()); + + } + + private void assertSuccessfullRegMail() { + TestMail tm = waitForMail(); + 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"); + } + + @Test + public void testNoPword() throws IOException { + testFailedForm("fname=a&lname=b&email=e&pword2=ap&day=1&month=1&year=1910&cca_agree=1"); + } + + @Test + public void testDiffPword() throws IOException { + testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap2&day=1&month=1&year=1910&cca_agree=1"); + } + + @Test + 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"); + testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=0&year=1910&cca_agree=1"); + 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"); + testFailedForm("fname=a&lname=b&email=e&pword1=ap&pword2=ap&day=1&month=1&year=100&cca_agree=1"); + 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"); + } + + @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"); + assertTrue(run.contains("fn" + uniq)); + assertTrue(run.contains("ln" + uniq)); + assertTrue(run.contains("ma" + uniq + "@cacert.org")); + assertTrue( !run.contains("pas" + uniq)); + assertTrue( !run.contains("pas2" + uniq)); + + } + + @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=\"country\" value=\"1\">")); + 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=\"regional\" value=\"1\">")); + 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", TEST_PASSWORD); + try { + registerUser("RegisterTest", "User", "testmail" + uniq + "@cacert.org", TEST_PASSWORD); + 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", TEST_PASSWORD); + 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 98248933..94f194a3 100644 --- a/tests/org/cacert/gigi/pages/wot/TestAssurance.java +++ b/tests/org/cacert/gigi/pages/wot/TestAssurance.java @@ -21,154 +21,153 @@ import org.junit.Test; import static org.junit.Assert.*; public class TestAssurance extends ManagedTest { - private String assurerM; - private String assureeM; - private int assurer; - private int assuree; - private String cookie; - - @Before - public void setup() throws IOException { - assurerM = createUniqueName() + "@cacert-test.org"; - assureeM = createUniqueName() + "@cacert-test.org"; - assurer = createAssuranceUser("a", "b", assurerM, TEST_PASSWORD); - assuree = createAssuranceUser("a", "c", assureeM, TEST_PASSWORD); - cookie = login(assurerM, TEST_PASSWORD); - - } - - @Test - public void testAssureSearch() throws IOException { - 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"); - assertNull(loc); - } - - @Test - public void testAssureSearchDob() throws IOException { - 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"); - assertNull(loc); - 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 { - URL u = new URL("https://" + getServerName() + AssurePage.PATH); - URLConnection uc = u.openConnection(); - uc.setDoOutput(true); - uc.addRequestProperty("Cookie", cookie); - uc.getOutputStream().write((query).getBytes()); - uc.getOutputStream().flush(); - - 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"); - assertTrue(error, error.startsWith("")); - } - - @Test - 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().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().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=?"); - 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().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"); - 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"); - assertTrue(error, !error.startsWith("")); - error = getError("date=2000-01-01&location=&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10"); - assertTrue(error, !error.startsWith("")); - } - - @Test - public void testAssureFormInvalDate() throws IOException { - String error = getError("date=20000101&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10"); - assertTrue(error, !error.startsWith("")); - 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"); - assertTrue(error, !error.startsWith("")); - error = getError("date=2000-01-01&location=testcase&certify=1&rules=&CCAAgreed=1&assertion=1&points=10"); - assertTrue(error, !error.startsWith("")); - error = getError("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=a&assertion=1&points=10"); - assertTrue(error, !error.startsWith("")); - 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 { - 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); - URLConnection uc = u.openConnection(); - uc.addRequestProperty("Cookie", cookie); - String csrf = getCSRF(uc); - uc = u.openConnection(); - uc.addRequestProperty("Cookie", cookie); - uc.setDoOutput(true); - if (doCSRF) { - uc.getOutputStream().write(("csrf=" + csrf + "&").getBytes()); - } - return uc; - } + + private String assurerM; + + private String assureeM; + + private int assurer; + + private int assuree; + + private String cookie; + + @Before + public void setup() throws IOException { + assurerM = createUniqueName() + "@cacert-test.org"; + assureeM = createUniqueName() + "@cacert-test.org"; + assurer = createAssuranceUser("a", "b", assurerM, TEST_PASSWORD); + assuree = createAssuranceUser("a", "c", assureeM, TEST_PASSWORD); + cookie = login(assurerM, TEST_PASSWORD); + + } + + @Test + public void testAssureSearch() throws IOException { + 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"); + assertNull(loc); + } + + @Test + public void testAssureSearchDob() throws IOException { + 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"); + assertNull(loc); + 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 { + URL u = new URL("https://" + getServerName() + AssurePage.PATH); + URLConnection uc = u.openConnection(); + uc.setDoOutput(true); + uc.addRequestProperty("Cookie", cookie); + uc.getOutputStream().write((query).getBytes()); + uc.getOutputStream().flush(); + + 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"); + assertTrue(error, error.startsWith("")); + } + + @Test + 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().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().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=?"); + 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().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"); + 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"); + assertTrue(error, !error.startsWith("")); + error = getError("date=2000-01-01&location=&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10"); + assertTrue(error, !error.startsWith("")); + } + + @Test + public void testAssureFormInvalDate() throws IOException { + String error = getError("date=20000101&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10"); + assertTrue(error, !error.startsWith("")); + 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"); + assertTrue(error, !error.startsWith("")); + error = getError("date=2000-01-01&location=testcase&certify=1&rules=&CCAAgreed=1&assertion=1&points=10"); + assertTrue(error, !error.startsWith("")); + error = getError("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=a&assertion=1&points=10"); + assertTrue(error, !error.startsWith("")); + 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 { + 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); + URLConnection uc = u.openConnection(); + uc.addRequestProperty("Cookie", cookie); + String csrf = getCSRF(uc); + uc = u.openConnection(); + uc.addRequestProperty("Cookie", cookie); + uc.setDoOutput(true); + if (doCSRF) { + uc.getOutputStream().write(("csrf=" + csrf + "&").getBytes()); + } + return uc; + } } diff --git a/tests/org/cacert/gigi/testUtils/IOUtils.java b/tests/org/cacert/gigi/testUtils/IOUtils.java index 2db46f87..e33192e7 100644 --- a/tests/org/cacert/gigi/testUtils/IOUtils.java +++ b/tests/org/cacert/gigi/testUtils/IOUtils.java @@ -8,38 +8,38 @@ import java.net.HttpURLConnection; import java.net.URLConnection; public class IOUtils { - private IOUtils() { - - } - - public static String readURL(URLConnection in) { - try { - if (!in.getContentType().equals("text/html; charset=UTF-8")) { - if (in instanceof HttpURLConnection && ((HttpURLConnection) in).getResponseCode() != 200) { - System.err - .println(readURL(new InputStreamReader(((HttpURLConnection) in).getErrorStream(), "UTF-8"))); - } - throw new Error("Unrecognized content-type: " + in.getContentType()); - } - return readURL(new InputStreamReader(in.getInputStream(), "UTF-8")); - } catch (IOException e) { - throw new Error(e); - } - - } - - public static String readURL(Reader in) { - CharArrayWriter caw = new CharArrayWriter(); - char[] buffer = new char[1024]; - int len = 0; - try { - while ((len = in.read(buffer)) > 0) { - caw.write(buffer, 0, len); - } - return new String(caw.toCharArray()); - } catch (IOException e) { - throw new Error(e); - } - - } + + private IOUtils() { + + } + + public static String readURL(URLConnection in) { + try { + if ( !in.getContentType().equals("text/html; charset=UTF-8")) { + if (in instanceof HttpURLConnection && ((HttpURLConnection) in).getResponseCode() != 200) { + System.err.println(readURL(new InputStreamReader(((HttpURLConnection) in).getErrorStream(), "UTF-8"))); + } + throw new Error("Unrecognized content-type: " + in.getContentType()); + } + return readURL(new InputStreamReader(in.getInputStream(), "UTF-8")); + } catch (IOException e) { + throw new Error(e); + } + + } + + public static String readURL(Reader in) { + CharArrayWriter caw = new CharArrayWriter(); + char[] buffer = new char[1024]; + int len = 0; + try { + while ((len = in.read(buffer)) > 0) { + caw.write(buffer, 0, len); + } + return new String(caw.toCharArray()); + } catch (IOException e) { + throw new Error(e); + } + + } } diff --git a/tests/org/cacert/gigi/testUtils/InitTruststore.java b/tests/org/cacert/gigi/testUtils/InitTruststore.java index 7811470d..1207df93 100644 --- a/tests/org/cacert/gigi/testUtils/InitTruststore.java +++ b/tests/org/cacert/gigi/testUtils/InitTruststore.java @@ -1,15 +1,15 @@ 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"); - } + private InitTruststore() {} - public static void run() { + 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 5d4db129..a021427e 100644 --- a/tests/org/cacert/gigi/testUtils/ManagedTest.java +++ b/tests/org/cacert/gigi/testUtils/ManagedTest.java @@ -50,392 +50,394 @@ import org.junit.AfterClass; import org.junit.BeforeClass; public class ManagedTest { - /** - * Some password that fullfills the password criteria. - */ - protected static final String TEST_PASSWORD = "xvXV12°§"; - - private final String registerService = "/register"; - - private static TestEmailReciever ter; - private static Process gigi; - private static String url = "localhost:4443"; - - public static String getServerName() { - return url; - } - - static Properties testProps = new Properties(); - static { - InitTruststore.run(); - HttpURLConnection.setFollowRedirects(false); - } - - @BeforeClass - public static void connectToServer() { - try { - testProps.load(new FileInputStream("config/test.properties")); - if (!DatabaseConnection.isInited()) { - 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") }); - String type = testProps.getProperty("type"); - Properties mainProps = generateMainProps(); - ServerConstants.init(mainProps); - if (type.equals("local")) { - url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort"); - String[] parts = testProps.getProperty("mail").split(":", 2); - ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1]))); - return; - } - url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort"); - gigi = Runtime.getRuntime().exec(testProps.getProperty("java")); - DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream()); - System.out.println("... starting server"); - - 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); - toGigi.flush(); - - final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream())); - String line; - while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) { - } - new Thread() { - @Override - public void run() { - String line; - try { - while ((line = br.readLine()) != null) { - System.err.println(line); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - }.start(); - if (line == null) { - throw new Error("Server startup failed"); - } - ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473)); - SimpleSigner.runSigner(); - } catch (IOException e) { - throw new Error(e); - } catch (ClassNotFoundException e1) { - e1.printStackTrace(); - } catch (SQLException e1) { - e1.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - - private static Properties generateMainProps() { - Properties mainProps = new Properties(); - mainProps.setProperty("host", "127.0.0.1"); - mainProps.setProperty("name.secure", testProps.getProperty("name.secure")); - mainProps.setProperty("name.www", testProps.getProperty("name.www")); - mainProps.setProperty("name.static", testProps.getProperty("name.static")); - - mainProps.setProperty("port", testProps.getProperty("serverPort")); - mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider"); - mainProps.setProperty("emailProvider.port", "8473"); - 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")); - return mainProps; - } - - @AfterClass - public static void tearDownServer() { - String type = testProps.getProperty("type"); - ter.destroy(); - if (type.equals("local")) { - return; - } - gigi.destroy(); - try { - SimpleSigner.stopSigner(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - @After - public void removeMails() { - ter.reset(); - } - - public TestMail waitForMail() { - try { - return ter.recieve(); - } catch (InterruptedException e) { - throw new Error(e); - } - } - - public static TestEmailReciever getMailReciever() { - return ter; - } - - public String runRegister(String param) throws IOException { - URL regist = new URL("https://" + getServerName() + registerService); - HttpURLConnection uc = (HttpURLConnection) regist.openConnection(); - HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection(); - - String headerField = csrfConn.getHeaderField("Set-Cookie"); - headerField = stripCookie(headerField); - - String csrf = getCSRF(csrfConn); - uc.addRequestProperty("Cookie", headerField); - uc.setDoOutput(true); - uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes()); - String d = IOUtils.readURL(uc); - return d; - } - - public String fetchStartErrorMessage(String d) throws IOException { - String formFail = "
    "; - int idx = d.indexOf(formFail); - if (idx == -1) { - return null; - } - String startError = d.substring(idx + formFail.length(), idx + 100).trim(); - return startError; - } - - 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 data = fetchStartErrorMessage(runRegister(query)); - assertTrue(data, data.startsWith("
    ")); - } catch (UnsupportedEncodingException e) { - throw new Error(e); - } catch (IOException e) { - throw new Error(e); - } - } - - 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=?"); - ps.setString(1, email); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - return rs.getInt(1); - } - throw new Error(); - } catch (InterruptedException e) { - throw new Error(e); - } catch (IOException e) { - throw new Error(e); - } catch (SQLException e) { - throw new Error(e); - } - } - - /** - * Creates a new user with 100 Assurance points given by an (invalid) - * assurance. - * - * @param firstName - * the first name - * @param lastName - * the last name - * @param email - * the email - * @param password - * the password - * @return a new userid. - */ - 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`=?"); - ps.setInt(1, uid); - ps.setInt(2, 0); - ps.execute(); - ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'"); - ps.setInt(1, uid); - ps.setInt(2, uid); - ps.execute(); - - } catch (SQLException e) { - throw new Error(e); - } - return uid; - } - - static int count = 0; - - public static String createUniqueName() { - return "test" + System.currentTimeMillis() + "a" + (count++); - } - - private String stripCookie(String headerField) { - return headerField.substring(0, headerField.indexOf(';')); - } - - public static final String SECURE_REFERENCE = "/account/certs/email"; - - public boolean isLoggedin(String cookie) throws IOException { - URL u = new URL("https://" + getServerName() + SECURE_REFERENCE); - HttpURLConnection huc = (HttpURLConnection) u.openConnection(); - huc.addRequestProperty("Cookie", cookie); - return huc.getResponseCode() == 200; - } - - 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"); - os.write(data.getBytes()); - os.flush(); - String headerField = huc.getHeaderField("Set-Cookie"); - return stripCookie(headerField); - } - - public String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException, - KeyManagementException, IOException, MalformedURLException { - - HttpURLConnection connection = (HttpURLConnection) new URL("https://" - + getServerName().replaceFirst("^www.", "secure.") + "/login").openConnection(); - authenticateClientCert(pk, ce, connection); - if (connection.getResponseCode() == 302) { - assertEquals("https://" + getServerName().replaceFirst("^www.", "secure.").replaceFirst(":443$", "") + "/", - connection.getHeaderField("Location").replaceFirst(":443$", "")); - return stripCookie(connection.getHeaderField("Set-Cookie")); - } else { - return null; - } - } - - public void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection) - throws NoSuchAlgorithmException, KeyManagementException { - KeyManager km = new X509KeyManager() { - - @Override - public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) { - return "client"; - } - - @Override - public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) { - return null; - } - - @Override - public X509Certificate[] getCertificateChain(String arg0) { - return new X509Certificate[] { ce }; - } - - @Override - public String[] getClientAliases(String arg0, Principal[] arg1) { - return new String[] { "client" }; - } - - @Override - public PrivateKey getPrivateKey(String arg0) { - if (arg0.equals("client")) { - return pk; - } - return null; - } - - @Override - public String[] getServerAliases(String arg0, Principal[] arg1) { - return new String[] { "client" }; - } - }; - SSLContext sc = SSLContext.getInstance("TLS"); - sc.init(new KeyManager[] { km }, null, null); - if (connection instanceof HttpsURLConnection) { - ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory()); - } - } - - public String getCSRF(URLConnection u) throws IOException { - return getCSRF(u, 0); - } - - public String getCSRF(URLConnection u, int formIndex) throws IOException { - String content = IOUtils.readURL(u); - Pattern p = Pattern.compile(""); - Matcher m = p.matcher(content); - for (int i = 0; i < formIndex + 1; i++) { - if (!m.find()) { - throw new Error("No CSRF Token"); - } - } - return m.group(1); - } - - public static String[] generateCSR(String dn) throws IOException { - Process p = Runtime.getRuntime().exec( - new String[] { "openssl", "req", "-newkey", "rsa:1024", "-nodes", "-subj", dn, "-config", - "keys/selfsign.config" }); - String csr = IOUtils.readURL(new InputStreamReader(p.getInputStream())); - - String[] parts = csr.split("(?<=-----)\n(?=-----)"); - if (parts.length != 2) { - System.err.println(IOUtils.readURL(new InputStreamReader(p.getErrorStream()))); - throw new Error(); - } - return parts; - } - - public String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException, - UnsupportedEncodingException, IOException { - return executeBasicWebInteraction(cookie, path, query, 0); - } - - public String executeBasicWebInteraction(String cookie, String path, String query, int formIndex) - throws IOException, MalformedURLException, UnsupportedEncodingException { - URLConnection uc = new URL("https://" + getServerName() + path).openConnection(); - uc.addRequestProperty("Cookie", cookie); - String csrf = getCSRF(uc, formIndex); - - uc = new URL("https://" + getServerName() + path).openConnection(); - uc.addRequestProperty("Cookie", cookie); - uc.setDoOutput(true); - OutputStream os = uc.getOutputStream(); - os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" // - + query// - ).getBytes()); - os.flush(); - String error = fetchStartErrorMessage(IOUtils.readURL(uc)); - return error; - } - - public static EmailAddress createVerifiedEmail(User u) throws InterruptedException, GigiApiException { - EmailAddress adrr = new EmailAddress(createUniqueName() + "test@test.tld", u); - adrr.insert(Language.getInstance("en")); - TestMail testMail = getMailReciever().recieve(); - assertTrue(adrr.getAddress().equals(testMail.getTo())); - String hash = testMail.extractLink().substring(testMail.extractLink().lastIndexOf('=') + 1); - adrr.verify(hash); - getMailReciever().clearMails(); - return adrr; - } + + /** + * Some password that fullfills the password criteria. + */ + protected static final String TEST_PASSWORD = "xvXV12°§"; + + private final String registerService = "/register"; + + private static TestEmailReciever ter; + + private static Process gigi; + + private static String url = "localhost:4443"; + + public static String getServerName() { + return url; + } + + static Properties testProps = new Properties(); + static { + InitTruststore.run(); + HttpURLConnection.setFollowRedirects(false); + } + + @BeforeClass + public static void connectToServer() { + try { + testProps.load(new FileInputStream("config/test.properties")); + if ( !DatabaseConnection.isInited()) { + 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") + }); + String type = testProps.getProperty("type"); + Properties mainProps = generateMainProps(); + ServerConstants.init(mainProps); + if (type.equals("local")) { + url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort"); + String[] parts = testProps.getProperty("mail").split(":", 2); + ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1]))); + return; + } + url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort"); + gigi = Runtime.getRuntime().exec(testProps.getProperty("java")); + DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream()); + System.out.println("... starting server"); + + 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); + toGigi.flush(); + + final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream())); + String line; + while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) { + } + new Thread() { + + @Override + public void run() { + String line; + try { + while ((line = br.readLine()) != null) { + System.err.println(line); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + }.start(); + if (line == null) { + throw new Error("Server startup failed"); + } + ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473)); + SimpleSigner.runSigner(); + } catch (IOException e) { + throw new Error(e); + } catch (ClassNotFoundException e1) { + e1.printStackTrace(); + } catch (SQLException e1) { + e1.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + + private static Properties generateMainProps() { + Properties mainProps = new Properties(); + mainProps.setProperty("host", "127.0.0.1"); + mainProps.setProperty("name.secure", testProps.getProperty("name.secure")); + mainProps.setProperty("name.www", testProps.getProperty("name.www")); + mainProps.setProperty("name.static", testProps.getProperty("name.static")); + + mainProps.setProperty("port", testProps.getProperty("serverPort")); + mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider"); + mainProps.setProperty("emailProvider.port", "8473"); + 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")); + return mainProps; + } + + @AfterClass + public static void tearDownServer() { + String type = testProps.getProperty("type"); + ter.destroy(); + if (type.equals("local")) { + return; + } + gigi.destroy(); + try { + SimpleSigner.stopSigner(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + @After + public void removeMails() { + ter.reset(); + } + + public TestMail waitForMail() { + try { + return ter.recieve(); + } catch (InterruptedException e) { + throw new Error(e); + } + } + + public static TestEmailReciever getMailReciever() { + return ter; + } + + public String runRegister(String param) throws IOException { + URL regist = new URL("https://" + getServerName() + registerService); + HttpURLConnection uc = (HttpURLConnection) regist.openConnection(); + HttpURLConnection csrfConn = (HttpURLConnection) regist.openConnection(); + + String headerField = csrfConn.getHeaderField("Set-Cookie"); + headerField = stripCookie(headerField); + + String csrf = getCSRF(csrfConn); + uc.addRequestProperty("Cookie", headerField); + uc.setDoOutput(true); + uc.getOutputStream().write((param + "&csrf=" + csrf).getBytes()); + String d = IOUtils.readURL(uc); + return d; + } + + public String fetchStartErrorMessage(String d) throws IOException { + String formFail = "
    "; + int idx = d.indexOf(formFail); + if (idx == -1) { + return null; + } + String startError = d.substring(idx + formFail.length(), idx + 100).trim(); + return startError; + } + + 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 data = fetchStartErrorMessage(runRegister(query)); + assertTrue(data, data.startsWith("
    ")); + } catch (UnsupportedEncodingException e) { + throw new Error(e); + } catch (IOException e) { + throw new Error(e); + } + } + + 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=?"); + ps.setString(1, email); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + return rs.getInt(1); + } + throw new Error(); + } catch (InterruptedException e) { + throw new Error(e); + } catch (IOException e) { + throw new Error(e); + } catch (SQLException e) { + throw new Error(e); + } + } + + /** + * Creates a new user with 100 Assurance points given by an (invalid) + * assurance. + * + * @param firstName + * the first name + * @param lastName + * the last name + * @param email + * the email + * @param password + * the password + * @return a new userid. + */ + 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`=?"); + ps.setInt(1, uid); + ps.setInt(2, 0); + ps.execute(); + ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'"); + ps.setInt(1, uid); + ps.setInt(2, uid); + ps.execute(); + + } catch (SQLException e) { + throw new Error(e); + } + return uid; + } + + static int count = 0; + + public static String createUniqueName() { + return "test" + System.currentTimeMillis() + "a" + (count++); + } + + private String stripCookie(String headerField) { + return headerField.substring(0, headerField.indexOf(';')); + } + + public static final String SECURE_REFERENCE = "/account/certs/email"; + + public boolean isLoggedin(String cookie) throws IOException { + URL u = new URL("https://" + getServerName() + SECURE_REFERENCE); + HttpURLConnection huc = (HttpURLConnection) u.openConnection(); + huc.addRequestProperty("Cookie", cookie); + return huc.getResponseCode() == 200; + } + + 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"); + os.write(data.getBytes()); + os.flush(); + String headerField = huc.getHeaderField("Set-Cookie"); + return stripCookie(headerField); + } + + public String login(final PrivateKey pk, final X509Certificate ce) throws NoSuchAlgorithmException, KeyManagementException, IOException, MalformedURLException { + + HttpURLConnection connection = (HttpURLConnection) new URL("https://" + getServerName().replaceFirst("^www.", "secure.") + "/login").openConnection(); + authenticateClientCert(pk, ce, connection); + if (connection.getResponseCode() == 302) { + assertEquals("https://" + getServerName().replaceFirst("^www.", "secure.").replaceFirst(":443$", "") + "/", connection.getHeaderField("Location").replaceFirst(":443$", "")); + return stripCookie(connection.getHeaderField("Set-Cookie")); + } else { + return null; + } + } + + public void authenticateClientCert(final PrivateKey pk, final X509Certificate ce, HttpURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException { + KeyManager km = new X509KeyManager() { + + @Override + public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) { + return "client"; + } + + @Override + public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) { + return null; + } + + @Override + public X509Certificate[] getCertificateChain(String arg0) { + return new X509Certificate[] { + ce + }; + } + + @Override + public String[] getClientAliases(String arg0, Principal[] arg1) { + return new String[] { + "client" + }; + } + + @Override + public PrivateKey getPrivateKey(String arg0) { + if (arg0.equals("client")) { + return pk; + } + return null; + } + + @Override + public String[] getServerAliases(String arg0, Principal[] arg1) { + return new String[] { + "client" + }; + } + }; + SSLContext sc = SSLContext.getInstance("TLS"); + sc.init(new KeyManager[] { + km + }, null, null); + if (connection instanceof HttpsURLConnection) { + ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory()); + } + } + + public String getCSRF(URLConnection u) throws IOException { + return getCSRF(u, 0); + } + + public String getCSRF(URLConnection u, int formIndex) throws IOException { + String content = IOUtils.readURL(u); + Pattern p = Pattern.compile(""); + Matcher m = p.matcher(content); + for (int i = 0; i < formIndex + 1; i++) { + if ( !m.find()) { + throw new Error("No CSRF Token"); + } + } + return m.group(1); + } + + public static String[] generateCSR(String dn) throws IOException { + Process p = Runtime.getRuntime().exec(new String[] { + "openssl", "req", "-newkey", "rsa:1024", "-nodes", "-subj", dn, "-config", "keys/selfsign.config" + }); + String csr = IOUtils.readURL(new InputStreamReader(p.getInputStream())); + + String[] parts = csr.split("(?<=-----)\n(?=-----)"); + if (parts.length != 2) { + System.err.println(IOUtils.readURL(new InputStreamReader(p.getErrorStream()))); + throw new Error(); + } + return parts; + } + + public String executeBasicWebInteraction(String cookie, String path, String query) throws MalformedURLException, UnsupportedEncodingException, IOException { + return executeBasicWebInteraction(cookie, path, query, 0); + } + + public String executeBasicWebInteraction(String cookie, String path, String query, int formIndex) throws IOException, MalformedURLException, UnsupportedEncodingException { + URLConnection uc = new URL("https://" + getServerName() + path).openConnection(); + uc.addRequestProperty("Cookie", cookie); + String csrf = getCSRF(uc, formIndex); + + uc = new URL("https://" + getServerName() + path).openConnection(); + uc.addRequestProperty("Cookie", cookie); + uc.setDoOutput(true); + OutputStream os = uc.getOutputStream(); + os.write(("csrf=" + URLEncoder.encode(csrf, "UTF-8") + "&" // + + query// + ).getBytes()); + os.flush(); + String error = fetchStartErrorMessage(IOUtils.readURL(uc)); + return error; + } + + public static EmailAddress createVerifiedEmail(User u) throws InterruptedException, GigiApiException { + EmailAddress adrr = new EmailAddress(createUniqueName() + "test@test.tld", u); + adrr.insert(Language.getInstance("en")); + TestMail testMail = getMailReciever().recieve(); + assertTrue(adrr.getAddress().equals(testMail.getTo())); + String hash = testMail.extractLink().substring(testMail.extractLink().lastIndexOf('=') + 1); + adrr.verify(hash); + getMailReciever().clearMails(); + return adrr; + } } diff --git a/tests/org/cacert/gigi/testUtils/PemKey.java b/tests/org/cacert/gigi/testUtils/PemKey.java index 170c00a1..c790dd72 100644 --- a/tests/org/cacert/gigi/testUtils/PemKey.java +++ b/tests/org/cacert/gigi/testUtils/PemKey.java @@ -10,29 +10,31 @@ import java.security.spec.PKCS8EncodedKeySpec; import java.util.Base64; public class PemKey { - public static PrivateKey parsePEMPrivateKey(String privKeyPEM) throws NoSuchAlgorithmException, - InvalidKeySpecException { - if (privKeyPEM.startsWith("-----BEGIN RSA PRIVATE KEY-----")) { - // key is pkcs1 convert to p8 - try { - Process p = Runtime.getRuntime().exec(new String[] { "openssl", "pkcs8", "-topk8", "-nocrypt" }); - p.getOutputStream().write(privKeyPEM.getBytes()); - p.getOutputStream().close(); - privKeyPEM = IOUtils.readURL(new InputStreamReader(p.getInputStream())); - } catch (IOException e) { - e.printStackTrace(); - } - } - privKeyPEM = privKeyPEM.replaceAll("-----BEGIN PRIVATE KEY-----", "").replace("\n", ""); - // Remove the first and last lines - privKeyPEM = privKeyPEM.replaceAll("-----END PRIVATE KEY-----", ""); - // Base64 decode the data - byte[] encoded = Base64.getDecoder().decode(privKeyPEM); - // PKCS8 decode the encoded RSA private key - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded); - KeyFactory kf = KeyFactory.getInstance("RSA"); - PrivateKey privKey = kf.generatePrivate(keySpec); - return privKey; - } + public static PrivateKey parsePEMPrivateKey(String privKeyPEM) throws NoSuchAlgorithmException, InvalidKeySpecException { + if (privKeyPEM.startsWith("-----BEGIN RSA PRIVATE KEY-----")) { + // key is pkcs1 convert to p8 + try { + Process p = Runtime.getRuntime().exec(new String[] { + "openssl", "pkcs8", "-topk8", "-nocrypt" + }); + p.getOutputStream().write(privKeyPEM.getBytes()); + p.getOutputStream().close(); + privKeyPEM = IOUtils.readURL(new InputStreamReader(p.getInputStream())); + } catch (IOException e) { + e.printStackTrace(); + } + } + privKeyPEM = privKeyPEM.replaceAll("-----BEGIN PRIVATE KEY-----", "").replace("\n", ""); + // Remove the first and last lines + privKeyPEM = privKeyPEM.replaceAll("-----END PRIVATE KEY-----", ""); + // Base64 decode the data + byte[] encoded = Base64.getDecoder().decode(privKeyPEM); + + // PKCS8 decode the encoded RSA private key + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded); + KeyFactory kf = KeyFactory.getInstance("RSA"); + PrivateKey privKey = kf.generatePrivate(keySpec); + return privKey; + } } diff --git a/tests/org/cacert/gigi/testUtils/TestEmailReciever.java b/tests/org/cacert/gigi/testUtils/TestEmailReciever.java index 93cd7e45..40b4e031 100644 --- a/tests/org/cacert/gigi/testUtils/TestEmailReciever.java +++ b/tests/org/cacert/gigi/testUtils/TestEmailReciever.java @@ -13,150 +13,157 @@ import java.util.regex.Pattern; import org.cacert.gigi.email.EmailProvider; public class TestEmailReciever extends EmailProvider implements Runnable { - public class 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()); - m.find(); - return m.group(0); - } - - } - - private Socket s; - private DataInputStream dis; - private DataOutputStream dos; - - public TestEmailReciever(SocketAddress target) throws IOException { - s = new Socket(); - s.connect(target); - s.setKeepAlive(true); - s.setSoTimeout(1000 * 60 * 60); - dis = new DataInputStream(s.getInputStream()); - dos = new DataOutputStream(s.getOutputStream()); - new Thread(this).start(); - setInstance(this); - } - - LinkedBlockingQueue mails = new LinkedBlockingQueue(); - - public TestMail recieve() throws InterruptedException { - return mails.poll(5, TimeUnit.SECONDS); - } - - @Override - public void run() { - try { - while (true) { - String type = dis.readUTF(); - if (type.equals("mail")) { - String to = dis.readUTF(); - String subject = dis.readUTF(); - String message = dis.readUTF(); - String from = dis.readUTF(); - String replyto = dis.readUTF(); - mails.add(new TestMail(to, subject, message, from, replyto)); - } else if (type.equals("challengeAddrBox")) { - String email = dis.readUTF(); - dos.writeUTF(quickEmailCheck(email)); - dos.flush(); - } else if (type.equals("ping")) { - } else { - System.err.println("Unknown type: " + type); - } - } - } catch (IOException e) { - if (!closed) { - e.printStackTrace(); - } - } - - } - - private String quickEmailCheck(String email) throws IOException { - if (approveRegex.matcher(email).matches()) { - return "OK"; - } else { - return error; - } - } - - String error = "FAIL"; - - public void setEmailCheckError(String error) { - this.error = error; - } - - Pattern approveRegex = Pattern.compile(".*"); - - public void setApproveRegex(Pattern approveRegex) { - this.approveRegex = approveRegex; - } - - public void clearMails() { - mails.clear(); - } - - public void reset() { - clearMails(); - error = "FAIL"; - approveRegex = Pattern.compile(".*"); - } - - boolean closed = false; - - public void destroy() { - try { - closed = true; - s.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public String checkEmailServer(int forUid, String address) throws IOException { - return quickEmailCheck(address); - } - - @Override - public void sendmail(String to, String subject, String message, String from, String replyto, String toname, - String fromname, String errorsto, boolean extra) throws IOException { - mails.add(new TestMail(to, subject, message, from, replyto)); - } + + public class 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()); + m.find(); + return m.group(0); + } + + } + + private Socket s; + + private DataInputStream dis; + + private DataOutputStream dos; + + public TestEmailReciever(SocketAddress target) throws IOException { + s = new Socket(); + s.connect(target); + s.setKeepAlive(true); + s.setSoTimeout(1000 * 60 * 60); + dis = new DataInputStream(s.getInputStream()); + dos = new DataOutputStream(s.getOutputStream()); + new Thread(this).start(); + setInstance(this); + } + + LinkedBlockingQueue mails = new LinkedBlockingQueue(); + + public TestMail recieve() throws InterruptedException { + return mails.poll(5, TimeUnit.SECONDS); + } + + @Override + public void run() { + try { + while (true) { + String type = dis.readUTF(); + if (type.equals("mail")) { + String to = dis.readUTF(); + String subject = dis.readUTF(); + String message = dis.readUTF(); + String from = dis.readUTF(); + String replyto = dis.readUTF(); + mails.add(new TestMail(to, subject, message, from, replyto)); + } else if (type.equals("challengeAddrBox")) { + String email = dis.readUTF(); + dos.writeUTF(quickEmailCheck(email)); + dos.flush(); + } else if (type.equals("ping")) { + } else { + System.err.println("Unknown type: " + type); + } + } + } catch (IOException e) { + if ( !closed) { + e.printStackTrace(); + } + } + + } + + private String quickEmailCheck(String email) throws IOException { + if (approveRegex.matcher(email).matches()) { + return "OK"; + } else { + return error; + } + } + + String error = "FAIL"; + + public void setEmailCheckError(String error) { + this.error = error; + } + + Pattern approveRegex = Pattern.compile(".*"); + + public void setApproveRegex(Pattern approveRegex) { + this.approveRegex = approveRegex; + } + + public void clearMails() { + mails.clear(); + } + + public void reset() { + clearMails(); + error = "FAIL"; + approveRegex = Pattern.compile(".*"); + } + + boolean closed = false; + + public void destroy() { + try { + closed = true; + s.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public String checkEmailServer(int forUid, String address) throws IOException { + return quickEmailCheck(address); + } + + @Override + public void sendmail(String to, String subject, String message, String from, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException { + mails.add(new TestMail(to, subject, message, from, replyto)); + } } diff --git a/tests/org/cacert/gigi/util/TestHTMLEncoder.java b/tests/org/cacert/gigi/util/TestHTMLEncoder.java index f7c21ab3..5d3a2aed 100644 --- a/tests/org/cacert/gigi/util/TestHTMLEncoder.java +++ b/tests/org/cacert/gigi/util/TestHTMLEncoder.java @@ -6,23 +6,23 @@ import org.junit.Test; public class TestHTMLEncoder { - @Test - public void testEncodeSimpleString() { - assertEquals("1234_ä", HTMLEncoder.encodeHTML("1234_ä")); - } + @Test + public void testEncodeSimpleString() { + assertEquals("1234_ä", HTMLEncoder.encodeHTML("1234_ä")); + } - @Test - public void testEncodeQuotes() { - assertEquals("\\"_ä.", HTMLEncoder.encodeHTML("\\\"_ä.")); - } + @Test + public void testEncodeQuotes() { + assertEquals("\\"_ä.", HTMLEncoder.encodeHTML("\\\"_ä.")); + } - @Test - public void testEncodeTagString() { - assertEquals("<td class="&amp;">", HTMLEncoder.encodeHTML("")); - } + @Test + public void testEncodeTagString() { + assertEquals("<td class="&amp;">", HTMLEncoder.encodeHTML("")); + } - @Test - public void testEncodeSingleQuoteString() { - assertEquals("'&#39;", 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 d3570e52..9797a03e 100644 --- a/tests/org/cacert/gigi/util/TestNotary.java +++ b/tests/org/cacert/gigi/util/TestNotary.java @@ -12,56 +12,50 @@ import org.junit.Test; import static org.junit.Assert.*; public class TestNotary extends ManagedTest { - @Test - 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", TEST_PASSWORD); - users[i] = new User(id); - } - User assurer = new User(createAssuranceUser("fn", "ln", createUniqueName() + "@email.org", TEST_PASSWORD)); - 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 }; - 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")); - } - - assertEquals(35, assurer.getMaxAssurePoints()); - - assertEquals(2 + 60, assurer.getExperiencePoints()); - - } - - @Test - 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", TEST_PASSWORD); - users[i] = new User(id); - } - int id = createAssuranceUser("fn", "ln", createUniqueName() + "@email.org", TEST_PASSWORD); - 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")); - } - } + @Test + 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", TEST_PASSWORD); + users[i] = new User(id); + } + User assurer = new User(createAssuranceUser("fn", "ln", createUniqueName() + "@email.org", TEST_PASSWORD)); + 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 + }; + + 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")); + } + + assertEquals(35, assurer.getMaxAssurePoints()); + + assertEquals(2 + 60, assurer.getExperiencePoints()); + + } + + @Test + 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", TEST_PASSWORD); + users[i] = new User(id); + } + int id = createAssuranceUser("fn", "ln", createUniqueName() + "@email.org", TEST_PASSWORD); + 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")); + } + } } diff --git a/tests/org/cacert/gigi/util/TestPasswordHash.java b/tests/org/cacert/gigi/util/TestPasswordHash.java index 21f5f8bd..2e323f78 100644 --- a/tests/org/cacert/gigi/util/TestPasswordHash.java +++ b/tests/org/cacert/gigi/util/TestPasswordHash.java @@ -4,17 +4,18 @@ import org.junit.Test; import static org.junit.Assert.*; public class TestPasswordHash { - @Test - public void testVerify() { - 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ä"))); - } - @Test - public void testVerifyNegative() { - assertFalse(PasswordHash.verifyHash("b", PasswordHash.hash("a"))); - assertFalse(PasswordHash.verifyHash("ae", PasswordHash.hash("auhlcb4 9x,IUQẞ&lvrvä"))); - } + @Test + public void testVerify() { + 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ä"))); + } + + @Test + public void testVerifyNegative() { + assertFalse(PasswordHash.verifyHash("b", PasswordHash.hash("a"))); + 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 f57e71af..e6cac695 100644 --- a/tests/org/cacert/gigi/util/TestPasswordStrengthChecker.java +++ b/tests/org/cacert/gigi/util/TestPasswordStrengthChecker.java @@ -5,69 +5,70 @@ import org.junit.Test; import static org.junit.Assert.*; public class TestPasswordStrengthChecker { - User u; - public TestPasswordStrengthChecker() { - u = new User(); - u.setFname("fname"); - u.setLname("lname"); - u.setMname("mname"); - u.setEmail("email"); - u.setSuffix("suffix"); - } + User u; - @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)); - } + public TestPasswordStrengthChecker() { + u = new User(); + u.setFname("fname"); + u.setLname("lname"); + u.setMname("mname"); + u.setEmail("email"); + u.setSuffix("suffix"); + } - @Test - public void testPasswordNonASCII() { - assertEquals(2, PasswordStrengthChecker.checkpw("0ä", u)); - assertEquals(3, PasswordStrengthChecker.checkpw("0aä", u)); - assertEquals(3, PasswordStrengthChecker.checkpw("0azä", u)); - assertEquals(3, PasswordStrengthChecker.checkpw("0az.ä", u)); - } + @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)); + } - @Test - public void testPasswordCharTypes() { - assertEquals(1, PasswordStrengthChecker.checkpw("0", u)); - assertEquals(2, PasswordStrengthChecker.checkpw("0a", u)); - assertEquals(2, PasswordStrengthChecker.checkpw("0az", u)); - assertEquals(3, PasswordStrengthChecker.checkpw("0azZ", u)); - assertEquals(4, PasswordStrengthChecker.checkpw("0a zZ", u)); - assertEquals(5, PasswordStrengthChecker.checkpw("0a. zZ", u)); + @Test + public void testPasswordNonASCII() { + assertEquals(2, PasswordStrengthChecker.checkpw("0ä", u)); + assertEquals(3, PasswordStrengthChecker.checkpw("0aä", u)); + assertEquals(3, PasswordStrengthChecker.checkpw("0azä", u)); + assertEquals(3, PasswordStrengthChecker.checkpw("0az.ä", u)); + } - assertEquals(1, PasswordStrengthChecker.checkpw(".", u)); - assertEquals(1, PasswordStrengthChecker.checkpw(" ", u)); - assertEquals(1, PasswordStrengthChecker.checkpw("b", u)); - assertEquals(1, PasswordStrengthChecker.checkpw("Z", u)); + @Test + public void testPasswordCharTypes() { + assertEquals(1, PasswordStrengthChecker.checkpw("0", u)); + assertEquals(2, PasswordStrengthChecker.checkpw("0a", u)); + assertEquals(2, PasswordStrengthChecker.checkpw("0az", u)); + assertEquals(3, PasswordStrengthChecker.checkpw("0azZ", u)); + assertEquals(4, PasswordStrengthChecker.checkpw("0a zZ", u)); + assertEquals(5, PasswordStrengthChecker.checkpw("0a. zZ", u)); - assertEquals(2, PasswordStrengthChecker.checkpw("0.", u)); - assertEquals(2, PasswordStrengthChecker.checkpw("0 ", u)); - assertEquals(2, PasswordStrengthChecker.checkpw("0a", u)); - assertEquals(2, PasswordStrengthChecker.checkpw("0Z", u)); + assertEquals(1, PasswordStrengthChecker.checkpw(".", u)); + assertEquals(1, PasswordStrengthChecker.checkpw(" ", u)); + assertEquals(1, PasswordStrengthChecker.checkpw("b", u)); + assertEquals(1, PasswordStrengthChecker.checkpw("Z", u)); - assertEquals(2, PasswordStrengthChecker.checkpw(" .", u)); - assertEquals(2, PasswordStrengthChecker.checkpw(" a", u)); - assertEquals(2, PasswordStrengthChecker.checkpw(" Z", u)); + assertEquals(2, PasswordStrengthChecker.checkpw("0.", u)); + assertEquals(2, PasswordStrengthChecker.checkpw("0 ", u)); + assertEquals(2, PasswordStrengthChecker.checkpw("0a", u)); + assertEquals(2, PasswordStrengthChecker.checkpw("0Z", u)); - } + assertEquals(2, PasswordStrengthChecker.checkpw(" .", u)); + assertEquals(2, PasswordStrengthChecker.checkpw(" a", u)); + assertEquals(2, PasswordStrengthChecker.checkpw(" Z", u)); - @Test - public void testPasswordContains() { - assertEquals(-1, PasswordStrengthChecker.checkpw("fnamea", u)); - assertEquals(-5, PasswordStrengthChecker.checkpw("na", u)); - assertEquals(0, PasswordStrengthChecker.checkpw("1lname", u)); - assertEquals(0, PasswordStrengthChecker.checkpw("1email", u)); - assertEquals(-1, PasswordStrengthChecker.checkpw("mai", u)); - assertEquals(-1, PasswordStrengthChecker.checkpw("suff", u)); - assertEquals(0, PasswordStrengthChecker.checkpw("1suffix", u)); + } - } + @Test + public void testPasswordContains() { + assertEquals( -1, PasswordStrengthChecker.checkpw("fnamea", u)); + assertEquals( -5, PasswordStrengthChecker.checkpw("na", u)); + assertEquals(0, PasswordStrengthChecker.checkpw("1lname", u)); + assertEquals(0, PasswordStrengthChecker.checkpw("1email", u)); + assertEquals( -1, PasswordStrengthChecker.checkpw("mai", u)); + assertEquals( -1, PasswordStrengthChecker.checkpw("suff", u)); + assertEquals(0, PasswordStrengthChecker.checkpw("1suffix", u)); + + } } diff --git a/util/org/cacert/gigi/util/DatabaseManager.java b/util/org/cacert/gigi/util/DatabaseManager.java index 47108395..9fe3f5fb 100644 --- a/util/org/cacert/gigi/util/DatabaseManager.java +++ b/util/org/cacert/gigi/util/DatabaseManager.java @@ -11,44 +11,46 @@ import java.sql.Statement; import java.util.Properties; 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 { - 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") }; - } - if (args.length < 4) { - System.err.println("Usage: com.mysql.jdbc.Driver jdbc:mysql://localhost/cacert user password"); - return; - } - run(args); - } + public static String readFile(File f) throws IOException { + return new String(Files.readAllBytes(f.toPath())); + } - public static void run(String[] args) throws ClassNotFoundException, SQLException, IOException { - Class.forName(args[0]); - 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"); - if (localData.exists()) { - addFile(stmt, localData); - } - stmt.executeBatch(); - stmt.close(); - } + 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") + }; + } + if (args.length < 4) { + System.err.println("Usage: com.mysql.jdbc.Driver jdbc:mysql://localhost/cacert user password"); + return; + } + run(args); + } - private static void addFile(Statement stmt, File f) throws IOException, SQLException { - String sql = readFile(f); - String[] stmts = sql.split(";"); - for (String string : stmts) { - if (!string.trim().equals("")) { - stmt.addBatch(string); - } - } - } + public static void run(String[] args) throws ClassNotFoundException, SQLException, IOException { + Class.forName(args[0]); + 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"); + if (localData.exists()) { + addFile(stmt, localData); + } + stmt.executeBatch(); + stmt.close(); + } + + private static void addFile(Statement stmt, File f) throws IOException, SQLException { + String sql = readFile(f); + String[] stmts = sql.split(";"); + for (String string : stmts) { + if ( !string.trim().equals("")) { + stmt.addBatch(string); + } + } + } } diff --git a/util/org/cacert/gigi/util/FetchLocales.java b/util/org/cacert/gigi/util/FetchLocales.java index 0c936b9c..4c93021e 100644 --- a/util/org/cacert/gigi/util/FetchLocales.java +++ b/util/org/cacert/gigi/util/FetchLocales.java @@ -22,94 +22,98 @@ import org.w3c.dom.Element; 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 { - System.out.println("downloading locales ..."); - File locale = new File("locale"); - locale.mkdir(); + public static final String DOWNLOAD_SERVER = "translations.cacert.org"; - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - DocumentBuilder db = dbf.newDocumentBuilder(); - for (String lang : AUTO_LANGS) { - Document doc = db.newDocument(); - doc.appendChild(doc.createElement("translations")); - URL fetch = new URL(PO_URL_TEMPLATE.replace("%", lang)); - URLConnection uc = fetch.openConnection(); - Scanner sc = new Scanner(uc.getInputStream()); - String s = readLine(sc); - StringBuffer contents = new StringBuffer(); - String id = ""; - while (s != null) { - if (s.startsWith("msgid")) { - contents.delete(0, contents.length()); - s = readString(s, sc, contents); - id = contents.toString(); - continue; - } else if (s.startsWith("msgstr")) { - contents.delete(0, contents.length()); - // System.out.println("msgstr"); - s = readString(s, sc, contents); - String msg = contents.toString().replace("\\\"", "\"").replace("\\n", "\n"); - insertTranslation(doc, id, msg); - } else if (s.startsWith("#")) { - // System.out.println(s); - } else if (s.equals("") || s.equals("\r")) { + public static final String PO_URL_TEMPLATE = "http://" + DOWNLOAD_SERVER + "/export/cacert/%/messages.po"; - } else { - System.out.println("unknown line: " + s); - } - s = readLine(sc); - } - TransformerFactory tFactory = TransformerFactory.newInstance(); - Transformer transformer = tFactory.newTransformer(); + 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" + }; - DOMSource source = new DOMSource(doc); - 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.transform(source, result); - fos.close(); - } - System.out.println("Done."); - } + public static void main(String[] args) throws IOException, ParserConfigurationException, TransformerException { + System.out.println("downloading locales ..."); + File locale = new File("locale"); + locale.mkdir(); - private static String readLine(Scanner sc) { - String line = sc.findWithinHorizon("[^\n]*\n", 0); - if (line == null) { - return null; - } - return line.substring(0, line.length() - 1); - } + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + for (String lang : AUTO_LANGS) { + Document doc = db.newDocument(); + doc.appendChild(doc.createElement("translations")); + URL fetch = new URL(PO_URL_TEMPLATE.replace("%", lang)); + URLConnection uc = fetch.openConnection(); + Scanner sc = new Scanner(uc.getInputStream()); + String s = readLine(sc); + StringBuffer contents = new StringBuffer(); + String id = ""; + while (s != null) { + if (s.startsWith("msgid")) { + contents.delete(0, contents.length()); + s = readString(s, sc, contents); + id = contents.toString(); + continue; + } else if (s.startsWith("msgstr")) { + contents.delete(0, contents.length()); + // System.out.println("msgstr"); + s = readString(s, sc, contents); + String msg = contents.toString().replace("\\\"", "\"").replace("\\n", "\n"); + insertTranslation(doc, id, msg); + } else if (s.startsWith("#")) { + // System.out.println(s); + } else if (s.equals("") || s.equals("\r")) { - private static void insertTranslation(Document doc, String id, String msg) { - Node idN = doc.createTextNode(id); - Node textN = doc.createTextNode(msg); - Element tr = doc.createElement("translation"); - Element e = doc.createElement("id"); - e.appendChild(idN); - tr.appendChild(e); - e = doc.createElement("msg"); - e.appendChild(textN); - tr.appendChild(e); - doc.getDocumentElement().appendChild(tr); - } + } else { + System.out.println("unknown line: " + s); + } + s = readLine(sc); + } + TransformerFactory tFactory = TransformerFactory.newInstance(); + Transformer transformer = tFactory.newTransformer(); - 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; - while ((s = readLine(sc)) != null) { - if (!s.startsWith("\"")) { - break; - } - contents.append(s.substring(1, s.length() - 1)); - } - return s; - } + DOMSource source = new DOMSource(doc); + 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.transform(source, result); + fos.close(); + } + System.out.println("Done."); + } + + private static String readLine(Scanner sc) { + String line = sc.findWithinHorizon("[^\n]*\n", 0); + if (line == null) { + return null; + } + 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); + Element tr = doc.createElement("translation"); + Element e = doc.createElement("id"); + e.appendChild(idN); + tr.appendChild(e); + e = doc.createElement("msg"); + e.appendChild(textN); + tr.appendChild(e); + doc.getDocumentElement().appendChild(tr); + } + + 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; + while ((s = readLine(sc)) != null) { + if ( !s.startsWith("\"")) { + break; + } + contents.append(s.substring(1, s.length() - 1)); + } + return s; + } } diff --git a/util/org/cacert/gigi/util/SimpleSigner.java b/util/org/cacert/gigi/util/SimpleSigner.java index c471586c..3290298b 100644 --- a/util/org/cacert/gigi/util/SimpleSigner.java +++ b/util/org/cacert/gigi/util/SimpleSigner.java @@ -21,196 +21,215 @@ import org.cacert.gigi.Certificate.CSRType; import org.cacert.gigi.database.DatabaseConnection; public class SimpleSigner { - private static PreparedStatement warnMail; - private static PreparedStatement updateMail; - private static PreparedStatement readyMail; - private static PreparedStatement revoke; - private static PreparedStatement revokeCompleted; - private static PreparedStatement finishJob; - private static boolean running = true; - private static Thread runner; - - public static void main(String[] args) throws IOException, SQLException, InterruptedException { - Properties p = new Properties(); - p.load(new FileReader("config/gigi.properties")); - DatabaseConnection.init(p); - - runSigner(); - } - - public synchronized static void stopSigner() throws InterruptedException { - if (runner == null) { - throw new IllegalStateException("already stopped"); - } - running = false; - runner.interrupt(); - runner.join(); - runner = null; - } - - public synchronized static void runSigner() throws SQLException, IOException, InterruptedException { - if (runner != null) { - throw new IllegalStateException("already running"); - } - running = true; - readyMail = DatabaseConnection - .getInstance() - .prepare( - "SELECT emailcerts.id,emailcerts.csr_name,emailcerts.subject, jobs.id,csr_type FROM jobs INNER JOIN emailcerts ON emailcerts.id=jobs.targetId" - + " WHERE jobs.state='open'"// - + " AND task='sign'"); - - updateMail = DatabaseConnection.getInstance().prepare( - "UPDATE emailcerts SET crt_name=?," + " created=NOW(), serial=? WHERE id=?"); - warnMail = DatabaseConnection.getInstance().prepare( - "UPDATE jobs SET warning=warning+1, state=IF(warning<3, 'open','error') WHERE id=?"); - - revoke = DatabaseConnection.getInstance().prepare( - "SELECT emailcerts.id, emailcerts.csr_name,jobs.id FROM jobs INNER JOIN emailcerts ON jobs.targetId=emailcerts.id" - + " WHERE jobs.state='open' AND task='revoke'"); - revokeCompleted = DatabaseConnection.getInstance().prepare("UPDATE emailcerts SET revoked=NOW() WHERE id=?"); - - finishJob = DatabaseConnection.getInstance().prepare("UPDATE jobs SET state='done' WHERE id=?"); - - runner = new Thread() { - @Override - public void run() { - work(); - } - - }; - runner.start(); - } - - private static void work() { - try { - gencrl(); - } catch (IOException e2) { - e2.printStackTrace(); - } catch (InterruptedException e2) { - e2.printStackTrace(); - } - while (running) { - try { - signCertificates(); - revokeCertificates(); - Thread.sleep(5000); - } catch (IOException e) { - e.printStackTrace(); - } catch (SQLException e) { - e.printStackTrace(); - } catch (InterruptedException e1) { - } - } - } - - private static void revokeCertificates() throws SQLException, IOException, InterruptedException { - ResultSet rs = revoke.executeQuery(); - boolean worked = false; - while (rs.next()) { - int id = rs.getInt(1); - File crt = KeyStorage.locateCrt(id); - String[] call = new String[] { "openssl", "ca",// - "-cert", "testca.crt",// - "-keyfile", "testca.key",// - "-revoke", "../" + crt.getPath(),// - "-batch",// - "-config", "selfsign.config" - - }; - Process p1 = Runtime.getRuntime().exec(call, null, new File("keys")); - System.out.println("revoking: " + crt.getPath()); - if (p1.waitFor() == 0) { - worked = true; - revokeCompleted.setInt(1, id); - revokeCompleted.execute(); - finishJob.setInt(1, rs.getInt(3)); - finishJob.execute(); - } else { - System.out.println("Failed"); - } - } - if (worked) { - gencrl(); - } - } - - private static void gencrl() throws IOException, InterruptedException { - String[] call = new String[] { "openssl", "ca",// - "-cert", "testca.crt",// - "-keyfile", "testca.key",// - "-gencrl",// - "-crlhours",// - "12",// - "-out", "testca.crl",// - "-config", "selfsign.config" - - }; - Process p1 = Runtime.getRuntime().exec(call, null, new File("keys")); - if (p1.waitFor() != 0) { - System.out.println("Error while generating crl."); - } - } - - private static void signCertificates() throws SQLException, IOException, InterruptedException { - ResultSet rs = readyMail.executeQuery(); - while (rs.next()) { - String csrname = rs.getString(2); - System.out.println("sign: " + csrname); - int id = rs.getInt(1); - String csrType = rs.getString(5); - CSRType ct = CSRType.valueOf(csrType); - File crt = KeyStorage.locateCrt(id); - String[] call = new String[] { "openssl", "ca",// - "-in", "../" + csrname,// - "-cert", "testca.crt",// - "-keyfile", "testca.key",// - "-out", "../" + crt.getPath(),// - "-days", "356",// - "-batch",// - "-subj", rs.getString(3),// - "-config", "selfsign.config"// - - }; - if (ct == CSRType.SPKAC) { - call[2] = "-spkac"; - } - Process p1 = Runtime.getRuntime().exec(call, null, new File("keys")); - - int waitFor = p1.waitFor(); - if (waitFor == 0) { - try (InputStream is = new FileInputStream(crt)) { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - X509Certificate crtp = (X509Certificate) cf.generateCertificate(is); - BigInteger serial = crtp.getSerialNumber(); - updateMail.setString(1, crt.getPath()); - updateMail.setString(2, serial.toString(16)); - updateMail.setInt(3, id); - updateMail.execute(); - - finishJob.setInt(1, rs.getInt(4)); - finishJob.execute(); - System.out.println("signed: " + id); - continue; - } catch (GeneralSecurityException e) { - e.printStackTrace(); - } - System.out.println("ERROR Afterwards: " + id); - warnMail.setInt(1, rs.getInt(4)); - warnMail.execute(); - } else { - BufferedReader br = new BufferedReader(new InputStreamReader(p1.getErrorStream())); - String s; - while ((s = br.readLine()) != null) { - System.out.println(s); - } - System.out.println(Arrays.toString(call)); - System.out.println("ERROR: " + id); - warnMail.setInt(1, rs.getInt(4)); - warnMail.execute(); - } - - } - rs.close(); - } + + private static PreparedStatement warnMail; + + private static PreparedStatement updateMail; + + private static PreparedStatement readyMail; + + private static PreparedStatement revoke; + + private static PreparedStatement revokeCompleted; + + private static PreparedStatement finishJob; + + private static boolean running = true; + + private static Thread runner; + + public static void main(String[] args) throws IOException, SQLException, InterruptedException { + Properties p = new Properties(); + p.load(new FileReader("config/gigi.properties")); + DatabaseConnection.init(p); + + runSigner(); + } + + public synchronized static void stopSigner() throws InterruptedException { + if (runner == null) { + throw new IllegalStateException("already stopped"); + } + running = false; + runner.interrupt(); + runner.join(); + runner = null; + } + + public synchronized static void runSigner() throws SQLException, IOException, InterruptedException { + if (runner != null) { + throw new IllegalStateException("already running"); + } + running = true; + readyMail = DatabaseConnection.getInstance().prepare("SELECT emailcerts.id,emailcerts.csr_name,emailcerts.subject, jobs.id,csr_type FROM jobs INNER JOIN emailcerts ON emailcerts.id=jobs.targetId" + " WHERE jobs.state='open'"// + + " AND task='sign'"); + + updateMail = DatabaseConnection.getInstance().prepare("UPDATE emailcerts SET crt_name=?," + " created=NOW(), serial=? WHERE id=?"); + warnMail = DatabaseConnection.getInstance().prepare("UPDATE jobs SET warning=warning+1, state=IF(warning<3, 'open','error') WHERE id=?"); + + revoke = DatabaseConnection.getInstance().prepare("SELECT emailcerts.id, emailcerts.csr_name,jobs.id FROM jobs INNER JOIN emailcerts ON jobs.targetId=emailcerts.id" + " WHERE jobs.state='open' AND task='revoke'"); + revokeCompleted = DatabaseConnection.getInstance().prepare("UPDATE emailcerts SET revoked=NOW() WHERE id=?"); + + finishJob = DatabaseConnection.getInstance().prepare("UPDATE jobs SET state='done' WHERE id=?"); + + runner = new Thread() { + + @Override + public void run() { + work(); + } + + }; + runner.start(); + } + + private static void work() { + try { + gencrl(); + } catch (IOException e2) { + e2.printStackTrace(); + } catch (InterruptedException e2) { + e2.printStackTrace(); + } + while (running) { + try { + signCertificates(); + revokeCertificates(); + Thread.sleep(5000); + } catch (IOException e) { + e.printStackTrace(); + } catch (SQLException e) { + e.printStackTrace(); + } catch (InterruptedException e1) { + } + } + } + + private static void revokeCertificates() throws SQLException, IOException, InterruptedException { + ResultSet rs = revoke.executeQuery(); + boolean worked = false; + while (rs.next()) { + int id = rs.getInt(1); + File crt = KeyStorage.locateCrt(id); + String[] call = new String[] { + "openssl", "ca",// + "-cert", + "testca.crt",// + "-keyfile", + "testca.key",// + "-revoke", + "../" + crt.getPath(),// + "-batch",// + "-config", + "selfsign.config" + + }; + Process p1 = Runtime.getRuntime().exec(call, null, new File("keys")); + System.out.println("revoking: " + crt.getPath()); + if (p1.waitFor() == 0) { + worked = true; + revokeCompleted.setInt(1, id); + revokeCompleted.execute(); + finishJob.setInt(1, rs.getInt(3)); + finishJob.execute(); + } else { + System.out.println("Failed"); + } + } + if (worked) { + gencrl(); + } + } + + private static void gencrl() throws IOException, InterruptedException { + String[] call = new String[] { + "openssl", "ca",// + "-cert", + "testca.crt",// + "-keyfile", + "testca.key",// + "-gencrl",// + "-crlhours",// + "12",// + "-out", + "testca.crl",// + "-config", + "selfsign.config" + + }; + Process p1 = Runtime.getRuntime().exec(call, null, new File("keys")); + if (p1.waitFor() != 0) { + System.out.println("Error while generating crl."); + } + } + + private static void signCertificates() throws SQLException, IOException, InterruptedException { + ResultSet rs = readyMail.executeQuery(); + while (rs.next()) { + String csrname = rs.getString(2); + System.out.println("sign: " + csrname); + int id = rs.getInt(1); + String csrType = rs.getString(5); + CSRType ct = CSRType.valueOf(csrType); + File crt = KeyStorage.locateCrt(id); + String[] call = new String[] { + "openssl", "ca",// + "-in", + "../" + csrname,// + "-cert", + "testca.crt",// + "-keyfile", + "testca.key",// + "-out", + "../" + crt.getPath(),// + "-days", + "356",// + "-batch",// + "-subj", + rs.getString(3),// + "-config", + "selfsign.config"// + + }; + if (ct == CSRType.SPKAC) { + call[2] = "-spkac"; + } + Process p1 = Runtime.getRuntime().exec(call, null, new File("keys")); + + int waitFor = p1.waitFor(); + if (waitFor == 0) { + try (InputStream is = new FileInputStream(crt)) { + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + X509Certificate crtp = (X509Certificate) cf.generateCertificate(is); + BigInteger serial = crtp.getSerialNumber(); + updateMail.setString(1, crt.getPath()); + updateMail.setString(2, serial.toString(16)); + updateMail.setInt(3, id); + updateMail.execute(); + + finishJob.setInt(1, rs.getInt(4)); + finishJob.execute(); + System.out.println("signed: " + id); + continue; + } catch (GeneralSecurityException e) { + e.printStackTrace(); + } + System.out.println("ERROR Afterwards: " + id); + warnMail.setInt(1, rs.getInt(4)); + warnMail.execute(); + } else { + BufferedReader br = new BufferedReader(new InputStreamReader(p1.getErrorStream())); + String s; + while ((s = br.readLine()) != null) { + System.out.println(s); + } + System.out.println(Arrays.toString(call)); + System.out.println("ERROR: " + id); + warnMail.setInt(1, rs.getInt(4)); + warnMail.execute(); + } + + } + rs.close(); + } }