private String csrName;
private String crtName;
private String csr = null;
+
public Certificate(String dn, String md, String csr) {
this.dn = dn;
this.md = md;
public Certificate(int id) {
try {
- PreparedStatement ps = DatabaseConnection
- .getInstance()
- .prepare(
- "SELECT subject, md, csr_name, crt_name FROM `emailcerts` WHERE id=?");
+ PreparedStatement ps = DatabaseConnection.getInstance().prepare(
+ "SELECT subject, md, csr_name, crt_name FROM `emailcerts` WHERE id=?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
private CertificateStatus(boolean unstable) {
this.unstable = unstable;
}
+
/**
* Checks, iff this certificate stage will be left by signer actions.
*
}
}
+
public CertificateStatus getStatus() throws SQLException {
if (id == 0) {
return CertificateStatus.DRAFT;
}
- PreparedStatement searcher = DatabaseConnection
- .getInstance()
- .prepare(
- "SELECT crt_name, created, revoked, warning FROM emailcerts WHERE id=?");
+ PreparedStatement searcher = DatabaseConnection.getInstance().prepare(
+ "SELECT crt_name, created, revoked, warning FROM emailcerts WHERE id=?");
searcher.setInt(1, id);
ResultSet rs = searcher.executeQuery();
if (!rs.next()) {
if (rs.getTime(2) != null && rs.getTime(3) == null) {
return CertificateStatus.ISSUED;
}
- if (rs.getTime(2) != null
- && rs.getString(3).equals("1970-01-01 00:00:00.0")) {
+ if (rs.getTime(2) != null && rs.getString(3).equals("1970-01-01 00:00:00.0")) {
return CertificateStatus.BEING_REVOKED;
}
return CertificateStatus.REVOKED;
if (getStatus() != CertificateStatus.DRAFT) {
throw new IllegalStateException();
}
- PreparedStatement inserter = DatabaseConnection
- .getInstance()
- .prepare(
- "INSERT INTO emailcerts SET md=?, subject=?, coll_found=0, crt_name=''");
+ PreparedStatement inserter = DatabaseConnection.getInstance().prepare(
+ "INSERT INTO emailcerts SET md=?, subject=?, coll_found=0, crt_name=''");
inserter.setString(1, md);
inserter.setString(2, dn);
inserter.execute();
fos.write(csr.getBytes());
fos.close();
- PreparedStatement updater = DatabaseConnection.getInstance()
- .prepare("UPDATE emailcerts SET csr_name=? WHERE id=?");
+ PreparedStatement updater = DatabaseConnection.getInstance().prepare(
+ "UPDATE emailcerts SET csr_name=? WHERE id=?");
updater.setString(1, csrName);
updater.setInt(2, id);
updater.execute();
}
}
+
public boolean waitFor(int max) throws SQLException, InterruptedException {
long start = System.currentTimeMillis();
while (getStatus().isUnstable()) {
}
return true;
}
+
public void revoke() {
try {
if (getStatus() != CertificateStatus.ISSUED) {
throw new IllegalStateException();
}
- PreparedStatement inserter = DatabaseConnection
- .getInstance()
- .prepare(
- "UPDATE emailcerts SET revoked = '1970-01-01' WHERE id=?");
+ PreparedStatement inserter = DatabaseConnection.getInstance().prepare(
+ "UPDATE emailcerts SET revoked = '1970-01-01' WHERE id=?");
inserter.setInt(1, id);
inserter.execute();
} catch (SQLException e) {
}
- public X509Certificate cert() throws IOException, GeneralSecurityException,
- SQLException {
+ public X509Certificate cert() throws IOException, GeneralSecurityException, SQLException {
CertificateStatus status = getStatus();
if (status != CertificateStatus.ISSUED) {
throw new IllegalStateException(status + " is not wanted here.");
}
return crt;
}
+
public Certificate renew() {
return null;
}
+
public int getId() {
return id;
}
+
public int getSerial() {
return serial;
}
+
public String getDistinguishedName() {
return dn;
}
+
public String getMessageDigest() {
return md;
}
ByteArrayOutputStream chunkConfig = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(chunkConfig);
byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
- byte[] keystore = Files.readAllBytes(Paths
- .get("config/keystore.pkcs12"));
+ byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
- DevelLauncher.writeGigiConfig(dos, "changeit".getBytes(),
- "changeit".getBytes(), mainProps, cacerts, keystore);
+ DevelLauncher.writeGigiConfig(dos, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts, keystore);
dos.flush();
InputStream oldin = System.in;
System.setIn(new ByteArrayInputStream(chunkConfig.toByteArray()));
Launcher.main(args);
System.setIn(oldin);
}
- public static void writeGigiConfig(OutputStream target, byte[] keystorepw,
- byte[] truststorepw, Properties mainprop, byte[] cacerts,
- byte[] keystore) throws IOException {
+
+ public static void writeGigiConfig(OutputStream target, byte[] keystorepw, byte[] truststorepw,
+ Properties mainprop, byte[] cacerts, byte[] keystore) throws IOException {
TarOutputStream tos = new TarOutputStream(target);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mainprop.store(baos, "");
tos.close();
}
- private static void putTarEntry(byte[] data, TarOutputStream tos,
- String name) throws IOException {
+
+ private static void putTarEntry(byte[] data, TarOutputStream tos, String name) throws IOException {
TarHeader th = new TarHeader();
th.name = new StringBuffer(name);
th.size = data.length;
tos.putNextEntry(new TarEntry(th));
tos.write(data);
}
- public static void writeChunk(DataOutputStream dos, byte[] chunk)
- throws IOException {
+
+ public static void writeChunk(DataOutputStream dos, byte[] chunk) throws IOException {
dos.writeInt(chunk.length);
dos.write(chunk);
}
- public static void launch(Properties props, File cacerts, File keystore)
- throws IOException {
+
+ public static void launch(Properties props, File cacerts, File keystore) throws IOException {
ByteArrayOutputStream config = new ByteArrayOutputStream();
props.store(config, "");
}
pages.put(MailOverview.DEFAULT_PATH, new MailOverview("My email addresses"));
baseTemplate = new Template(new InputStreamReader(Gigi.class.getResourceAsStream("Gigi.templ")));
m = new Menu("Certificates", "cert", new MenuItem(MailOverview.DEFAULT_PATH, "Emails"), new MenuItem("",
- "Client Certificates"), new MenuItem("", "Domains"), new MenuItem("", "Server Certificates"));
+ "Client Certificates"), new MenuItem("", "Domains"), new MenuItem("", "Server Certificates"));
super.init();
}
@Override
protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException,
- IOException {
+ IOException {
addXSSHeaders(resp);
// if (req.getHeader("Origin") != null) {
// resp.getWriter().println("No cross domain access allowed.");
public static void addXSSHeaders(HttpServletResponse hsr) {
hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePort() + " https://"
- + ServerConstants.getSecureHostNamePort());
+ + ServerConstants.getSecureHostNamePort());
hsr.addHeader("Access-Control-Max-Age", "60");
hsr.addHeader("Content-Security-Policy", getDefaultCSP());
csp.append("script-src https://" + ServerConstants.getStaticHostNamePort());
csp.append(";style-src https://" + ServerConstants.getStaticHostNamePort());
csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://"
- + ServerConstants.getWwwHostNamePort());
+ + ServerConstants.getWwwHostNamePort());
csp.append("report-url https://api.cacert.org/security/csp/report");
defaultCSP = csp.toString();
}
private GigiConfig() {
}
+
public byte[] getCacerts() {
return cacerts;
}
+
public byte[] getKeystore() {
return keystore;
}
+
public Properties getMainProps() {
return mainProps;
}
tis.close();
return gc;
}
+
public static byte[] readFully(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
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++) {
return res;
}
- public KeyStore getPrivateStore() throws GeneralSecurityException,
- IOException {
+ public KeyStore getPrivateStore() throws GeneralSecurityException, IOException {
KeyStore ks1 = KeyStore.getInstance("pkcs12");
ks1.load(new ByteArrayInputStream(keystore), keystorpw);
return ks1;
}
- public KeyStore getTrustStore() throws GeneralSecurityException,
- IOException {
+
+ public KeyStore getTrustStore() throws GeneralSecurityException, IOException {
KeyStore ks1 = KeyStore.getInstance("jks");
ks1.load(new ByteArrayInputStream(cacerts), truststorepw);
return ks1;
}
+
public String getPrivateStorePw() {
return new String(keystorpw);
}
private static HashMap<String, Language> langs = new HashMap<String, Language>();
HashMap<String, String> translations = new HashMap<String, String>();
Locale l;
- private Language(String language) throws ParserConfigurationException,
- IOException, SAXException {
+
+ private Language(String language) throws ParserConfigurationException, IOException, SAXException {
if (language.contains("_")) {
String[] parts = language.split("_");
l = new Locale(parts[0], parts[1]);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
- Document d = db.parse(new FileInputStream(new File("locale", language
- + ".xml")));
+ Document d = db.parse(new FileInputStream(new File("locale", language + ".xml")));
NodeList nl = d.getDocumentElement().getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
if (!(nl.item(i) instanceof Element)) {
}
System.out.println(translations.size() + " strings loaded.");
}
+
public String getTranslation(String text) {
String string = translations.get(text);
if (string == null || string.equals("")) {
}
return string;
}
+
public static Language getInstance(String language) {
Language l = langs.get(language);
if (l == null) {
}
return l;
}
+
public Locale getLocale() {
return l;
}
package org.cacert.gigi;
+
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
// for client-cert auth
https_config.addCustomizer(new SecureRequestCustomizer());
- ServerConnector connector = new ServerConnector(s,
- createConnectionFactory(conf), new HttpConnectionFactory(
- https_config));
+ ServerConnector connector = new ServerConnector(s, createConnectionFactory(conf), new HttpConnectionFactory(
+ https_config));
connector.setHost(conf.getMainProps().getProperty("host"));
- connector.setPort(Integer.parseInt(conf.getMainProps().getProperty(
- "port")));
- s.setConnectors(new Connector[]{connector});
+ connector.setPort(Integer.parseInt(conf.getMainProps().getProperty("port")));
+ s.setConnectors(new Connector[] { connector });
HandlerList hl = new HandlerList();
- hl.setHandlers(new Handler[]{generateStaticContext(),
- generateGigiContext(conf.getMainProps()), generateAPIContext()});
+ hl.setHandlers(new Handler[] { generateStaticContext(), generateGigiContext(conf.getMainProps()),
+ generateAPIContext() });
s.setHandler(hl);
s.start();
- if (connector.getPort() <= 1024
- && !System.getProperty("os.name").toLowerCase().contains("win")) {
+ if (connector.getPort() <= 1024 && !System.getProperty("os.name").toLowerCase().contains("win")) {
SetUID uid = new SetUID();
if (!uid.setUid(65536 - 2, 65536 - 2).getSuccess()) {
Log.getLogger(Launcher.class).warn("Couldn't set uid!");
}
}
- private static SslConnectionFactory createConnectionFactory(GigiConfig conf)
- throws GeneralSecurityException, IOException {
- final SslContextFactory sslContextFactory = generateSSLContextFactory(
- conf, "www");
- final SslContextFactory secureContextFactory = generateSSLContextFactory(
- conf, "secure");
+ private static SslConnectionFactory createConnectionFactory(GigiConfig conf) throws GeneralSecurityException,
+ IOException {
+ final SslContextFactory sslContextFactory = generateSSLContextFactory(conf, "www");
+ final SslContextFactory secureContextFactory = generateSSLContextFactory(conf, "secure");
secureContextFactory.setNeedClientAuth(true);
- final SslContextFactory staticContextFactory = generateSSLContextFactory(
- conf, "static");
- final SslContextFactory apiContextFactory = generateSSLContextFactory(
- conf, "api");
+ final SslContextFactory staticContextFactory = generateSSLContextFactory(conf, "static");
+ final SslContextFactory apiContextFactory = generateSSLContextFactory(conf, "api");
try {
secureContextFactory.start();
staticContextFactory.start();
} catch (Exception e) {
e.printStackTrace();
}
- return new SslConnectionFactory(sslContextFactory,
- HttpVersion.HTTP_1_1.asString()) {
+ return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()) {
@Override
public boolean shouldRestartSSL() {
return true;
}
+
@Override
public SSLEngine restartSSL(SSLSession sslSession) {
SSLEngine e2 = null;
if (sniServerName instanceof SNIHostName) {
SNIHostName host = (SNIHostName) sniServerName;
String hostname = host.getAsciiName();
- if (hostname.equals(ServerConstants
- .getWwwHostName())) {
+ if (hostname.equals(ServerConstants.getWwwHostName())) {
e2 = sslContextFactory.newSSLEngine();
- } else if (hostname.equals(ServerConstants
- .getStaticHostName())) {
+ } else if (hostname.equals(ServerConstants.getStaticHostName())) {
e2 = staticContextFactory.newSSLEngine();
- } else if (hostname.equals(ServerConstants
- .getSecureHostName())) {
+ } else if (hostname.equals(ServerConstants.getSecureHostName())) {
e2 = secureContextFactory.newSSLEngine();
- } else if (hostname.equals(ServerConstants
- .getApiHostName())) {
+ } else if (hostname.equals(ServerConstants.getApiHostName())) {
e2 = apiContextFactory.newSSLEngine();
}
break;
}
}
if (e2 == null) {
- e2 = sslContextFactory.newSSLEngine(
- sslSession.getPeerHost(), sslSession.getPeerPort());
+ e2 = sslContextFactory.newSSLEngine(sslSession.getPeerHost(), sslSession.getPeerPort());
}
e2.setUseClientMode(false);
return e2;
HandlerWrapper hw = new PolicyRedirector();
hw.setHandler(rh);
- ServletContextHandler servlet = new ServletContextHandler(
- ServletContextHandler.SESSIONS);
- servlet.setInitParameter(SessionManager.__SessionCookieProperty,
- "CACert-Session");
+ ServletContextHandler servlet = new ServletContextHandler(ServletContextHandler.SESSIONS);
+ servlet.setInitParameter(SessionManager.__SessionCookieProperty, "CACert-Session");
servlet.addServlet(new ServletHolder(new Gigi(conf)), "/*");
HandlerList hl = new HandlerList();
- hl.setHandlers(new Handler[]{hw, servlet});
+ hl.setHandlers(new Handler[] { hw, servlet });
ContextHandler ch = new ContextHandler();
- ch.setVirtualHosts(new String[]{ServerConstants.getWwwHostName(),
- ServerConstants.getSecureHostName()});
+ ch.setVirtualHosts(new String[] { ServerConstants.getWwwHostName(), ServerConstants.getSecureHostName() });
ch.setHandler(hl);
return ch;
ContextHandler ch = new ContextHandler();
ch.setHandler(rh);
- ch.setVirtualHosts(new String[]{ServerConstants.getStaticHostName()});
+ ch.setVirtualHosts(new String[] { ServerConstants.getStaticHostName() });
return ch;
}
private static Handler generateAPIContext() {
ServletContextHandler sch = new ServletContextHandler();
- sch.addVirtualHosts(new String[]{ServerConstants.getApiHostName()});
+ sch.addVirtualHosts(new String[] { ServerConstants.getApiHostName() });
sch.addServlet(new ServletHolder(new GigiAPI()), "/*");
return sch;
}
- private static SslContextFactory generateSSLContextFactory(GigiConfig conf,
- String alias) throws GeneralSecurityException, IOException {
+ private static SslContextFactory generateSSLContextFactory(GigiConfig conf, String alias)
+ throws GeneralSecurityException, IOException {
SslContextFactory scf = new SslContextFactory() {
String[] ciphers = null;
SSLParameters ssl = sslEngine.getSSLParameters();
ssl.setUseCipherSuitesOrder(true);
if (ciphers == null) {
- ciphers = CipherInfo.filter(sslEngine
- .getSupportedCipherSuites());
+ ciphers = CipherInfo.filter(sslEngine.getSupportedCipherSuites());
}
ssl.setCipherSuites(ciphers);
out.print("</span>");
out.println("</span>");
}
+
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Name)) {
public class PolicyRedirector extends HandlerWrapper {
@Override
- public void handle(String target, Request baseRequest,
- HttpServletRequest request, HttpServletResponse response)
- throws IOException, ServletException {
+ public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
+ throws IOException, ServletException {
if (target.equals("/")) {
return;
}
public User(int id) {
this.id = id;
try {
- PreparedStatement ps = DatabaseConnection
- .getInstance()
- .prepare(
- "SELECT `fname`, `lname`,`mname`, `suffix`, `dob`, `email` FROM `users` WHERE id=?");
+ PreparedStatement ps = DatabaseConnection.getInstance().prepare(
+ "SELECT `fname`, `lname`,`mname`, `suffix`, `dob`, `email` FROM `users` WHERE id=?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
- name = new Name(rs.getString(1), rs.getString(2),
- rs.getString(3), rs.getString(4));
+ name = new Name(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4));
dob = rs.getDate(5);
email = rs.getString(6);
}
e.printStackTrace();
}
}
+
public User() {
}
+
public int getId() {
return id;
}
+
public String getFname() {
return name.fname;
}
+
public String getLname() {
return name.lname;
}
+
public String getMname() {
return name.mname;
}
+
public Name getName() {
return name;
}
+
public void setMname(String mname) {
this.name.mname = mname;
}
+
public String getSuffix() {
return name.suffix;
}
+
public void setSuffix(String suffix) {
this.name.suffix = suffix;
}
+
public Date getDob() {
return dob;
}
+
public void setDob(Date dob) {
this.dob = dob;
}
+
public String getEmail() {
return email;
}
+
public void setEmail(String email) {
this.email = email;
}
+
public void setId(int id) {
this.id = id;
}
+
public void setFname(String fname) {
this.name.fname = fname;
}
+
public void setLname(String lname) {
this.name.lname = lname;
}
+
public void insert(String password) throws SQLException {
if (id != 0) {
throw new Error("refusing to insert");
}
PreparedStatement query = DatabaseConnection.getInstance().prepare(
- "insert into `users` set `email`=?, `password`=?, "
- + "`fname`=?, `mname`=?, `lname`=?, "
- + "`suffix`=?, `dob`=?, `created`=NOW(), locked=0");
+ "insert into `users` set `email`=?, `password`=?, " + "`fname`=?, `mname`=?, `lname`=?, "
+ + "`suffix`=?, `dob`=?, `created`=NOW(), locked=0");
query.setString(1, email);
query.setString(2, PasswordHash.hash(password));
query.setString(3, name.fname);
return hasPassedCATS();
}
+
public boolean hasPassedCATS() throws SQLException {
PreparedStatement query = DatabaseConnection.getInstance().prepare(
- "SELECT 1 FROM `cats_passed` where `user_id`=?");
+ "SELECT 1 FROM `cats_passed` where `user_id`=?");
query.setInt(1, id);
ResultSet rs = query.executeQuery();
if (rs.next()) {
return false;
}
}
+
public int getAssurancePoints() throws SQLException {
- PreparedStatement query = DatabaseConnection
- .getInstance()
- .prepare(
- "SELECT sum(points) FROM `notary` where `to`=? AND `deleted`=0");
+ PreparedStatement query = DatabaseConnection.getInstance().prepare(
+ "SELECT sum(points) FROM `notary` where `to`=? AND `deleted`=0");
query.setInt(1, id);
ResultSet rs = query.executeQuery();
int points = 0;
rs.close();
return points;
}
+
public int getExperiencePoints() throws SQLException {
PreparedStatement query = DatabaseConnection.getInstance().prepare(
- "SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0");
+ "SELECT count(*) FROM `notary` where `from`=? AND `deleted`=0");
query.setInt(1, id);
ResultSet rs = query.executeQuery();
int points = 0;
rs.close();
return points;
}
+
@Override
public boolean equals(Object obj) {
if (!(obj instanceof User)) {
return false;
}
User s = (User) obj;
- return name.equals(s.name) && email.equals(s.email)
- && dob.toString().equals(s.dob.toString()); // This is due to
- // day cutoff
+ return name.equals(s.name) && email.equals(s.email) && dob.toString().equals(s.dob.toString()); // This
+ // is
+ // due
+ // to
+ // day
+ // cutoff
}
/**
public class GigiAPI extends HttpServlet {
@Override
- protected void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
+ protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String pi = req.getPathInfo();
if (pi == null) {
return;
HashMap<String, PreparedStatement> statements = new HashMap<String, PreparedStatement>();
private static Properties credentials;
Statement adHoc;
+
public DatabaseConnection() {
try {
Class.forName(credentials.getProperty("sql.driver"));
tryConnect();
}
+
private void tryConnect() {
try {
- c = DriverManager.getConnection(credentials.getProperty("sql.url")
- + "?zeroDateTimeBehavior=convertToNull",
- credentials.getProperty("sql.user"),
- credentials.getProperty("sql.password"));
- PreparedStatement ps = c
- .prepareStatement("SET SESSION wait_timeout=?;");
+ c = DriverManager.getConnection(credentials.getProperty("sql.url") + "?zeroDateTimeBehavior=convertToNull",
+ credentials.getProperty("sql.user"), credentials.getProperty("sql.password"));
+ PreparedStatement ps = c.prepareStatement("SET SESSION wait_timeout=?;");
ps.setInt(1, CONNECTION_TIMEOUT);
ps.execute();
ps.close();
e.printStackTrace();
}
}
+
public PreparedStatement prepare(String query) throws SQLException {
ensureOpen();
PreparedStatement statement = statements.get(query);
if (statement == null) {
- statement = c.prepareStatement(query,
- Statement.RETURN_GENERATED_KEYS);
+ statement = c.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
statements.put(query, statement);
}
return statement;
}
+
long lastAction = System.currentTimeMillis();
+
private void ensureOpen() {
if (System.currentTimeMillis() - lastAction > CONNECTION_TIMEOUT * 1000L) {
try {
}
lastAction = System.currentTimeMillis();
}
+
public static int lastInsertId(PreparedStatement query) throws SQLException {
ResultSet rs = query.getGeneratedKeys();
rs.next();
rs.close();
return id;
}
+
static ThreadLocal<DatabaseConnection> instances = new ThreadLocal<DatabaseConnection>() {
@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()) {
}
@Override
- public void sendmail(String to, String subject, String message,
- String from, String replyto, String toname, String fromname,
- String errorsto, boolean extra) throws IOException {
+ public void sendmail(String to, String subject, String message, String from, String replyto, String toname,
+ String fromname, String errorsto, boolean extra) throws IOException {
synchronized (System.out) {
System.out.println("== MAIL ==");
System.out.println("To: " + to);
}
}
+
@Override
- public String checkEmailServer(int forUid, String address)
- throws IOException {
+ public String checkEmailServer(int forUid, String address) throws IOException {
System.out.println("checkMailBox: " + address);
return OK;
}
import org.cacert.gigi.database.DatabaseConnection;
public abstract class EmailProvider {
- public abstract void sendmail(String to, String subject, String message,
- String from, String replyto, String toname, String fromname,
- String errorsto, boolean extra) throws IOException;
+ public abstract void sendmail(String to, String subject, String message, String from, String replyto,
+ String toname, String fromname, String errorsto, boolean extra) throws IOException;
+
private static EmailProvider instance;
+
public static EmailProvider getInstance() {
return instance;
}
+
public static void init(Properties conf) {
try {
Class<?> c = Class.forName(conf.getProperty("emailProvider"));
- instance = (EmailProvider) c.getDeclaredConstructor(
- Properties.class).newInstance(conf);
+ instance = (EmailProvider) c.getDeclaredConstructor(Properties.class).newInstance(conf);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
public static final String OK = "OK";
public static final String FAIL = "FAIL";
private static final Pattern MAIL = Pattern
- .compile("^([a-zA-Z0-9])+([a-zA-Z0-9\\+\\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\\._-]+)+$");
+ .compile("^([a-zA-Z0-9])+([a-zA-Z0-9\\+\\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\\._-]+)+$");
- public String checkEmailServer(int forUid, String address)
- throws IOException {
+ public String checkEmailServer(int forUid, String address) throws IOException {
if (MAIL.matcher(address).matches()) {
String[] parts = address.split("@", 2);
String domain = parts[1];
for (String host : mxhosts) {
try (Socket s = new Socket(host, 25);
- BufferedReader br = new BufferedReader(
- new InputStreamReader(s.getInputStream()));
- PrintWriter pw = new PrintWriter(s.getOutputStream())) {
+ BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
+ PrintWriter pw = new PrintWriter(s.getOutputStream())) {
String line;
- while ((line = br.readLine()) != null
- && line.startsWith("220-")) {
+ while ((line = br.readLine()) != null && line.startsWith("220-")) {
}
if (line == null || !line.startsWith("220")) {
continue;
pw.print("HELO www.cacert.org\r\n");
pw.flush();
- while ((line = br.readLine()) != null
- && line.startsWith("220")) {
+ while ((line = br.readLine()) != null && line.startsWith("220")) {
}
if (line == null || !line.startsWith("250")) {
pw.flush();
try {
- PreparedStatement statmt = DatabaseConnection
- .getInstance()
- .prepare(
- "insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?");
+ PreparedStatement statmt = DatabaseConnection.getInstance().prepare(
+ "insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?");
statmt.setString(1, address);
statmt.setString(2, line);
statmt.setInt(3, forUid);
}
}
try {
- PreparedStatement statmt = DatabaseConnection
- .getInstance()
- .prepare(
- "insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?");
+ PreparedStatement statmt = DatabaseConnection.getInstance().prepare(
+ "insert into `pinglog` set `when`=NOW(), `email`=?, `result`=?, `uid`=?");
statmt.setString(1, address);
- statmt.setString(2,
- "Failed to make a connection to the mail server");
+ statmt.setString(2, "Failed to make a connection to the mail server");
statmt.setInt(3, forUid);
statmt.execute();
} catch (SQLException e) {
}
return FAIL;
}
- private static LinkedList<String> getMxHosts(String domain)
- throws IOException {
+
+ private static LinkedList<String> getMxHosts(String domain) throws IOException {
LinkedList<String> mxhosts = new LinkedList<String>();
- Process dig = Runtime.getRuntime().exec(
- new String[]{"dig", "+short", "MX", domain});
- try (BufferedReader br = new BufferedReader(new InputStreamReader(
- dig.getInputStream()))) {
+ Process dig = Runtime.getRuntime().exec(new String[] { "dig", "+short", "MX", domain });
+ try (BufferedReader br = new BufferedReader(new InputStreamReader(dig.getInputStream()))) {
String line;
while ((line = br.readLine()) != null) {
String[] mxparts = line.split(" ", 2);
public class Sendmail extends EmailProvider {
protected Sendmail(Properties props) {
}
- private static final Pattern NON_ASCII = Pattern
- .compile("[^a-zA-Z0-9 .-\\[\\]!_@]");
+
+ private static final Pattern NON_ASCII = Pattern.compile("[^a-zA-Z0-9 .-\\[\\]!_@]");
@Override
- public void sendmail(String to, String subject, String message,
- String from, String replyto, String toname, String fromname,
- String errorsto, boolean extra) throws IOException {
+ public void sendmail(String to, String subject, String message, String from, String replyto, String toname,
+ String fromname, String errorsto, boolean extra) throws IOException {
String[] bits = from.split(",");
Socket smtp = new Socket("dogcraft.de", 25);
PrintWriter out = new PrintWriter(smtp.getOutputStream());
- BufferedReader in = new BufferedReader(new InputStreamReader(
- smtp.getInputStream()));
+ BufferedReader in = new BufferedReader(new InputStreamReader(smtp.getInputStream()));
readResponse(in);
out.print("HELO www.cacert.org\r\n");
out.flush();
// out.print("X-OriginatingIP: ".$_SERVER["REMOTE_ADDR"]."\r\n");
// }
// TODO
- SimpleDateFormat emailDate = new SimpleDateFormat(
- "E, d MMM yyyy HH:mm:ss ZZZZ (z)", Locale.ENGLISH);
- out.print("Date: "
- + emailDate.format(new Date(System.currentTimeMillis()))
- + "\r\n");
+ SimpleDateFormat emailDate = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss ZZZZ (z)", Locale.ENGLISH);
+ out.print("Date: " + emailDate.format(new Date(System.currentTimeMillis())) + "\r\n");
out.print("Sender: " + errorsto + "\r\n");
out.print("Errors-To: " + errorsto + "\r\n");
if (replyto != null) {
out.print("To: " + to + "\r\n");
if (NON_ASCII.matcher(subject).matches()) {
- out.print("Subject: =?utf-8?B?"
- + Base64.getEncoder().encodeToString(subject.getBytes())
- + "?=\r\n");
+ out.print("Subject: =?utf-8?B?" + Base64.getEncoder().encodeToString(subject.getBytes()) + "?=\r\n");
} else {
out.print("Subject: " + subject + "\r\n");
}
// $message)))."\r\n.\r\n");
message = message + "\r\n";
- String sendM = message.replace("\r", "").replace("\n.\n", "\n")
- .replace("\n.\n", "\n").replace("\n", "\r\n")
- + ".\r\n";
+ String sendM = message.replace("\r", "").replace("\n.\n", "\n").replace("\n.\n", "\n").replace("\n", "\r\n")
+ + ".\r\n";
out.print(sendM);
out.flush();
readResponse(in);
readResponse(in);
smtp.close();
}
+
private static void readResponse(BufferedReader in) throws IOException {
String line;
while ((line = in.readLine()) != null && line.matches("\\d+-")) {
Socket client;
DataOutputStream out;
DataInputStream in;
+
protected TestEmailProvider(Properties props) {
try {
- servs = new ServerSocket(Integer.parseInt(props
- .getProperty("emailProvider.port")), 10,
- InetAddress.getByName("127.0.0.1"));
+ servs = new ServerSocket(Integer.parseInt(props.getProperty("emailProvider.port")), 10,
+ InetAddress.getByName("127.0.0.1"));
} catch (IOException e) {
e.printStackTrace();
}
}
+
@Override
- public synchronized void sendmail(String to, String subject,
- String message, String from, String replyto, String toname,
- String fromname, String errorsto, boolean extra) throws IOException {
+ public synchronized void sendmail(String to, String subject, String message, String from, String replyto,
+ String toname, String fromname, String errorsto, boolean extra) throws IOException {
while (true) {
assureLocalConnection();
try {
}
}
}
+
private void assureLocalConnection() throws IOException {
if (out != null) {
try {
in = new DataInputStream(client.getInputStream());
}
}
+
@Override
- public synchronized String checkEmailServer(int forUid, String address)
- throws IOException {
+ public synchronized String checkEmailServer(int forUid, String address) throws IOException {
while (true) {
assureLocalConnection();
try {
public class CertificateTable implements Outputable {
String resultSet;
+
public CertificateTable(String resultSet) {
this.resultSet = resultSet;
}
- private static final String[] columnNames = new String[]{
- "Renew/Revoke/Delete", "Status", "Email Address", "SerialNumber",
- "Revoked", "Expires", "Login"};
+
+ private static final String[] columnNames = new String[] { "Renew/Revoke/Delete", "Status", "Email Address",
+ "SerialNumber", "Revoked", "Expires", "Login" };
@Override
public void output(PrintWriter out, Language l, Map<String, Object> vars) {
static Template IE;
static {
normal = new Template(new InputStreamReader(
- ClientCSRGenerate.class
- .getResourceAsStream("ClientCSRGenerate.templ")));
+ ClientCSRGenerate.class.getResourceAsStream("ClientCSRGenerate.templ")));
IE = new Template(new InputStreamReader(
- ClientCSRGenerate.class
- .getResourceAsStream("ClientCSRGenerateIE.templ")));
+ ClientCSRGenerate.class.getResourceAsStream("ClientCSRGenerateIE.templ")));
}
+
public static void output(HttpServletRequest req, HttpServletResponse resp) {
HashMap<String, Object> vars = new HashMap<String, Object>();
vars.put("minsize", "2048");
- vars.put("normalhost",
- "https://" + ServerConstants.getWwwHostNamePort());
- vars.put("securehost",
- "https://" + ServerConstants.getSecureHostNamePort());
- vars.put("statichost",
- "https://" + ServerConstants.getStaticHostNamePort());
+ vars.put("normalhost", "https://" + ServerConstants.getWwwHostNamePort());
+ vars.put("securehost", "https://" + ServerConstants.getSecureHostNamePort());
+ vars.put("statichost", "https://" + ServerConstants.getStaticHostNamePort());
try {
normal.output(resp.getWriter(), Page.getLanguage(req), vars);
} catch (IOException e) {
public class DateSelector implements Outputable {
String[] names;
+
public DateSelector(String day, String month, String year) {
- this.names = new String[]{day, month, year};
+ this.names = new String[] { day, month, year };
}
+
int day;
int month;
int year;
+
@Override
public void output(PrintWriter out, Language l, Map<String, Object> vars) {
out.print("<nobr><select name=\"");
year = parseIntSafe(yearS);
}
}
+
private int parseIntSafe(String dayS) {
try {
return Integer.parseInt(dayS);
}
return 0;
}
+
public boolean isValid() {
if (!(1900 < year && 1 <= month && month <= 12 && 1 <= day && day <= 32)) {
return false;
@Override
public String toString() {
- return "DateSelector [names=" + Arrays.toString(names) + ", day=" + day
- + ", month=" + month + ", year=" + year + "]";
+ return "DateSelector [names=" + Arrays.toString(names) + ", day=" + day + ", month=" + month + ", year=" + year
+ + "]";
}
public java.sql.Date getDate() {
public abstract class Form implements Outputable {
String csrf;
+
public Form() {
csrf = RandomToken.generateToken(32);
}
public abstract boolean submit(PrintWriter out, HttpServletRequest req);
+
@Override
- public final void output(PrintWriter out, Language l,
- Map<String, Object> vars) {
+ public final void output(PrintWriter out, Language l, Map<String, Object> vars) {
out.println("<form method='POST' autocomplete='off'>");
outputContent(out, l, vars);
out.print("<input type='csrf' value='");
out.println("'></form>");
}
- protected abstract void outputContent(PrintWriter out, Language l,
- Map<String, Object> vars);
+ protected abstract void outputContent(PrintWriter out, Language l, Map<String, Object> vars);
protected void outputError(PrintWriter out, ServletRequest req, String text) {
out.print("<div>");
protected String getCSRFToken() {
return csrf;
}
+
protected void checkCSRF(HttpServletRequest req) {
if (!csrf.equals(req.getParameter("csrf"))) {
throw new CSRFError();
LinkedList<Outputable> commands = new LinkedList<Outputable>();
StringBuffer buf = new StringBuffer();
int ch = r.read();
- outer : while (true) {
+ outer: while (true) {
while (!endsWith(buf, "<?")) {
if (ch == -1) {
break outer;
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);
+ && buf.substring(buf.length() - string.length(), buf.length()).equals(string);
}
+
private Outputable parseCommand(String s2) {
s2 = s2.replace("\n", "");
if (s2.startsWith("=_")) {
return new Outputable() {
@Override
- public void output(PrintWriter out, Language l,
- Map<String, Object> vars) {
+ public void output(PrintWriter out, Language l, Map<String, Object> vars) {
out.print(l.getTranslation(raw));
}
};
return new Outputable() {
@Override
- public void output(PrintWriter out, Language l,
- Map<String, Object> vars) {
+ public void output(PrintWriter out, Language l, Map<String, Object> vars) {
outputVar(out, l, vars, raw);
}
};
return new Outputable() {
@Override
- public void output(PrintWriter out, Language l,
- Map<String, Object> vars) {
+ public void output(PrintWriter out, Language l, Map<String, Object> vars) {
String[] parts = l.getTranslation(text).split("%s");
String[] myvars = store.toArray(new String[store.size()]);
out.print(parts[0]);
}
return null;
}
+
public void output(PrintWriter out, Language l, Map<String, Object> vars) {
for (int i = 0; i < contents.length; i++) {
out.print(contents[i]);
}
}
}
- private void outputVar(PrintWriter out, Language l,
- Map<String, Object> vars, String varname) {
+
+ private void outputVar(PrintWriter out, Language l, Map<String, Object> vars, String varname) {
Object s = vars.get(varname);
if (s == null) {
}
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
- resp.getWriter()
- .println(
- "<form method='POST' action='/login'>"
- + "<input type='text' name='username'>"
- + "<input type='password' name='password'> <input type='submit' value='login'></form>");
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+ resp.getWriter().println(
+ "<form method='POST' action='/login'>" + "<input type='text' name='username'>"
+ + "<input type='password' name='password'> <input type='submit' value='login'></form>");
}
@Override
- public boolean beforeTemplate(HttpServletRequest req,
- HttpServletResponse resp) throws IOException {
+ public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String redir = (String) req.getSession().getAttribute(LOGIN_RETURNPATH);
if (req.getSession().getAttribute("loggedin") == null) {
- X509Certificate[] cert = (X509Certificate[]) req
- .getAttribute("javax.servlet.request.X509Certificate");
+ X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
if (cert != null && cert[0] != null) {
tryAuthWithCertificate(req, cert[0]);
}
}
return false;
}
+
@Override
public boolean needsLogin() {
return false;
}
+
private void tryAuthWithUnpw(HttpServletRequest req) {
String un = req.getParameter("username");
String pw = req.getParameter("password");
try {
- PreparedStatement ps = DatabaseConnection
- .getInstance()
- .prepare(
- "SELECT `password`, `id` FROM `users` WHERE `email`=? AND locked='0' AND verified='1'");
+ PreparedStatement ps = DatabaseConnection.getInstance().prepare(
+ "SELECT `password`, `id` FROM `users` WHERE `email`=? AND locked='0' AND verified='1'");
ps.setString(1, un);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
e.printStackTrace();
}
}
+
public static User getUser(HttpServletRequest req) {
return (User) req.getSession().getAttribute(USER);
}
- private void tryAuthWithCertificate(HttpServletRequest req,
- X509Certificate x509Certificate) {
- String serial = x509Certificate.getSerialNumber().toString(16)
- .toUpperCase();
+
+ private void tryAuthWithCertificate(HttpServletRequest req, X509Certificate x509Certificate) {
+ String serial = x509Certificate.getSerialNumber().toString(16).toUpperCase();
try {
- PreparedStatement ps = DatabaseConnection
- .getInstance()
- .prepare(
- "SELECT `memid` FROM `emailcerts` WHERE `serial`=? AND `disablelogin`='0' AND `revoked` = "
- + "'0000-00-00 00:00:00'");
+ PreparedStatement ps = DatabaseConnection.getInstance().prepare(
+ "SELECT `memid` FROM `emailcerts` WHERE `serial`=? AND `disablelogin`='0' AND `revoked` = "
+ + "'0000-00-00 00:00:00'");
ps.setString(1, serial);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
}
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.getWriter().println("Access granted.");
}
+
@Override
public boolean needsLogin() {
return false;
public Page(String title) {
this.title = title;
try {
- InputStream resource = getClass().getResourceAsStream(
- getClass().getSimpleName() + ".templ");
+ InputStream resource = getClass().getResourceAsStream(getClass().getSimpleName() + ".templ");
if (resource != null) {
- defaultTemplate = new Template(new InputStreamReader(resource,
- "UTF-8"));
+ defaultTemplate = new Template(new InputStreamReader(resource, "UTF-8"));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
* @throws IOException
* if output goes wrong.
*/
- public boolean beforeTemplate(HttpServletRequest req,
- HttpServletResponse resp) throws IOException {
+ public boolean beforeTemplate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
return false;
}
* @throws IOException
* if output goes wrong.
*/
- public abstract void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException;
+ public abstract void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException;
/**
* Same as {@link #doGet(HttpServletRequest, HttpServletResponse)} but for
* @throws IOException
* if output goes wrong.
*/
- public void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doGet(req, resp);
}
public void setTitle(String title) {
this.title = title;
}
+
public static Language getLanguage(ServletRequest req) {
return Language.getInstance("de");
}
}
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.getWriter().println("This page is secure.");
}
public class Verify extends Page {
public static final String PATH = "/verify";
+
public Verify() {
super("Verify email");
}
+
@Override
public boolean needsLogin() {
return false;
}
+
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
String hash = req.getParameter("hash");
String type = req.getParameter("type");
String id = req.getParameter("id");
if ("email".equals(type)) {
try {
- PreparedStatement ps = DatabaseConnection
- .getInstance()
- .prepare(
- "select email, memid from `email` where `id`=? and `hash`=? and `hash` != '' and `deleted` = 0");
+ PreparedStatement ps = DatabaseConnection.getInstance().prepare(
+ "select email, memid from `email` where `id`=? and `hash`=? and `hash` != '' and `deleted` = 0");
ps.setString(1, id);
ps.setString(2, hash);
ResultSet rs = ps.executeQuery();
rs.last();
if (rs.getRow() == 1) {
- PreparedStatement ps1 = DatabaseConnection
- .getInstance()
- .prepare(
- "update `email` set `hash`='', `modified`=NOW() where `id`=?");
+ PreparedStatement ps1 = DatabaseConnection.getInstance().prepare(
+ "update `email` set `hash`='', `modified`=NOW() where `id`=?");
ps1.setString(1, id);
ps1.execute();
- PreparedStatement ps2 = DatabaseConnection
- .getInstance()
- .prepare(
- "update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'");
+ PreparedStatement ps2 = DatabaseConnection.getInstance().prepare(
+ "update `users` set `verified`='1' where `id`=? and `email`=? and `verified`='0'");
ps2.setString(1, rs.getString(2));
ps2.setString(2, rs.getString(1));
ps2.execute();
}
}
}
+
@Override
- public void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String hash = req.getParameter("hash");
String type = req.getParameter("type");
if ("email".equals(type)) {
public class ChangeForm extends Form {
private static Template t;
static {
- t = new Template(new InputStreamReader(
- ChangePasswordPage.class
- .getResourceAsStream("ChangePasswordForm.templ")));
+ t = new Template(
+ new InputStreamReader(ChangePasswordPage.class.getResourceAsStream("ChangePasswordForm.templ")));
}
@Override
- public void outputContent(PrintWriter out, Language l,
- Map<String, Object> vars) {
+ public void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
t.output(out, l, vars);
}
}
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
- new ChangeForm().output(resp.getWriter(), getLanguage(req),
- new HashMap<String, Object>());
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+ new ChangeForm().output(resp.getWriter(), getLanguage(req), new HashMap<String, Object>());
}
}
}
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
HashMap<String, Object> vars = new HashMap<String, Object>();
- vars.put("CCA",
- "<a href='/policy/CAcertCommunityAgreement.html'>CCA</a>");
+ vars.put("CCA", "<a href='/policy/CAcertCommunityAgreement.html'>CCA</a>");
getDefaultTemplate().output(resp.getWriter(), getLanguage(req), vars);
}
+
@Override
- public void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
- if (req.getParameter("optionalCSR") == null
- || req.getParameter("optionalCSR").equals("")) {
+ if (req.getParameter("optionalCSR") == null || req.getParameter("optionalCSR").equals("")) {
out.println("csr missing");
ClientCSRGenerate.output(req, resp);
}
// Error.
return;
}
- Certificate c = new Certificate("/commonName=CAcert WoT User",
- "sha256", csr);
+ Certificate c = new Certificate("/commonName=CAcert WoT User", "sha256", csr);
c.issue();
try {
c.waitFor(60000);
}
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
String pi = req.getPathInfo().substring(PATH.length());
if (pi.length() != 0) {
HashMap<String, Object> vars = new HashMap<String, Object>();
User us = LoginPage.getUser(req);
try {
- PreparedStatement ps = DatabaseConnection
- .getInstance()
- .prepare(
- "SELECT `id`, `CN`, `serial`, `revoked`, `expire`, `disablelogin` FROM `emailcerts` WHERE `memid`=?");
+ PreparedStatement ps = DatabaseConnection.getInstance().prepare(
+ "SELECT `id`, `CN`, `serial`, `revoked`, `expire`, `disablelogin` FROM `emailcerts` WHERE `memid`=?");
ps.setInt(1, us.getId());
ResultSet rs = ps.executeQuery();
vars.put("mailcerts", rs);
}
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
final User us = LoginPage.getUser(req);
Language lang = Page.getLanguage(req);
int id = us.getId();
try {
PreparedStatement ps = DatabaseConnection.getInstance().prepare(
- "SELECT * from `email` WHERE `memid`=? AND `deleted`=0");
+ "SELECT * from `email` WHERE `memid`=? AND `deleted`=0");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
HashMap<String, Object> vars = new HashMap<>();
public static final String PATH = "/account/details";
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
User u = (User) req.getSession().getAttribute(USER);
PrintWriter out = resp.getWriter();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("fname", HTMLEncoder.encodeHTML(u.getFname()));
- map.put("mname",
- u.getMname() == null
- ? ""
- : HTMLEncoder.encodeHTML(u.getMname()));
+ map.put("mname", u.getMname() == null ? "" : HTMLEncoder.encodeHTML(u.getMname()));
map.put("lname", HTMLEncoder.encodeHTML(u.getLname()));
- map.put("suffix",
- u.getSuffix() == null ? "" : HTMLEncoder.encodeHTML(u
- .getSuffix()));
+ map.put("suffix", u.getSuffix() == null ? "" : HTMLEncoder.encodeHTML(u.getSuffix()));
DateSelector ds = new DateSelector("day", "month", "year");
map.put("DoB", ds);
map.put("details", "");
}
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
- getDefaultTemplate().output(resp.getWriter(), Page.getLanguage(req),
- null);
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+ getDefaultTemplate().output(resp.getWriter(), Page.getLanguage(req), null);
}
}
}
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
HashMap<String, Object> vars = new HashMap<String, Object>();
getDefaultTemplate().output(out, getLanguage(req), vars);
Signup s = getForm(req);
s.output(out, getLanguage(req), vars);
}
+
public Signup getForm(HttpServletRequest req) {
HttpSession hs = req.getSession();
Signup s = (Signup) hs.getAttribute(SIGNUP_PROCESS);
return s;
}
+
@Override
- public void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Signup s = getForm(req);
if (s.submit(resp.getWriter(), req)) {
HttpSession hs = req.getSession();
hs.setAttribute(SIGNUP_PROCESS, null);
- resp.getWriter()
- .println(
- translate(
- req,
- "Your information has been submitted"
- + " into our system. You will now be sent an email with a web link,"
- + " you need to open that link in your web browser within 24 hours"
- + " or your information will be removed from our system!"));
+ resp.getWriter().println(
+ translate(req, "Your information has been submitted"
+ + " into our system. You will now be sent an email with a web link,"
+ + " you need to open that link in your web browser within 24 hours"
+ + " or your information will be removed from our system!"));
return;
}
super.doPost(req, resp);
}
+
@Override
public boolean needsLogin() {
return false;
User buildup = new User();
Template t;
boolean general = true, country = true, regional = true, radius = true;
+
public Signup() {
try {
- t = new Template(new InputStreamReader(
- Signup.class.getResourceAsStream("Signup.templ"), "UTF-8"));
+ t = new Template(new InputStreamReader(Signup.class.getResourceAsStream("Signup.templ"), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
buildup.setEmail("");
buildup.setDob(new Date(0));
}
+
DateSelector myDoB = new DateSelector("day", "month", "year");
@Override
- public void outputContent(PrintWriter out, Language l,
- Map<String, Object> outerVars) {
+ public void outputContent(PrintWriter out, Language l, Map<String, Object> outerVars) {
HashMap<String, Object> vars = new HashMap<String, Object>();
vars.put("fname", HTMLEncoder.encodeHTML(buildup.getFname()));
vars.put("mname", HTMLEncoder.encodeHTML(buildup.getMname()));
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"),
- "<a href=\"//wiki.cacert.org/FAQ/HowToEnterNamesInJoinForm\" target=\"_blank\">",
- "</a>"));
+ vars.put("helpOnNames", String.format(l.getTranslation("Help on Names %sin the wiki%s"),
+ "<a href=\"//wiki.cacert.org/FAQ/HowToEnterNamesInJoinForm\" target=\"_blank\">", "</a>"));
t.output(out, l, vars);
}
+
private void update(HttpServletRequest r) {
if (r.getParameter("fname") != null) {
buildup.setFname(r.getParameter("fname"));
failed = true;
}
if (!"1".equals(req.getParameter("cca_agree"))) {
- outputError(out, req,
- "You have to agree to the CAcert Community agreement.");
+ outputError(out, req, "You have to agree to the CAcert Community agreement.");
failed = true;
}
if (buildup.getEmail().equals("")) {
}
int pwpoints = PasswordStrengthChecker.checkpw(pw1, buildup);
if (pwpoints < 3) {
- outputError(
- out,
- req,
- "The Pass Phrase you submitted failed to contain enough"
- + " differing characters and/or contained words from"
- + " your name and/or email address.");
+ outputError(out, req, "The Pass Phrase you submitted failed to contain enough"
+ + " differing characters and/or contained words from" + " your name and/or email address.");
failed = true;
}
if (failed) {
}
try {
PreparedStatement q1 = DatabaseConnection.getInstance().prepare(
- "select * from `email` where `email`=? and `deleted`=0");
+ "select * from `email` where `email`=? and `deleted`=0");
PreparedStatement q2 = DatabaseConnection.getInstance().prepare(
- "select * from `users` where `email`=? and `deleted`=0");
+ "select * from `users` where `email`=? and `deleted`=0");
q1.setString(1, buildup.getEmail());
q2.setString(1, buildup.getEmail());
ResultSet r1 = q1.executeQuery();
ResultSet r2 = q2.executeQuery();
if (r1.next() || r2.next()) {
- outputError(out, req,
- "This email address is currently valid in the system.");
+ outputError(out, req, "This email address is currently valid in the system.");
failed = true;
}
r1.close();
r2.close();
- PreparedStatement q3 = DatabaseConnection
- .getInstance()
- .prepare(
- "select `domain` from `baddomains` where `domain`=RIGHT(?, LENGTH(`domain`))");
+ PreparedStatement q3 = DatabaseConnection.getInstance().prepare(
+ "select `domain` from `baddomains` where `domain`=RIGHT(?, LENGTH(`domain`))");
q3.setString(1, buildup.getEmail());
ResultSet r3 = q3.executeQuery();
String domain = r3.getString(1);
out.print("<div>");
out.print(String.format(
- Page.translate(req,
- "We don't allow signups from people using email addresses from %s"),
- domain));
+ Page.translate(req, "We don't allow signups from people using email addresses from %s"), domain));
out.println("</div>");
failed = true;
}
}
String mailResult = EmailProvider.FAIL;
try {
- mailResult = EmailProvider.getInstance().checkEmailServer(0,
- buildup.getEmail());
+ mailResult = EmailProvider.getInstance().checkEmailServer(0, buildup.getEmail());
} catch (IOException e) {
}
if (!mailResult.equals(EmailProvider.OK)) {
if (mailResult.startsWith("4")) {
- outputError(
- out,
- req,
- "The mail server responsible for your domain indicated"
- + " a temporary failure. This may be due to anti-SPAM measures, such"
- + " as greylisting. Please try again in a few minutes.");
+ outputError(out, req, "The mail server responsible for your domain indicated"
+ + " a temporary failure. This may be due to anti-SPAM measures, such"
+ + " as greylisting. Please try again in a few minutes.");
} else {
- outputError(
- out,
- req,
- "Email Address given was invalid, or a test connection"
- + " couldn't be made to your server, or the server"
- + " rejected the email address as invalid");
+ outputError(out, req, "Email Address given was invalid, or a test connection"
+ + " couldn't be made to your server, or the server" + " rejected the email address as invalid");
}
if (mailResult.equals(EmailProvider.FAIL)) {
- outputError(out, req,
- "Failed to make a connection to the mail server");
+ outputError(out, req, "Failed to make a connection to the mail server");
} else {
out.print("<div>");
out.print(mailResult);
return true;
}
- private void run(HttpServletRequest req, String password)
- throws SQLException {
+ private void run(HttpServletRequest req, String password) throws SQLException {
try {
DatabaseConnection.getInstance().beginTransaction();
String hash = RandomToken.generateToken(16);
buildup.insert(password);
int memid = buildup.getId();
PreparedStatement ps = DatabaseConnection.getInstance().prepare(
- "insert into `email` set `email`=?,"
- + " `hash`=?, `created`=NOW(),`memid`=?");
+ "insert into `email` set `email`=?," + " `hash`=?, `created`=NOW(),`memid`=?");
ps.setString(1, buildup.getEmail());
ps.setString(2, hash);
ps.setInt(3, memid);
ps.execute();
int emailid = DatabaseConnection.lastInsertId(ps);
- ps = DatabaseConnection
- .getInstance()
- .prepare(
- "insert into `alerts` set `memid`=?,"
- + " `general`=?, `country`=?, `regional`=?, `radius`=?");
+ ps = DatabaseConnection.getInstance().prepare(
+ "insert into `alerts` set `memid`=?," + " `general`=?, `country`=?, `regional`=?, `radius`=?");
ps.setInt(1, memid);
ps.setString(2, general ? "1" : "0");
ps.setString(3, country ? "1" : "0");
ps.setString(4, regional ? "1" : "0");
ps.setString(5, radius ? "1" : "0");
ps.execute();
- Notary.writeUserAgreement(memid, "CCA", "account creation", "",
- true, 0);
+ Notary.writeUserAgreement(memid, "CCA", "account creation", "", true, 0);
StringBuffer body = new StringBuffer();
body.append(Page
- .translate(
- req,
- "Thanks for signing up with CAcert.org, below is the link you need to open to verify your account. Once your account is verified you will be able to start issuing certificates till your hearts' content!"));
+ .translate(
+ req,
+ "Thanks for signing up with CAcert.org, below is the link you need to open to verify your account. Once your account is verified you will be able to start issuing certificates till your hearts' content!"));
body.append("\n\nhttps://");
body.append(ServerConstants.getWwwHostNamePort());
body.append("/verify?type=email&id=");
body.append(Page.translate(req, "CAcert.org Support!"));
try {
EmailProvider.getInstance().sendmail(buildup.getEmail(),
- "[CAcert.org] " + Page.translate(req, "Mail Probe"),
- body.toString(), "support@cacert.org", null, null,
- null, null, false);
+ "[CAcert.org] " + Page.translate(req, "Mail Probe"), body.toString(), "support@cacert.org", null,
+ null, null, null, false);
} catch (IOException e) {
e.printStackTrace();
}
User assuree;
static final Template templ;
static {
- templ = new Template(new InputStreamReader(
- AssuranceForm.class.getResourceAsStream("AssuranceForm.templ")));
+ templ = new Template(new InputStreamReader(AssuranceForm.class.getResourceAsStream("AssuranceForm.templ")));
}
public AssuranceForm(int assuree) {
this.assuree = new User(assuree);
}
+
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@Override
- public void outputContent(PrintWriter out, Language l,
- Map<String, Object> vars) {
+ public void outputContent(PrintWriter out, Language l, Map<String, Object> vars) {
HashMap<String, Object> res = new HashMap<String, Object>();
res.putAll(vars);
res.put("name", assuree.getName());
out.println("<div class='formError'>");
boolean failed = false;
- if (!"1".equals(req.getParameter("certify"))
- || !"1".equals(req.getParameter("rules"))
- || !"1".equals(req.getParameter("CCAAgreed"))
- || !"1".equals(req.getParameter("assertion"))) {
+ if (!"1".equals(req.getParameter("certify")) || !"1".equals(req.getParameter("rules"))
+ || !"1".equals(req.getParameter("CCAAgreed")) || !"1".equals(req.getParameter("assertion"))) {
outputError(out, req, "You failed to check all boxes to validate"
- + " your adherence to the rules and policies of CAcert");
+ + " your adherence to the rules and policies of CAcert");
failed = true;
}
- if (req.getParameter("date") == null
- || req.getParameter("date").equals("")) {
- outputError(out, req,
- "You must enter the date when you met the assuree.");
+ if (req.getParameter("date") == null || req.getParameter("date").equals("")) {
+ outputError(out, req, "You must enter the date when you met the assuree.");
failed = true;
} else {
try {
Date d = sdf.parse(req.getParameter("date"));
if (d.getTime() > System.currentTimeMillis()) {
- outputError(out, req,
- "You must not enter a date in the future.");
+ outputError(out, req, "You must not enter a date in the future.");
failed = true;
}
} catch (ParseException e) {
- outputError(out, req,
- "You must enter the date in this format: YYYY-MM-DD.");
+ outputError(out, req, "You must enter the date in this format: YYYY-MM-DD.");
failed = true;
}
}
// check location, min 3 characters
- if (req.getParameter("location") == null
- || req.getParameter("location").equals("")) {
- outputError(out, req,
- "You failed to enter a location of your meeting.");
+ if (req.getParameter("location") == null || req.getParameter("location").equals("")) {
+ outputError(out, req, "You failed to enter a location of your meeting.");
failed = true;
} else if (req.getParameter("location").length() <= 2) {
- outputError(out, req,
- "You must enter a location with at least 3 characters eg town and country.");
+ outputError(out, req, "You must enter a location with at least 3 characters eg town and country.");
failed = true;
}
// TODO checkPoints
return false;
}
try {
- AssuranceResult success = Notary.assure(LoginPage.getUser(req),
- assuree, Integer.parseInt(req.getParameter("points")),
- req.getParameter("location"), req.getParameter("date"));
+ AssuranceResult success = Notary.assure(LoginPage.getUser(req), assuree,
+ Integer.parseInt(req.getParameter("points")), req.getParameter("location"), req.getParameter("date"));
if (success != AssuranceResult.ASSURANCE_SUCCEDED) {
outputError(out, req, success.getMessage());
}
public AssurePage() {
super("Assure someone");
- t = new Template(new InputStreamReader(
- AssuranceForm.class.getResourceAsStream("AssureeSearch.templ")));
+ t = new Template(new InputStreamReader(AssuranceForm.class.getResourceAsStream("AssureeSearch.templ")));
}
@Override
- public void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
String pi = req.getPathInfo().substring(PATH.length());
if (pi.length() > 1) {
User myself = LoginPage.getUser(req);
int mid = Integer.parseInt(pi.substring(1));
- AssuranceResult check = Notary.checkAssuranceIsPossible(myself,
- new User(mid));
+ AssuranceResult check = Notary.checkAssuranceIsPossible(myself, new User(mid));
if (check != AssuranceResult.ASSURANCE_SUCCEDED) {
out.println(translate(req, check.getMessage()));
return;
hs.setAttribute(SESSION, form);
}
- form.output(out, getLanguage(req), new HashMap<String, Object>());;
+ form.output(out, getLanguage(req), new HashMap<String, Object>());
+ ;
} else {
HashMap<String, Object> vars = new HashMap<String, Object>();
vars.put("DoB", ds);
t.output(out, getLanguage(req), vars);
}
}
+
@Override
- public void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws IOException {
+ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
String pi = req.getPathInfo().substring(PATH.length());
if (pi.length() > 1) {
return;
}
- AssuranceForm form = (AssuranceForm) req.getSession().getAttribute(
- SESSION);
+ AssuranceForm form = (AssuranceForm) req.getSession().getAttribute(SESSION);
if (form == null) {
out.println("No form found. This is an Error. Fill in the form again.");
return;
System.out.println("searching for");
ResultSet rs = null;
try {
- PreparedStatement ps = DatabaseConnection
- .getInstance()
- .prepare(
- "SELECT id, verified FROM users WHERE email=? AND dob=? AND deleted=0");
+ PreparedStatement ps = DatabaseConnection.getInstance().prepare(
+ "SELECT id, verified FROM users WHERE email=? AND dob=? AND deleted=0");
ps.setString(1, req.getParameter("email"));
- String day = req.getParameter("year") + "-"
- + req.getParameter("month") + "-" + req.getParameter("day");
+ String day = req.getParameter("year") + "-" + req.getParameter("month") + "-" + req.getParameter("day");
ps.setString(2, day);
rs = ps.executeQuery();
int id = 0;
out.println("Error, ambigous user. Please contact support@cacert.org.");
} else {
if (verified == 0) {
- out.println(translate(req,
- "User is not yet verified. Please try again in 24 hours!"));
+ out.println(translate(req, "User is not yet verified. Please try again in 24 hours!"));
}
resp.sendRedirect(PATH + "/" + id);
}
} else {
out.print("<div class='formError'>");
- out.println(translate(
- req,
- "I'm sorry, there was no email and date of birth matching"
- + " what you entered in the system. Please double check"
- + " your information."));
+ out.println(translate(req, "I'm sorry, there was no email and date of birth matching"
+ + " what you entered in the system. Please double check" + " your information."));
out.print("</div>");
}
@Override
public void ping(String domain, String configuration, String expToken) {
try {
- Process p = Runtime.getRuntime().exec(
- new String[]{"dig", "+short", "NS", domain});
- BufferedReader br = new BufferedReader(new InputStreamReader(
- p.getInputStream()));
+ Process p = Runtime.getRuntime().exec(new String[] { "dig", "+short", "NS", domain });
+ BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
LinkedList<String> nameservers = new LinkedList<String>();
while ((line = br.readLine()) != null) {
StringBuffer result = new StringBuffer();
result.append("failed: ");
boolean failed = nameservers.isEmpty();
- nameservers : for (String NS : nameservers) {
- String[] call = new String[]{"dig", "+short", "TXT",
- "cacert." + domain, NS};
+ nameservers: for (String NS : nameservers) {
+ String[] call = new String[] { "dig", "+short", "TXT", "cacert." + domain, NS };
System.out.println(Arrays.toString(call));
p = Runtime.getRuntime().exec(call);
- br = new BufferedReader(new InputStreamReader(
- p.getInputStream()));
+ br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String token = null;
boolean found = false;
while ((line = br.readLine()) != null) {
public void ping(String domain, String configuration, String expToken) {
try {
URL u = new URL("http://" + domain + "/cacert_rai.txt");
- BufferedReader br = new BufferedReader(new InputStreamReader(
- u.openStream(), "UTF-8"));
+ BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream(), "UTF-8"));
String line = br.readLine();
if (line == null) {
// empty
try {
SocketChannel sch = SocketChannel.open();
String[] parts = configuration.split(":", 2);
- sch.connect(new InetSocketAddress(domain, Integer
- .parseInt(parts[0])));
+ sch.connect(new InetSocketAddress(domain, Integer.parseInt(parts[0])));
if (parts.length == 2) {
switch (parts[1]) {
- case "xmpp" :
- startXMPP(sch, false, domain);
- break;
- case "server-xmpp" :
- startXMPP(sch, true, domain);
- break;
- case "smtp" :
- startSMTP(sch);
- break;
- case "imap" :
- startIMAP(sch);
- break;
+ case "xmpp":
+ startXMPP(sch, false, domain);
+ break;
+ case "server-xmpp":
+ startXMPP(sch, true, domain);
+ break;
+ case "smtp":
+ startSMTP(sch);
+ break;
+ case "imap":
+ startIMAP(sch);
+ break;
}
}
}
}
+
private void startIMAP(SocketChannel sch) throws IOException {
Socket s = sch.socket();
InputStream is = s.getInputStream();
os.flush();
scanFor(is, "\n");
}
- private void startXMPP(SocketChannel sch, boolean server, String domain)
- throws IOException {
+
+ private void startXMPP(SocketChannel sch, boolean server, String domain) throws IOException {
Socket s = sch.socket();
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
- os.write(("<stream:stream to=\"" + domain + "\" xmlns=\"jabber:"
- + (server ? "server" : "client") + "\"" + " xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\">")
- .getBytes());
+ os.write(("<stream:stream to=\"" + domain + "\" xmlns=\"jabber:" + (server ? "server" : "client") + "\"" + " xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\">")
+ .getBytes());
os.flush();
- os.write("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>"
- .getBytes());
+ os.write("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>".getBytes());
os.flush();
scanFor(is, "<proceed");
scanFor(is, ">");
}
+
private void scanFor(InputStream is, String scanFor) throws IOException {
int pos = 0;
while (pos < scanFor.length()) {
}
}
}
+
private void startSMTP(SocketChannel sch) throws IOException {
Socket s = sch.socket();
InputStream is = s.getInputStream();
s.getOutputStream().flush();
readSMTP(is);
}
+
private void readSMTP(InputStream is) throws IOException {
int counter = 0;
boolean finish = true;
}
}
}
+
private void test(SocketChannel sch, String domain) {
try {
SSLContext sc = SSLContext.getDefault();
SSLEngine se = sc.createSSLEngine();
- ByteBuffer enc_in = ByteBuffer.allocate(se.getSession()
- .getPacketBufferSize());
- ByteBuffer enc_out = ByteBuffer.allocate(se.getSession()
- .getPacketBufferSize());
- ByteBuffer dec_in = ByteBuffer.allocate(se.getSession()
- .getApplicationBufferSize());
- ByteBuffer dec_out = ByteBuffer.allocate(se.getSession()
- .getApplicationBufferSize());
+ ByteBuffer enc_in = ByteBuffer.allocate(se.getSession().getPacketBufferSize());
+ ByteBuffer enc_out = ByteBuffer.allocate(se.getSession().getPacketBufferSize());
+ ByteBuffer dec_in = ByteBuffer.allocate(se.getSession().getApplicationBufferSize());
+ ByteBuffer dec_out = ByteBuffer.allocate(se.getSession().getApplicationBufferSize());
se.setUseClientMode(true);
SSLParameters sp = se.getSSLParameters();
- sp.setServerNames(Arrays.<SNIServerName> asList(new SNIHostName(
- domain)));
+ sp.setServerNames(Arrays.<SNIServerName> asList(new SNIHostName(domain)));
se.setSSLParameters(sp);
se.beginHandshake();
enc_in.limit(0);
while (se.getHandshakeStatus() != HandshakeStatus.FINISHED
- && se.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) {
+ && se.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) {
switch (se.getHandshakeStatus()) {
- case NEED_WRAP :
- dec_out.limit(0);
- se.wrap(dec_out, enc_out);
- enc_out.flip();
- while (enc_out.remaining() > 0) {
- sch.write(enc_out);
- }
- enc_out.clear();
- break;
- case NEED_UNWRAP :
- if (enc_in.remaining() == 0) {
- enc_in.clear();
- sch.read(enc_in);
- enc_in.flip();
- }
- while (se.unwrap(enc_in, dec_in).getStatus() == Status.BUFFER_UNDERFLOW) {
- enc_in.position(enc_in.limit());
- enc_in.limit(enc_in.capacity());
- sch.read(enc_in);
- enc_in.flip();
- }
- enc_in.compact();
+ case NEED_WRAP:
+ dec_out.limit(0);
+ se.wrap(dec_out, enc_out);
+ enc_out.flip();
+ while (enc_out.remaining() > 0) {
+ sch.write(enc_out);
+ }
+ enc_out.clear();
+ break;
+ case NEED_UNWRAP:
+ if (enc_in.remaining() == 0) {
+ enc_in.clear();
+ sch.read(enc_in);
+ enc_in.flip();
+ }
+ while (se.unwrap(enc_in, dec_in).getStatus() == Status.BUFFER_UNDERFLOW) {
+ enc_in.position(enc_in.limit());
+ enc_in.limit(enc_in.capacity());
+ sch.read(enc_in);
enc_in.flip();
- break;
- case NEED_TASK :
- se.getDelegatedTask().run();
- break;
- case NOT_HANDSHAKING :
- case FINISHED :
+ }
+ enc_in.compact();
+ enc_in.flip();
+ break;
+ case NEED_TASK:
+ se.getDelegatedTask().run();
+ break;
+ case NOT_HANDSHAKING:
+ case FINISHED:
}
}
System.out.println("completed");
System.out.println(se.getSession().getCipherSuite());
- X509Certificate[] peerCertificateChain = se.getSession()
- .getPeerCertificateChain();
+ X509Certificate[] peerCertificateChain = se.getSession().getPeerCertificateChain();
for (X509Certificate x509Certificate : peerCertificateChain) {
System.out.println(x509Certificate.getSubjectDN().getName());
}
public CipherInfoGenerator() throws ReflectiveOperationException {
SSLContextImpl sc = new SSLContextImpl.TLS12Context();
- Method m = SSLContextImpl.class
- .getDeclaredMethod("getSupportedCipherSuiteList");
+ Method m = SSLContextImpl.class.getDeclaredMethod("getSupportedCipherSuiteList");
m.setAccessible(true);
Object o = m.invoke(sc);
Class<?> cipherSuiteList = o.getClass();
macSize = mac.getDeclaredField("size");
macSize.setAccessible(true);
}
- public CipherInfo generateInfo(String suiteName)
- throws IllegalArgumentException, IllegalAccessException {
+
+ public CipherInfo generateInfo(String suiteName) throws IllegalArgumentException, IllegalAccessException {
Object suite = names.get(suiteName);
String keyExchange = exchange.get(suite).toString();
Object bulkCipher = cipher.get(suite);
padding = transformationParts[2];
}
- return new CipherInfo(suiteName, keyExchange,
- transformationParts[0], keysize * 8, chaining, padding,
- macNam, macSiz * 8);
+ return new CipherInfo(suiteName, keyExchange, transformationParts[0], keysize * 8, chaining, padding,
+ macNam, macSiz * 8);
}
}
+
String keyExchange;
String cipher;
int keySize;
int macSize;
String suiteName;
- private CipherInfo(String suiteName, String keyExchange, String cipher,
- int keySize, String cipherChaining, String cipherPadding,
- String macName, int macSize) {
+ private CipherInfo(String suiteName, String keyExchange, String cipher, int keySize, String cipherChaining,
+ String cipherPadding, String macName, int macSize) {
this.suiteName = suiteName;
this.keyExchange = keyExchange;
this.cipher = cipher;
}
return null;
}
+
public String getSuiteName() {
return suiteName;
}
+
/**
* 5: ECDHE, AES||CAMELLIA, keysize >=256 <br>
* 4: DHE, AES||CAMELLIA, keysize >= 256<br>
* @return the strength
*/
public int getStrength() {
- if (cipher.equals("NULL") || cipher.equals("RC4")
- || cipher.contains("DES")) {
+ if (cipher.equals("NULL") || cipher.equals("RC4") || cipher.contains("DES")) {
return 0;
}
boolean ecdhe = keyExchange.startsWith("ECDHE");
}
return 0;
}
- private static final String[] CIPHER_RANKING = new String[]{"CAMELLIA",
- "AES", "RC4", "3DES", "DES", "DES40"};
+
+ private static final String[] CIPHER_RANKING = new String[] { "CAMELLIA", "AES", "RC4", "3DES", "DES", "DES40" };
@Override
public String toString() {
- return "CipherInfo [keyExchange=" + keyExchange + ", cipher=" + cipher
- + ", keySize=" + keySize + ", cipherChaining=" + cipherChaining
- + ", cipherPadding=" + cipherPadding + ", macName=" + macName
- + ", macSize=" + macSize + "]";
+ return "CipherInfo [keyExchange=" + keyExchange + ", cipher=" + cipher + ", keySize=" + keySize
+ + ", cipherChaining=" + cipherChaining + ", cipherPadding=" + cipherPadding + ", macName=" + macName
+ + ", macSize=" + macSize + "]";
}
+
/**
* ECDHE<br>
* GCM<br>
return suiteName.compareTo(o.suiteName);
}
+
static String[] cipherRanking = null;
+
public static String[] getCompleteRanking() {
if (cipherRanking == null) {
- String[] ciphers = filterCiphers((Iterable<String>) cig.names
- .keySet());
+ String[] ciphers = filterCiphers((Iterable<String>) cig.names.keySet());
cipherRanking = ciphers;
}
return cipherRanking;
}
+
private static String[] filterCiphers(Iterable<String> toFilter) {
TreeSet<CipherInfo> chosenCiphers = new TreeSet<CipherInfo>();
for (String o : toFilter) {
}
return ciphers;
}
+
public static String[] filter(String[] supportedCipherSuites) {
return filterCiphers(Arrays.asList(supportedCipherSuites));
}
parent.mkdirs();
return new File(parent, id + ".crt");
}
+
public static File locateCsr(int id) {
File parent = new File(csr, (id / 1000) + "");
parent.mkdirs();
import org.cacert.gigi.database.DatabaseConnection;
public class Notary {
- public static void writeUserAgreement(int memid, String document,
- String method, String comment, boolean active, int secmemid)
- throws SQLException {
- PreparedStatement q = DatabaseConnection
- .getInstance()
- .prepare(
- "insert into `user_agreements` set `memid`=?, `secmemid`=?,"
- + " `document`=?,`date`=NOW(), `active`=?,`method`=?,`comment`=?");
+ public static void writeUserAgreement(int memid, String document, String method, String comment, boolean active,
+ int secmemid) throws SQLException {
+ PreparedStatement q = DatabaseConnection.getInstance().prepare(
+ "insert into `user_agreements` set `memid`=?, `secmemid`=?,"
+ + " `document`=?,`date`=NOW(), `active`=?,`method`=?,`comment`=?");
q.setInt(1, memid);
q.setInt(2, secmemid);
q.setString(3, document);
q.execute();
}
- public static AssuranceResult checkAssuranceIsPossible(User assurer,
- User target) {
+ public static AssuranceResult checkAssuranceIsPossible(User assurer, User target) {
if (assurer.getId() == target.getId()) {
return AssuranceResult.CANNOT_ASSURE_SELF;
}
try {
- PreparedStatement ps = DatabaseConnection
- .getInstance()
- .prepare(
- "SELECT 1 FROM `notary` where `to`=? and `from`=? AND `deleted`=0");
+ PreparedStatement ps = DatabaseConnection.getInstance().prepare(
+ "SELECT 1 FROM `notary` where `to`=? and `from`=? AND `deleted`=0");
ps.setInt(1, target.getId());
ps.setInt(2, assurer.getId());
ResultSet rs = ps.executeQuery();
}
public enum AssuranceResult {
- CANNOT_ASSURE("You cannot assure."), ALREADY_ASSUREED(
- "You already assured this person."), CANNOT_ASSURE_SELF(
- "Cannot assure myself."), ASSURANCE_SUCCEDED(""), ASSUREE_CHANGED(
- "Person details changed. Please start over again."), POINTS_OUT_OF_RANGE(
- "Points out of range.");
+ CANNOT_ASSURE("You cannot assure."), ALREADY_ASSUREED("You already assured this person."), CANNOT_ASSURE_SELF(
+ "Cannot assure myself."), ASSURANCE_SUCCEDED(""), ASSUREE_CHANGED(
+ "Person details changed. Please start over again."), POINTS_OUT_OF_RANGE("Points out of range.");
private final String message;
+
private AssuranceResult(String message) {
this.message = message;
}
+
public String getMessage() {
return message;
}
}
- public synchronized static AssuranceResult assure(User assurer,
- User target, int awarded, String location, String date)
- throws SQLException {
+ public synchronized static AssuranceResult assure(User assurer, User target, int awarded, String location,
+ String date) throws SQLException {
AssuranceResult can = checkAssuranceIsPossible(assurer, target);
if (can != AssuranceResult.ASSURANCE_SUCCEDED) {
return can;
return AssuranceResult.POINTS_OUT_OF_RANGE;
}
- PreparedStatement ps = DatabaseConnection
- .getInstance()
- .prepare(
- "INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?");
+ PreparedStatement ps = DatabaseConnection.getInstance().prepare(
+ "INSERT INTO `notary` SET `from`=?, `to`=?, `points`=?, `location`=?, `date`=?");
ps.setInt(1, assurer.getId());
ps.setInt(2, target.getId());
ps.setInt(3, awarded);
static Pattern upper = Pattern.compile("[A-Z]");
static Pattern whitespace = Pattern.compile("\\s");
static Pattern special = Pattern.compile("(?!\\s)\\W");
+
private PasswordStrengthChecker() {
}
+
private static int checkpwlight(String pw) {
int points = 0;
if (pw.length() > 15) {
}
return points;
}
+
public static int checkpw(String pw, User u) {
if (pw == null) {
return 0;
// TODO dictionary check
return light;
}
+
private static boolean contained(String pw, String check) {
if (check == null || check.equals("")) {
return false;
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++) {
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")) {
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;
}
public class LoginTest extends ManagedTest {
public static final String secureReference = "/account/certs/email";
+
@Test
public void testLoginUnverified() throws IOException {
long uniq = System.currentTimeMillis();
waitForMail();
assertFalse(isLoggedin(login(email, pw)));
}
+
@Test
public void testLoginVerified() throws IOException {
long uniq = System.currentTimeMillis();
createVerifiedUser("an", "bn", email, pw);
assertTrue(isLoggedin(login(email, pw)));
}
+
public boolean isLoggedin(String cookie) throws IOException {
URL u = new URL("https://" + getServerName() + secureReference);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
static {
InitTruststore.run();
}
+
@Test
- public void testClientIntitiatedRenegotiation()
- throws NoSuchAlgorithmException, IOException {
+ public void testClientIntitiatedRenegotiation() throws NoSuchAlgorithmException, IOException {
SSLContext sc = SSLContext.getDefault();
SSLEngine se = sc.createSSLEngine();
String[] serverParts = getServerName().split(":", 2);
- SocketChannel s = SocketChannel.open(new InetSocketAddress(
- serverParts[0], Integer.parseInt(serverParts[1])));
+ SocketChannel s = SocketChannel.open(new InetSocketAddress(serverParts[0], Integer.parseInt(serverParts[1])));
in = ByteBuffer.allocate(se.getSession().getApplicationBufferSize());
inC = ByteBuffer.allocate(se.getSession().getPacketBufferSize());
se.beginHandshake();
try {
work(se, s);
- throw new Error(
- "Client re-negotiation succeded (possible DoS vulnerability");
+ throw new Error("Client re-negotiation succeded (possible DoS vulnerability");
} catch (EOFException e) {
// Cool, server closed connection
}
}
- private void work(SSLEngine se, SocketChannel s) throws SSLException,
- IOException {
+
+ private void work(SSLEngine se, SocketChannel s) throws SSLException, IOException {
while (se.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING
- && se.getHandshakeStatus() != HandshakeStatus.FINISHED) {
+ && se.getHandshakeStatus() != HandshakeStatus.FINISHED) {
switch (se.getHandshakeStatus()) {
- case NEED_WRAP :
- wrap(se, s);
- break;
- case NEED_UNWRAP :
- unwrap(se, s);
- break;
- case NEED_TASK :
- se.getDelegatedTask().run();
- break;
- default :
- System.out.println(se.getHandshakeStatus());
+ case NEED_WRAP:
+ wrap(se, s);
+ break;
+ case NEED_UNWRAP:
+ unwrap(se, s);
+ break;
+ case NEED_TASK:
+ se.getDelegatedTask().run();
+ break;
+ default:
+ System.out.println(se.getHandshakeStatus());
}
}
}
- private SSLEngineResult unwrap(SSLEngine se, SocketChannel s)
- throws IOException, SSLException {
+
+ private SSLEngineResult unwrap(SSLEngine se, SocketChannel s) throws IOException, SSLException {
if (inC.remaining() == 0) {
inC.clear();
s.read(inC);
}
return result;
}
- private SSLEngineResult wrap(SSLEngine se, SocketChannel s)
- throws SSLException, IOException {
+
+ private SSLEngineResult wrap(SSLEngine se, SocketChannel s) throws SSLException, IOException {
outC.clear();
SSLEngineResult result = se.wrap(out, outC);
outC.flip();
public class TestSecurityHeaders extends ManagedTest {
@Test
public void testSTS() throws IOException {
- HttpURLConnection uc = (HttpURLConnection) new URL("https://"
- + getServerName()).openConnection();
+ HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection();
assertNotNull(uc.getHeaderField("Strict-Transport-Security"));
}
public void testCSP() throws IOException {
- HttpURLConnection uc = (HttpURLConnection) new URL("https://"
- + getServerName()).openConnection();
+ HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection();
assertNotNull(uc.getHeaderField("Content-Security-Policy"));
}
+
public void testAllowOrigin() throws IOException {
- HttpURLConnection uc = (HttpURLConnection) new URL("https://"
- + getServerName()).openConnection();
+ HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName()).openConnection();
assertNotNull(uc.getHeaderField("Access-Control-Allow-Origin"));
}
@Test
public void testWebStoreAndLoad() throws SQLException {
- int id = createVerifiedUser("aä", "b", createUniqueName()
- + "a@email.org", "xvXV12°§");
+ int id = createVerifiedUser("aä", "b", createUniqueName() + "a@email.org", "xvXV12°§");
User u = new User(id);
assertEquals("aä", u.getFname());
@Test
public void testAssurerUtilMethods() throws SQLException {
- int id = createAssuranceUser("aä", "b", createUniqueName()
- + "a@email.org", "xvXV12°§");
+ int id = createAssuranceUser("aä", "b", createUniqueName() + "a@email.org", "xvXV12°§");
User u = new User(id);
assertTrue(u.canAssure());
@Before
public void setUp() throws Exception {
}
+
@Test
public void testSuccess() throws IOException {
long uniq = System.currentTimeMillis();
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");
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=-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=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");
+ 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"));
@Test
public void testCheckboxesStay() throws IOException {
String run2 = runRegister("general=1&country=a®ional=1&radius=0");
- assertTrue(run2
- .contains("name=\"general\" value=\"1\" checked=\"checked\">"));
+ assertTrue(run2.contains("name=\"general\" value=\"1\" checked=\"checked\">"));
assertTrue(run2.contains("name=\"country\" value=\"1\">"));
- assertTrue(run2
- .contains("name=\"regional\" value=\"1\" checked=\"checked\">"));
+ assertTrue(run2.contains("name=\"regional\" value=\"1\" checked=\"checked\">"));
assertTrue(run2.contains("name=\"radius\" value=\"1\">"));
run2 = runRegister("general=0&country=1&radius=1");
assertTrue(run2.contains("name=\"general\" value=\"1\">"));
- assertTrue(run2
- .contains("name=\"country\" value=\"1\" checked=\"checked\">"));
+ assertTrue(run2.contains("name=\"country\" value=\"1\" checked=\"checked\">"));
assertTrue(run2.contains("name=\"regional\" value=\"1\">"));
- assertTrue(run2
- .contains("name=\"radius\" value=\"1\" checked=\"checked\">"));
+ assertTrue(run2.contains("name=\"radius\" value=\"1\" checked=\"checked\">"));
}
@Test
public void testDoubleMail() throws IOException {
long uniq = System.currentTimeMillis();
- registerUser("RegisterTest", "User", "testmail" + uniq + "@cacert.org",
- "registerPW'1");
+ registerUser("RegisterTest", "User", "testmail" + uniq + "@cacert.org", "registerPW'1");
try {
- registerUser("RegisterTest", "User", "testmail" + uniq
- + "@cacert.org", "registerPW");
- throw new Error(
- "Registering a user with the same email needs to fail.");
+ registerUser("RegisterTest", "User", "testmail" + uniq + "@cacert.org", "registerPW");
+ throw new Error("Registering a user with the same email needs to fail.");
} catch (AssertionError e) {
}
}
+
@Test
public void testInvalidMailbox() {
getMailReciever().setApproveRegex(Pattern.compile("a"));
long uniq = System.currentTimeMillis();
try {
- registerUser("RegisterTest", "User", "testInvalidMailbox" + uniq
- + "@cacert.org", "registerPW");
- throw new Error(
- "Registering a user with invalid mailbox must fail.");
+ registerUser("RegisterTest", "User", "testInvalidMailbox" + uniq + "@cacert.org", "registerPW");
+ throw new Error("Registering a user with invalid mailbox must fail.");
} catch (AssertionError e) {
}
}
+
private void testFailedForm(String query) throws IOException {
String startError = fetchStartErrorMessage(runRegister(query));
assertTrue(startError, !startError.startsWith("</div>"));
private int assurer;
private int assuree;
private String cookie;
+
@Before
public void setup() throws IOException {
assurerM = createUniqueName() + "@cacert-test.org";
cookie = login(assurerM, "xvXV.1");
}
+
@Test
public void testAssureSearch() throws IOException {
- String loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8")
- + "&day=1&month=1&year=1910");
+ String loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=1&year=1910");
assertTrue(loc, loc.endsWith(AssurePage.PATH + "/" + assuree));
}
@Test
public void testAssureSearchEmail() throws IOException {
- String loc = search("email=1" + URLEncoder.encode(assureeM, "UTF-8")
- + "&day=1&month=1&year=1910");
+ String loc = search("email=1" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=1&year=1910");
assertNull(loc);
}
+
@Test
public void testAssureSearchDob() throws IOException {
- String loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8")
- + "&day=2&month=1&year=1910");
+ String loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=2&month=1&year=1910");
assertNull(loc);
- loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8")
- + "&day=1&month=2&year=1910");
+ loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=2&year=1910");
assertNull(loc);
- loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8")
- + "&day=1&month=1&year=1911");
+ loc = search("email=" + URLEncoder.encode(assureeM, "UTF-8") + "&day=1&month=1&year=1911");
assertNull(loc);
}
- private String search(String query) throws MalformedURLException,
- IOException, UnsupportedEncodingException {
+
+ private String search(String query) throws MalformedURLException, IOException, UnsupportedEncodingException {
URL u = new URL("https://" + getServerName() + AssurePage.PATH);
URLConnection uc = u.openConnection();
uc.setDoOutput(true);
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");
public void testAssureFormNoCSRF() throws IOException {
// override csrf
HttpURLConnection uc = (HttpURLConnection) buildupAssureFormConnection(false);
- uc.getOutputStream()
- .write(("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10")
- .getBytes());
+ uc.getOutputStream().write(
+ ("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10").getBytes());
uc.getOutputStream().flush();
assertEquals(500, uc.getResponseCode());
}
+
@Test
public void testAssureFormWrongCSRF() throws IOException {
// override csrf
HttpURLConnection uc = (HttpURLConnection) buildupAssureFormConnection(false);
- uc.getOutputStream()
- .write(("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10&csrf=aragc")
- .getBytes());
+ uc.getOutputStream().write(
+ ("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10&csrf=aragc")
+ .getBytes());
uc.getOutputStream().flush();
assertEquals(500, uc.getResponseCode());
}
+
@Test
public void testAssureFormRace() throws IOException, SQLException {
URLConnection uc = buildupAssureFormConnection(true);
- PreparedStatement ps = DatabaseConnection.getInstance().prepare(
- "UPDATE `users` SET email='changed' WHERE id=?");
+ PreparedStatement ps = DatabaseConnection.getInstance()
+ .prepare("UPDATE `users` SET email='changed' WHERE id=?");
ps.setInt(1, assuree);
ps.execute();
- uc.getOutputStream()
- .write(("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10")
- .getBytes());
+ uc.getOutputStream().write(
+ ("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10").getBytes());
uc.getOutputStream().flush();
String error = fetchStartErrorMessage(IOUtils.readURL(uc));
assertTrue(error, !error.startsWith("</div>"));
}
+
@Test
public void testAssureFormFuture() throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("YYYY");
- int year = Integer.parseInt(sdf.format(new Date(System
- .currentTimeMillis()))) + 2;
- String error = getError("date="
- + year
- + "-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
+ int year = Integer.parseInt(sdf.format(new Date(System.currentTimeMillis()))) + 2;
+ String error = getError("date=" + year
+ + "-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
assertTrue(error, !error.startsWith("</div>"));
}
+
@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");
error = getError("date=&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=1&points=10");
assertTrue(error, !error.startsWith("</div>"));
}
+
@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");
error = getError("date=2000-01-01&location=testcase&certify=1&rules=1&CCAAgreed=1&assertion=z&points=10");
assertTrue(error, !error.startsWith("</div>"));
}
- private String getError(String query) throws MalformedURLException,
- IOException {
+
+ private String getError(String query) throws MalformedURLException, IOException {
URLConnection uc = buildupAssureFormConnection(true);
uc.getOutputStream().write((query).getBytes());
uc.getOutputStream().flush();
String error = fetchStartErrorMessage(IOUtils.readURL(uc));
return error;
}
- private URLConnection buildupAssureFormConnection(boolean doCSRF)
- throws MalformedURLException, IOException {
- URL u = new URL("https://" + getServerName() + AssurePage.PATH + "/"
- + assuree);
+
+ private URLConnection buildupAssureFormConnection(boolean doCSRF) throws MalformedURLException, IOException {
+ URL u = new URL("https://" + getServerName() + AssurePage.PATH + "/" + assuree);
URLConnection uc = u.openConnection();
uc.addRequestProperty("Cookie", cookie);
String csrf = getCSRF(uc);
private IOUtils() {
}
+
public static String readURL(URLConnection in) {
try {
if (!in.getContentType().equals("text/html; charset=UTF-8")) {
- throw new Error("Unrecognized content-type: "
- + in.getContentType());
+ throw new Error("Unrecognized content-type: " + in.getContentType());
}
return readURL(new InputStreamReader(in.getInputStream(), "UTF-8"));
} catch (IOException e) {
}
}
+
public static String readURL(Reader in) {
CharArrayWriter caw = new CharArrayWriter();
char[] buffer = new char[1024];
public class InitTruststore {
private InitTruststore() {
}
+
static {
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
System.setProperty("javax.net.ssl.trustStore", "config/cacerts.jks");
}
+
public static void run() {
}
public static String getServerName() {
return url;
}
+
static Properties testProps = new Properties();
static {
InitTruststore.run();
DatabaseConnection.init(testProps);
}
System.out.println("... purging Database");
- DatabaseManager.run(new String[]{
- testProps.getProperty("sql.driver"),
- testProps.getProperty("sql.url"),
- testProps.getProperty("sql.user"),
- testProps.getProperty("sql.password")});
+ DatabaseManager.run(new String[] { testProps.getProperty("sql.driver"), testProps.getProperty("sql.url"),
+ testProps.getProperty("sql.user"), testProps.getProperty("sql.password") });
String type = testProps.getProperty("type");
if (type.equals("local")) {
url = testProps.getProperty("server");
String[] parts = testProps.getProperty("mail").split(":", 2);
- ter = new TestEmailReciever(new InetSocketAddress(parts[0],
- Integer.parseInt(parts[1])));
+ ter = new TestEmailReciever(new InetSocketAddress(parts[0], Integer.parseInt(parts[1])));
return;
}
- url = testProps.getProperty("name.www") + ":"
- + testProps.getProperty("serverPort");
+ url = testProps.getProperty("name.www") + ":" + testProps.getProperty("serverPort");
gigi = Runtime.getRuntime().exec(testProps.getProperty("java"));
- DataOutputStream toGigi = new DataOutputStream(
- gigi.getOutputStream());
+ DataOutputStream toGigi = new DataOutputStream(gigi.getOutputStream());
System.out.println("... starting server");
Properties mainProps = new Properties();
mainProps.setProperty("host", "127.0.0.1");
mainProps.setProperty("name.secure", "sec");
- mainProps
- .setProperty("name.www", testProps.getProperty("name.www"));
+ mainProps.setProperty("name.www", testProps.getProperty("name.www"));
mainProps.setProperty("name.static", "stat");
mainProps.setProperty("port", testProps.getProperty("serverPort"));
- mainProps.setProperty("emailProvider",
- "org.cacert.gigi.email.TestEmailProvider");
+ mainProps.setProperty("emailProvider", "org.cacert.gigi.email.TestEmailProvider");
mainProps.setProperty("emailProvider.port", "8473");
- mainProps.setProperty("sql.driver",
- testProps.getProperty("sql.driver"));
+ mainProps.setProperty("sql.driver", testProps.getProperty("sql.driver"));
mainProps.setProperty("sql.url", testProps.getProperty("sql.url"));
- mainProps
- .setProperty("sql.user", testProps.getProperty("sql.user"));
- mainProps.setProperty("sql.password",
- testProps.getProperty("sql.password"));
+ mainProps.setProperty("sql.user", testProps.getProperty("sql.user"));
+ mainProps.setProperty("sql.password", testProps.getProperty("sql.password"));
- byte[] cacerts = Files
- .readAllBytes(Paths.get("config/cacerts.jks"));
- byte[] keystore = Files.readAllBytes(Paths
- .get("config/keystore.pkcs12"));
+ byte[] cacerts = Files.readAllBytes(Paths.get("config/cacerts.jks"));
+ byte[] keystore = Files.readAllBytes(Paths.get("config/keystore.pkcs12"));
- DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(),
- "changeit".getBytes(), mainProps, cacerts, keystore);
+ DevelLauncher.writeGigiConfig(toGigi, "changeit".getBytes(), "changeit".getBytes(), mainProps, cacerts,
+ keystore);
toGigi.flush();
- final BufferedReader br = new BufferedReader(new InputStreamReader(
- gigi.getErrorStream()));
+ final BufferedReader br = new BufferedReader(new InputStreamReader(gigi.getErrorStream()));
String line;
- while ((line = br.readLine()) != null
- && !line.contains("Server:main: Started")) {
+ while ((line = br.readLine()) != null && !line.contains("Server:main: Started")) {
}
new Thread() {
@Override
if (line == null) {
throw new Error("Server startup failed");
}
- ter = new TestEmailReciever(
- new InetSocketAddress("localhost", 8473));
+ ter = new TestEmailReciever(new InetSocketAddress("localhost", 8473));
} catch (IOException e) {
throw new Error(e);
} catch (ClassNotFoundException e1) {
}
}
+
@AfterClass
public static void tearDownServer() {
String type = testProps.getProperty("type");
}
gigi.destroy();
}
+
@After
public void removeMails() {
ter.reset();
throw new Error(e);
}
}
+
public static TestEmailReciever getMailReciever() {
return ter;
}
+
public String runRegister(String param) throws IOException {
- HttpURLConnection uc = (HttpURLConnection) new URL("https://"
- + getServerName() + registerService).openConnection();
+ HttpURLConnection uc = (HttpURLConnection) new URL("https://" + getServerName() + registerService)
+ .openConnection();
uc.setDoOutput(true);
uc.getOutputStream().write(param.getBytes());
String d = IOUtils.readURL(uc);
return d;
}
+
public String fetchStartErrorMessage(String d) throws IOException {
String formFail = "<div class='formError'>";
int idx = d.indexOf(formFail);
assertNotEquals(-1, idx);
- String startError = d.substring(idx + formFail.length(), idx + 100)
- .trim();
+ String startError = d.substring(idx + formFail.length(), idx + 100).trim();
return startError;
}
- public void registerUser(String firstName, String lastName, String email,
- String password) {
+ public void registerUser(String firstName, String lastName, String email, String password) {
try {
- String query = "fname=" + URLEncoder.encode(firstName, "UTF-8")
- + "&lname=" + URLEncoder.encode(lastName, "UTF-8")
- + "&email=" + URLEncoder.encode(email, "UTF-8")
- + "&pword1=" + URLEncoder.encode(password, "UTF-8")
- + "&pword2=" + URLEncoder.encode(password, "UTF-8")
- + "&day=1&month=1&year=1910&cca_agree=1";
+ String query = "fname=" + URLEncoder.encode(firstName, "UTF-8") + "&lname="
+ + URLEncoder.encode(lastName, "UTF-8") + "&email=" + URLEncoder.encode(email, "UTF-8") + "&pword1="
+ + URLEncoder.encode(password, "UTF-8") + "&pword2=" + URLEncoder.encode(password, "UTF-8")
+ + "&day=1&month=1&year=1910&cca_agree=1";
String data = fetchStartErrorMessage(runRegister(query));
assertTrue(data, data.startsWith("</div>"));
} catch (UnsupportedEncodingException e) {
throw new Error(e);
}
}
- public int createVerifiedUser(String firstName, String lastName,
- String email, String password) {
+
+ public int createVerifiedUser(String firstName, String lastName, String email, String password) {
registerUser(firstName, lastName, email, password);
try {
TestMail tm = ter.recieve();
String verifyLink = tm.extractLink();
String[] parts = verifyLink.split("\\?");
- URL u = new URL("https://" + getServerName() + "/verify?"
- + parts[1]);
- u.openStream().close();;
- PreparedStatement ps = DatabaseConnection.getInstance().prepare(
- "SELECT id FROM users where email=?");
+ URL u = new URL("https://" + getServerName() + "/verify?" + parts[1]);
+ u.openStream().close();
+ ;
+ PreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT id FROM users where email=?");
ps.setString(1, email);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
throw new Error(e);
}
}
+
/**
* Creates a new user with 100 Assurance points given by an (invalid)
* assurance.
* the password
* @return a new userid.
*/
- public int createAssuranceUser(String firstName, String lastName,
- String email, String password) {
+ public int createAssuranceUser(String firstName, String lastName, String email, String password) {
int uid = createVerifiedUser(firstName, lastName, email, password);
try {
- PreparedStatement ps = DatabaseConnection
- .getInstance()
- .prepare(
- "INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
+ PreparedStatement ps = DatabaseConnection.getInstance().prepare(
+ "INSERT INTO `cats_passed` SET `user_id`=?, `variant_id`=?");
ps.setInt(1, uid);
ps.setInt(2, 0);
ps.execute();
- ps = DatabaseConnection.getInstance().prepare(
- "INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
+ ps = DatabaseConnection.getInstance().prepare("INSERT INTO `notary` SET `from`=?, `to`=?, points='100'");
ps.setInt(1, uid);
ps.setInt(2, uid);
ps.execute();
}
return uid;
}
+
static int count = 0;
+
public String createUniqueName() {
return "test" + System.currentTimeMillis() + "a" + (count++);
}
+
public String login(String email, String pw) throws IOException {
URL u = new URL("https://" + getServerName() + "/login");
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setDoOutput(true);
OutputStream os = huc.getOutputStream();
- String data = "username=" + URLEncoder.encode(email, "UTF-8")
- + "&password=" + URLEncoder.encode(pw, "UTF-8");
+ String data = "username=" + URLEncoder.encode(email, "UTF-8") + "&password=" + URLEncoder.encode(pw, "UTF-8");
os.write(data.getBytes());
os.flush();
String headerField = huc.getHeaderField("Set-Cookie");
String message;
String from;
String replyto;
- public TestMail(String to, String subject, String message, String from,
- String replyto) {
+
+ public TestMail(String to, String subject, String message, String from, String replyto) {
this.to = to;
this.subject = subject;
this.message = message;
this.from = from;
this.replyto = replyto;
}
+
public String getTo() {
return to;
}
+
public String getSubject() {
return subject;
}
+
public String getMessage() {
return message;
}
+
public String getFrom() {
return from;
}
+
public String getReplyto() {
return replyto;
}
+
public String extractLink() {
Pattern link = Pattern.compile("https?://[^\\s]+(?=\\s)");
Matcher m = link.matcher(getMessage());
}
}
+
private Socket s;
private DataInputStream dis;
private DataOutputStream dos;
dos = new DataOutputStream(s.getOutputStream());
new Thread(this).start();
}
+
LinkedBlockingQueue<TestMail> mails = new LinkedBlockingQueue<TestEmailReciever.TestMail>();
public TestMail recieve() throws InterruptedException {
return mails.poll(5, TimeUnit.SECONDS);
}
+
@Override
public void run() {
try {
}
}
+
Pattern approveRegex = Pattern.compile(".*");
+
public void setApproveRegex(Pattern approveRegex) {
this.approveRegex = approveRegex;
}
public void clearMails() {
mails.clear();
}
+
public void reset() {
clearMails();
approveRegex = Pattern.compile(".*");
}
+
boolean closed = false;
+
public void destroy() {
try {
closed = true;
public void testEncodeSimpleString() {
assertEquals("1234_ä", HTMLEncoder.encodeHTML("1234_ä"));
}
+
@Test
public void testEncodeQuotes() {
assertEquals("\\"_ä.", HTMLEncoder.encodeHTML("\\\"_ä."));
}
+
@Test
public void testEncodeTagString() {
- assertEquals("<td class="&amp;">",
- HTMLEncoder.encodeHTML("<td class=\"&\">"));
+ assertEquals("<td class="&amp;">", HTMLEncoder.encodeHTML("<td class=\"&\">"));
}
+
@Test
public void testEncodeSingleQuoteString() {
assertEquals("'&#39;", HTMLEncoder.encodeHTML("''"));
public void testNormalAssurance() throws SQLException {
User[] users = new User[30];
for (int i = 0; i < users.length; i++) {
- int id = createVerifiedUser("fn" + i, "ln" + i, createUniqueName()
- + "@email.org", "xvXV12°§");
+ int id = createVerifiedUser("fn" + i, "ln" + i, createUniqueName() + "@email.org", "xvXV12°§");
users[i] = new User(id);
}
- User assurer = new User(createAssuranceUser("fn", "ln",
- createUniqueName() + "@email.org", "xvXV12°§"));
- int[] result = new int[]{10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20,
- 20, 20, 20, 25, 25, 25, 25, 25, 30, 30, 30, 30, 30, 35, 35, 35,
- 35, 35, 35};
+ User assurer = new User(createAssuranceUser("fn", "ln", createUniqueName() + "@email.org", "xvXV12°§"));
+ int[] result = new int[] { 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20, 20, 25, 25, 25, 25, 25, 30, 30,
+ 30, 30, 30, 35, 35, 35, 35, 35, 35 };
System.out.println(result.length);
- assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(
- assurer, users[0], -1, "test-notary", "2014-01-01"));
+ assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED,
+ Notary.assure(assurer, users[0], -1, "test-notary", "2014-01-01"));
for (int i = 0; i < result.length; i++) {
assertEquals(result[i], assurer.getMaxAssurePoints());
- assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(
- assurer, users[i], result[i] + 1, "test-notary",
- "2014-01-01"));
- assertEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(
- assurer, users[i], result[i], "test-notary", "2014-01-01"));
- assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(
- assurer, users[i], result[i], "test-notary", "2014-01-01"));
+ assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED,
+ Notary.assure(assurer, users[i], result[i] + 1, "test-notary", "2014-01-01"));
+ assertEquals(AssuranceResult.ASSURANCE_SUCCEDED,
+ Notary.assure(assurer, users[i], result[i], "test-notary", "2014-01-01"));
+ assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED,
+ Notary.assure(assurer, users[i], result[i], "test-notary", "2014-01-01"));
}
assertEquals(35, assurer.getMaxAssurePoints());
public void testPoJam() throws SQLException {
User[] users = new User[30];
for (int i = 0; i < users.length; i++) {
- int id = createVerifiedUser("fn" + i, "ln" + i, createUniqueName()
- + "@email.org", "xvXV12°§");
+ int id = createVerifiedUser("fn" + i, "ln" + i, createUniqueName() + "@email.org", "xvXV12°§");
users[i] = new User(id);
}
- int id = createAssuranceUser("fn", "ln", createUniqueName()
- + "@email.org", "xvXV12°§");
- PreparedStatement ps = DatabaseConnection.getInstance().prepare(
- "UPDATE users SET dob=NOW() WHERE id=?");
+ int id = createAssuranceUser("fn", "ln", createUniqueName() + "@email.org", "xvXV12°§");
+ PreparedStatement ps = DatabaseConnection.getInstance().prepare("UPDATE users SET dob=NOW() WHERE id=?");
ps.setInt(1, id);
ps.execute();
User assurer = new User(id);
for (int i = 0; i < users.length; i++) {
- assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(
- assurer, users[i], -1, "test-notary", "2014-01-01"));
- assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(
- assurer, users[i], 11, "test-notary", "2014-01-01"));
- assertEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(
- assurer, users[i], 10, "test-notary", "2014-01-01"));
- assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED, Notary.assure(
- assurer, users[i], 10, "test-notary", "2014-01-01"));
+ assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED,
+ Notary.assure(assurer, users[i], -1, "test-notary", "2014-01-01"));
+ assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED,
+ Notary.assure(assurer, users[i], 11, "test-notary", "2014-01-01"));
+ assertEquals(AssuranceResult.ASSURANCE_SUCCEDED,
+ Notary.assure(assurer, users[i], 10, "test-notary", "2014-01-01"));
+ assertNotEquals(AssuranceResult.ASSURANCE_SUCCEDED,
+ Notary.assure(assurer, users[i], 10, "test-notary", "2014-01-01"));
}
}
}
assertTrue(PasswordHash.verifyHash("a", PasswordHash.hash("a")));
assertTrue(PasswordHash.verifyHash("", PasswordHash.hash("")));
assertTrue(PasswordHash.verifyHash("a1234", PasswordHash.hash("a1234")));
- assertTrue(PasswordHash.verifyHash("auhlcb4 9x,IUQẞ&lvrvä",
- PasswordHash.hash("auhlcb4 9x,IUQẞ&lvrvä")));
+ assertTrue(PasswordHash.verifyHash("auhlcb4 9x,IUQẞ&lvrvä", PasswordHash.hash("auhlcb4 9x,IUQẞ&lvrvä")));
}
+
@Test
public void testVerifyNegative() {
assertFalse(PasswordHash.verifyHash("b", PasswordHash.hash("a")));
- assertFalse(PasswordHash.verifyHash("ae",
- PasswordHash.hash("auhlcb4 9x,IUQẞ&lvrvä")));
+ assertFalse(PasswordHash.verifyHash("ae", PasswordHash.hash("auhlcb4 9x,IUQẞ&lvrvä")));
}
}
public class TestPasswordStrengthChecker {
User u;
+
public TestPasswordStrengthChecker() {
u = new User();
u.setFname("fname");
u.setEmail("email");
u.setSuffix("suffix");
}
+
@Test
public void testPasswordLength() {
assertEquals(1, PasswordStrengthChecker.checkpw("01234", u));
assertEquals(2, PasswordStrengthChecker.checkpw("0123456789012345", u));
- assertEquals(3,
- PasswordStrengthChecker.checkpw("012345678901234567890", u));
- assertEquals(4, PasswordStrengthChecker.checkpw(
- "01234567890123456789012345", u));
- assertEquals(5, PasswordStrengthChecker.checkpw(
- "0123456789012345678901234567890", u));
+ assertEquals(3, PasswordStrengthChecker.checkpw("012345678901234567890", u));
+ assertEquals(4, PasswordStrengthChecker.checkpw("01234567890123456789012345", u));
+ assertEquals(5, PasswordStrengthChecker.checkpw("0123456789012345678901234567890", u));
}
+
@Test
public void testPasswordNonASCII() {
assertEquals(2, PasswordStrengthChecker.checkpw("0ä", u));
assertEquals(3, PasswordStrengthChecker.checkpw("0azä", u));
assertEquals(3, PasswordStrengthChecker.checkpw("0az.ä", u));
}
+
@Test
public void testPasswordCharTypes() {
assertEquals(1, PasswordStrengthChecker.checkpw("0", u));
assertEquals(2, PasswordStrengthChecker.checkpw(" Z", u));
}
+
@Test
public void testPasswordContains() {
assertEquals(-1, PasswordStrengthChecker.checkpw("fnamea", u));
public static String readFile(File f) throws IOException {
return new String(Files.readAllBytes(f.toPath()));
}
- public static void main(String[] args) throws SQLException,
- ClassNotFoundException, IOException {
+
+ public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
if (args.length == 0) {
Properties p = new Properties();
p.load(new FileReader("config/gigi.properties"));
- args = new String[]{p.getProperty("sql.driver"),
- p.getProperty("sql.url"), p.getProperty("sql.user"),
- p.getProperty("sql.password")};
+ args = new String[] { p.getProperty("sql.driver"), p.getProperty("sql.url"), p.getProperty("sql.user"),
+ p.getProperty("sql.password") };
}
if (args.length < 4) {
- System.err
- .println("Usage: com.mysql.jdbc.Driver jdbc:mysql://localhost/cacert user password");
+ System.err.println("Usage: com.mysql.jdbc.Driver jdbc:mysql://localhost/cacert user password");
return;
}
run(args);
}
- public static void run(String[] args) throws ClassNotFoundException,
- SQLException, IOException {
+
+ public static void run(String[] args) throws ClassNotFoundException, SQLException, IOException {
Class.forName(args[0]);
- Connection conn = DriverManager
- .getConnection(args[1], args[2], args[3]);
+ Connection conn = DriverManager.getConnection(args[1], args[2], args[3]);
Statement stmt = conn.createStatement();
addFile(stmt, new File("doc/tableStructure.sql"));
File localData = new File("doc/sampleData.sql");
stmt.executeBatch();
stmt.close();
}
- private static void addFile(Statement stmt, File f) throws IOException,
- SQLException {
+
+ private static void addFile(Statement stmt, File f) throws IOException, SQLException {
String sql = readFile(f);
String[] stmts = sql.split(";");
for (String string : stmts) {
public class FetchLocales {
public static final String DOWNLOAD_SERVER = "translations.cacert.org";
- public static final String PO_URL_TEMPLATE = "http://" + DOWNLOAD_SERVER
- + "/export/cacert/%/messages.po";
- public static final String[] AUTO_LANGS = new String[]{"en", "de", "nl",
- "pt_BR", "fr", "sv", "it", "es", "hu", "fi", "ja", "bg", "pt",
- "da", "pl", "zh_CN", "ru", "lv", "cs", "zh_TW", "el", "tr", "ar"};
- public static void main(String[] args) throws IOException,
- ParserConfigurationException, TransformerException {
+ public static final String PO_URL_TEMPLATE = "http://" + DOWNLOAD_SERVER + "/export/cacert/%/messages.po";
+ public static final String[] AUTO_LANGS = new String[] { "en", "de", "nl", "pt_BR", "fr", "sv", "it", "es", "hu",
+ "fi", "ja", "bg", "pt", "da", "pl", "zh_CN", "ru", "lv", "cs", "zh_TW", "el", "tr", "ar" };
+
+ public static void main(String[] args) throws IOException, ParserConfigurationException, TransformerException {
System.out.println("downloading locales ...");
File locale = new File("locale");
locale.mkdir();
contents.delete(0, contents.length());
// System.out.println("msgstr");
s = readString(s, sc, contents);
- String msg = contents.toString().replace("\\\"", "\"")
- .replace("\\n", "\n");
+ String msg = contents.toString().replace("\\\"", "\"").replace("\\n", "\n");
insertTranslation(doc, id, msg);
} else if (s.startsWith("#")) {
// System.out.println(s);
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
- FileOutputStream fos = new FileOutputStream(new File(locale, lang
- + ".xml"));
+ FileOutputStream fos = new FileOutputStream(new File(locale, lang + ".xml"));
StreamResult result = new StreamResult(fos);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
- transformer.setOutputProperty(
- "{http://xml.apache.org/xslt}indent-amount", "2");
+ transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(source, result);
fos.close();
}
}
+
private static String readLine(Scanner sc) {
String line = sc.findWithinHorizon("[^\n]*\n", 0);
if (line == null) {
}
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);
tr.appendChild(e);
doc.getDocumentElement().appendChild(tr);
}
- private static String readString(String head, Scanner sc,
- StringBuffer contents) throws IOException {
+
+ private static String readString(String head, Scanner sc, StringBuffer contents) throws IOException {
head = head.split(" ", 2)[1];
contents.append(head.substring(1, head.length() - 1));
String s;
DatabaseConnection.init(p);
readyMail = DatabaseConnection.getInstance().prepare(
- "SELECT id, csr_name, subject FROM emailcerts" + " WHERE csr_name is not null"//
- + " AND created=0"//
- + " AND crt_name=''"//
- + " AND warning<3");
+ "SELECT id, csr_name, subject FROM emailcerts" + " WHERE csr_name is not null"//
+ + " AND created=0"//
+ + " AND crt_name=''"//
+ + " AND warning<3");
updateMail = DatabaseConnection.getInstance().prepare(
- "UPDATE emailcerts SET crt_name=?," + " created=NOW(), serial=? WHERE id=?");
+ "UPDATE emailcerts SET crt_name=?," + " created=NOW(), serial=? WHERE id=?");
warnMail = DatabaseConnection.getInstance().prepare("UPDATE emailcerts SET warning=warning+1 WHERE id=?");
revoke = DatabaseConnection.getInstance().prepare(
- "SELECT id, csr_name FROM emailcerts" + " WHERE csr_name is not null"//
- + " AND created != 0"//
- + " AND revoked = '1970-01-01'");
+ "SELECT id, csr_name FROM emailcerts" + " WHERE csr_name is not null"//
+ + " AND created != 0"//
+ + " AND revoked = '1970-01-01'");
revokeCompleted = DatabaseConnection.getInstance().prepare("UPDATE emailcerts SET revoked=NOW() WHERE id=?");
gencrl();
while (true) {