1 package org.cacert.gigi;
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.io.UnsupportedEncodingException;
6 import java.security.KeyStore;
7 import java.security.cert.X509Certificate;
8 import java.util.Calendar;
9 import java.util.Collections;
10 import java.util.HashMap;
11 import java.util.LinkedList;
12 import java.util.Locale;
14 import java.util.Properties;
15 import java.util.regex.Pattern;
17 import javax.servlet.ServletException;
18 import javax.servlet.http.HttpServlet;
19 import javax.servlet.http.HttpServletRequest;
20 import javax.servlet.http.HttpServletResponse;
21 import javax.servlet.http.HttpSession;
23 import org.cacert.gigi.database.DatabaseConnection;
24 import org.cacert.gigi.database.DatabaseConnection.Link;
25 import org.cacert.gigi.dbObjects.CACertificate;
26 import org.cacert.gigi.dbObjects.CATS.CATSType;
27 import org.cacert.gigi.dbObjects.CertificateProfile;
28 import org.cacert.gigi.dbObjects.DomainPingConfiguration;
29 import org.cacert.gigi.localisation.Language;
30 import org.cacert.gigi.output.Menu;
31 import org.cacert.gigi.output.MenuCollector;
32 import org.cacert.gigi.output.PageMenuItem;
33 import org.cacert.gigi.output.SimpleMenuItem;
34 import org.cacert.gigi.output.template.Form;
35 import org.cacert.gigi.output.template.Form.CSRFException;
36 import org.cacert.gigi.output.template.Outputable;
37 import org.cacert.gigi.output.template.Template;
38 import org.cacert.gigi.pages.AboutPage;
39 import org.cacert.gigi.pages.HandlesMixedRequest;
40 import org.cacert.gigi.pages.LoginPage;
41 import org.cacert.gigi.pages.LogoutPage;
42 import org.cacert.gigi.pages.MainPage;
43 import org.cacert.gigi.pages.OneFormPage;
44 import org.cacert.gigi.pages.Page;
45 import org.cacert.gigi.pages.PasswordResetPage;
46 import org.cacert.gigi.pages.RootCertPage;
47 import org.cacert.gigi.pages.StaticPage;
48 import org.cacert.gigi.pages.TestSecure;
49 import org.cacert.gigi.pages.Verify;
50 import org.cacert.gigi.pages.account.ChangePasswordPage;
51 import org.cacert.gigi.pages.account.FindAgentAccess;
52 import org.cacert.gigi.pages.account.History;
53 import org.cacert.gigi.pages.account.MyDetails;
54 import org.cacert.gigi.pages.account.UserTrainings;
55 import org.cacert.gigi.pages.account.certs.CertificateAdd;
56 import org.cacert.gigi.pages.account.certs.Certificates;
57 import org.cacert.gigi.pages.account.domain.DomainOverview;
58 import org.cacert.gigi.pages.account.mail.MailOverview;
59 import org.cacert.gigi.pages.admin.TTPAdminPage;
60 import org.cacert.gigi.pages.admin.support.FindDomainPage;
61 import org.cacert.gigi.pages.admin.support.FindUserPage;
62 import org.cacert.gigi.pages.admin.support.SupportEnterTicketPage;
63 import org.cacert.gigi.pages.admin.support.SupportUserDetailsPage;
64 import org.cacert.gigi.pages.error.AccessDenied;
65 import org.cacert.gigi.pages.error.PageNotFound;
66 import org.cacert.gigi.pages.main.RegisterPage;
67 import org.cacert.gigi.pages.orga.CreateOrgPage;
68 import org.cacert.gigi.pages.orga.ViewOrgPage;
69 import org.cacert.gigi.pages.wot.AssurePage;
70 import org.cacert.gigi.pages.wot.MyPoints;
71 import org.cacert.gigi.pages.wot.RequestTTPPage;
72 import org.cacert.gigi.ping.PingerDaemon;
73 import org.cacert.gigi.util.AuthorizationContext;
74 import org.cacert.gigi.util.DomainAssessment;
75 import org.cacert.gigi.util.ServerConstants;
77 public final class Gigi extends HttpServlet {
79 private class MenuBuilder {
81 private LinkedList<Menu> categories = new LinkedList<Menu>();
83 private HashMap<String, Page> pages = new HashMap<String, Page>();
85 private MenuCollector rootMenu;
87 public MenuBuilder() {}
89 private void putPage(String path, Page p, String category) {
91 if (category == null) {
94 Menu m = getMenu(category);
95 m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
99 private Menu getMenu(String category) {
101 for (Menu menu : categories) {
102 if (menu.getMenuName().equals(category)) {
108 m = new Menu(category);
114 public MenuCollector generateMenu() throws ServletException {
115 putPage("/denied", new AccessDenied(), null);
116 putPage("/error", new PageNotFound(), null);
117 putPage("/login", new LoginPage(), null);
118 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getWwwHostNamePort() + "/login", "Password Login") {
121 public boolean isPermitted(AuthorizationContext ac) {
125 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
128 public boolean isPermitted(AuthorizationContext ac) {
132 putPage("/", new MainPage(), null);
133 putPage("/roots", new RootCertPage(truststore), "SomeCA.org");
134 putPage("/about", new AboutPage(), "SomeCA.org");
136 putPage("/secure", new TestSecure(), null);
137 putPage(Verify.PATH, new Verify(), null);
138 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
139 putPage(RegisterPage.PATH, new RegisterPage(), "SomeCA.org");
140 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
141 putPage(MailOverview.DEFAULT_PATH, new MailOverview(), "Certificates");
142 putPage(DomainOverview.PATH + "*", new DomainOverview(), "Certificates");
144 putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
145 putPage(MyPoints.PATH, new MyPoints(), "Web of Trust");
146 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
148 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
149 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
150 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
152 putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "Support Console");
153 putPage(FindUserPage.PATH, new FindUserPage(), "Support Console");
154 putPage(FindDomainPage.PATH, new FindDomainPage(), "Support Console");
156 putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage(), null);
157 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
158 putPage(LogoutPage.PATH, new LogoutPage(), "My Account");
159 putPage(History.PATH, new History(false), "My Account");
160 putPage(FindAgentAccess.PATH, new OneFormPage("Access to Find Agent", FindAgentAccess.class) {
163 public String getSuccessPath(Form f) {
164 return FindAgentAccess.PATH;
167 putPage(History.SUPPORT_PATH, new History(true), null);
168 putPage(UserTrainings.PATH, new UserTrainings(false), "My Account");
169 putPage(MyDetails.PATH, new MyDetails(), "My Account");
170 putPage(UserTrainings.SUPPORT_PATH, new UserTrainings(true), null);
172 putPage(PasswordResetPage.PATH, new PasswordResetPage(), null);
176 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
177 Page p = (Page) manager.getMethod("getInstance").invoke(null);
178 String pa = (String) manager.getField("PATH").get(null);
179 putPage(pa + "/*", p, "Gigi test server");
180 } catch (ReflectiveOperationException e) {
186 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
187 } catch (UnsupportedEncodingException e) {
188 throw new ServletException(e);
190 baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
191 rootMenu = new MenuCollector();
193 Menu languages = new Menu("Language");
194 for (Locale l : Language.getSupportedLocales()) {
195 languages.addItem(new SimpleMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
197 categories.add(languages);
198 for (Menu menu : categories) {
203 // rootMenu.prepare();
207 public Map<String, Page> getPages() {
208 return Collections.unmodifiableMap(pages);
212 public static final String LOGGEDIN = "loggedin";
214 public static final String CERT_SERIAL = "org.cacert.gigi.serial";
216 public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
218 public static final String AUTH_CONTEXT = "auth";
220 public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
222 private static final long serialVersionUID = -6386785421902852904L;
224 private static Gigi instance;
226 private Template baseTemplate;
228 private PingerDaemon pinger;
230 private KeyStore truststore;
232 private boolean testing;
234 private MenuCollector rootMenu;
236 private Map<String, Page> pages;
238 private boolean firstInstanceInited = false;
240 public Gigi(Properties conf, KeyStore truststore) {
241 synchronized (Gigi.class) {
242 if (instance != null) {
243 throw new IllegalStateException("Multiple Gigi instances!");
245 testing = conf.getProperty("testing") != null;
247 DomainAssessment.init(conf);
248 DatabaseConnection.init(conf);
249 this.truststore = truststore;
250 pinger = new PingerDaemon(truststore);
256 public synchronized void init() throws ServletException {
257 if (firstInstanceInited) {
261 // ensure those static initializers are finished
262 try (Link l = DatabaseConnection.newLink(false)) {
263 CACertificate.getById(1);
264 CertificateProfile.getById(1);
265 CATSType.ASSURER_CHALLENGE.getDisplayName();
266 } catch (InterruptedException e) {
270 MenuBuilder mb = new MenuBuilder();
271 rootMenu = mb.generateMenu();
272 pages = mb.getPages();
274 firstInstanceInited = true;
278 private Page getPage(String pathInfo) {
279 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
280 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
282 Page page = pages.get(pathInfo);
286 page = pages.get(pathInfo + "/*");
290 int idx = pathInfo.lastIndexOf('/');
291 if (idx == -1 || idx == 0) {
295 page = pages.get(pathInfo.substring(0, idx) + "/*");
299 int lIdx = pathInfo.lastIndexOf('/', idx - 1);
303 String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
304 page = pages.get(lastResort);
309 private static String staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
311 private static String staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
313 private static String getStaticTemplateVar(boolean https) {
315 return staticTemplateVarHttps;
317 return staticTemplateVarHttp;
322 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
323 if ("/error".equals(req.getPathInfo()) || "/denied".equals(req.getPathInfo())) {
324 if (DatabaseConnection.hasInstance()) {
325 serviceWithConnection(req, resp);
329 try (DatabaseConnection.Link l = DatabaseConnection.newLink( !req.getMethod().equals("POST"))) {
330 serviceWithConnection(req, resp);
331 } catch (InterruptedException e) {
336 protected void serviceWithConnection(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
337 boolean isSecure = req.isSecure();
338 addXSSHeaders(resp, isSecure);
339 // Firefox only sends this, if it's a cross domain access; safari sends
341 String originHeader = req.getHeader("Origin");
342 if (originHeader != null //
343 && !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
344 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
345 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
346 resp.setContentType("text/html; charset=utf-8");
347 resp.getWriter().println("<html><head><title>Alert</title></head><body>No cross domain access allowed.<br/><b>If you don't know why you're seeing this you may have been fished! Please change your password immediately!</b></body></html>");
350 HttpSession hs = req.getSession();
351 String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
352 if (clientSerial != null) {
353 X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
354 if (cert == null || cert[0] == null//
355 || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial) //
356 || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
358 resp.sendError(403, "Certificate mismatch.");
363 if (req.getParameter("lang") != null) {
364 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
365 Language lu = Language.getInstance(l);
366 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
368 final Page p = getPage(req.getPathInfo());
371 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
372 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
375 AuthorizationContext currentAuthContext = LoginPage.getAuthorizationContext(req);
376 if ( !p.isPermitted(currentAuthContext)) {
377 if (hs.getAttribute("loggedin") == null) {
378 String request = req.getPathInfo();
379 request = request.split("\\?")[0];
380 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
381 resp.sendRedirect("/login");
387 if (p.beforeTemplate(req, resp)) {
390 HashMap<String, Object> vars = new HashMap<String, Object>();
391 // System.out.println(req.getMethod() + ": " + req.getPathInfo() +
393 Outputable content = new Outputable() {
396 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
398 if (req.getMethod().equals("POST")) {
399 if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
406 } catch (CSRFException err) {
408 resp.sendError(500, "CSRF invalid");
409 } catch (IOException e) {
412 } catch (IOException e) {
418 Language lang = Page.getLanguage(req);
420 vars.put(Menu.AUTH_VALUE, currentAuthContext);
421 vars.put("menu", rootMenu);
422 vars.put("title", lang.getTranslation(p.getTitle()));
423 vars.put("static", getStaticTemplateVar(isSecure));
424 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
425 vars.put("content", content);
426 if (currentAuthContext != null) {
427 // TODO maybe move this information into the AuthContext object
428 vars.put("loginMethod", req.getSession().getAttribute(LOGIN_METHOD));
429 vars.put("authContext", currentAuthContext);
432 resp.setContentType("text/html; charset=utf-8");
433 baseTemplate.output(resp.getWriter(), lang, vars);
435 resp.sendError(404, "Page not found.");
440 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
441 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
442 hsr.addHeader("Access-Control-Max-Age", "60");
444 hsr.addHeader("Content-Security-Policy", httpsCSP);
446 hsr.addHeader("Content-Security-Policy", httpCSP);
448 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
452 private static String httpsCSP = genHttpsCSP();
454 private static String httpCSP = genHttpCSP();
456 private static String genHttpsCSP() {
457 StringBuffer csp = new StringBuffer();
458 csp.append("default-src 'none'");
459 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
460 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
461 csp.append(";media-src 'none'; object-src 'none'");
462 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
463 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
464 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
465 // csp.append(";report-url https://api.cacert.org/security/csp/report");
466 return csp.toString();
469 private static String genHttpCSP() {
470 StringBuffer csp = new StringBuffer();
471 csp.append("default-src 'none'");
472 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
473 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
474 csp.append(";media-src 'none'; object-src 'none'");
475 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
476 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
477 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
478 // csp.append(";report-url http://api.cacert.org/security/csp/report");
479 return csp.toString();
483 * Requests Pinging of domains.
486 * if not null, the {@link DomainPingConfiguration} to test, if
487 * null, just re-check if there is something to do.
489 public static void notifyPinger(DomainPingConfiguration toReping) {
490 if (toReping != null) {
491 instance.pinger.queue(toReping);
493 instance.pinger.interrupt();