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.CSRFException;
35 import org.cacert.gigi.output.template.Outputable;
36 import org.cacert.gigi.output.template.Template;
37 import org.cacert.gigi.pages.AboutPage;
38 import org.cacert.gigi.pages.HandlesMixedRequest;
39 import org.cacert.gigi.pages.LoginPage;
40 import org.cacert.gigi.pages.LogoutPage;
41 import org.cacert.gigi.pages.MainPage;
42 import org.cacert.gigi.pages.Page;
43 import org.cacert.gigi.pages.PasswordResetPage;
44 import org.cacert.gigi.pages.RootCertPage;
45 import org.cacert.gigi.pages.StaticPage;
46 import org.cacert.gigi.pages.TestSecure;
47 import org.cacert.gigi.pages.Verify;
48 import org.cacert.gigi.pages.account.ChangePasswordPage;
49 import org.cacert.gigi.pages.account.History;
50 import org.cacert.gigi.pages.account.MyDetails;
51 import org.cacert.gigi.pages.account.UserTrainings;
52 import org.cacert.gigi.pages.account.certs.CertificateAdd;
53 import org.cacert.gigi.pages.account.certs.Certificates;
54 import org.cacert.gigi.pages.account.domain.DomainOverview;
55 import org.cacert.gigi.pages.account.mail.MailOverview;
56 import org.cacert.gigi.pages.admin.TTPAdminPage;
57 import org.cacert.gigi.pages.admin.support.FindDomainPage;
58 import org.cacert.gigi.pages.admin.support.FindUserPage;
59 import org.cacert.gigi.pages.admin.support.SupportEnterTicketPage;
60 import org.cacert.gigi.pages.admin.support.SupportUserDetailsPage;
61 import org.cacert.gigi.pages.error.AccessDenied;
62 import org.cacert.gigi.pages.error.PageNotFound;
63 import org.cacert.gigi.pages.main.RegisterPage;
64 import org.cacert.gigi.pages.orga.CreateOrgPage;
65 import org.cacert.gigi.pages.orga.ViewOrgPage;
66 import org.cacert.gigi.pages.wot.AssurePage;
67 import org.cacert.gigi.pages.wot.MyListingPage;
68 import org.cacert.gigi.pages.wot.MyPoints;
69 import org.cacert.gigi.pages.wot.RequestTTPPage;
70 import org.cacert.gigi.ping.PingerDaemon;
71 import org.cacert.gigi.util.AuthorizationContext;
72 import org.cacert.gigi.util.DomainAssessment;
73 import org.cacert.gigi.util.ServerConstants;
75 public final class Gigi extends HttpServlet {
77 private class MenuBuilder {
79 private LinkedList<Menu> categories = new LinkedList<Menu>();
81 private HashMap<String, Page> pages = new HashMap<String, Page>();
83 private MenuCollector rootMenu;
85 public MenuBuilder() {}
87 private void putPage(String path, Page p, String category) {
89 if (category == null) {
92 Menu m = getMenu(category);
93 m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
97 private Menu getMenu(String category) {
99 for (Menu menu : categories) {
100 if (menu.getMenuName().equals(category)) {
106 m = new Menu(category);
112 public MenuCollector generateMenu() throws ServletException {
113 putPage("/denied", new AccessDenied(), null);
114 putPage("/error", new PageNotFound(), null);
115 putPage("/login", new LoginPage(), null);
116 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getWwwHostNamePort() + "/login", "Password Login") {
119 public boolean isPermitted(AuthorizationContext ac) {
123 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
126 public boolean isPermitted(AuthorizationContext ac) {
130 putPage("/", new MainPage(), null);
131 putPage("/roots", new RootCertPage(truststore), "SomeCA.org");
132 putPage("/about", new AboutPage(), "SomeCA.org");
134 putPage("/secure", new TestSecure(), null);
135 putPage(Verify.PATH, new Verify(), null);
136 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
137 putPage(RegisterPage.PATH, new RegisterPage(), "SomeCA.org");
138 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
139 putPage(MailOverview.DEFAULT_PATH, new MailOverview(), "Certificates");
140 putPage(DomainOverview.PATH + "*", new DomainOverview(), "Certificates");
142 putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
143 putPage(MyPoints.PATH, new MyPoints(), "Web of Trust");
144 putPage(MyListingPage.PATH, new MyListingPage(), "Web of Trust");
145 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
147 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
148 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
149 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
151 putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "Support Console");
152 putPage(FindUserPage.PATH, new FindUserPage(), "Support Console");
153 putPage(FindDomainPage.PATH, new FindDomainPage(), "Support Console");
155 putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage(), null);
156 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
157 putPage(LogoutPage.PATH, new LogoutPage(), "My Account");
158 putPage(History.PATH, new History(false), "My Account");
159 putPage(History.SUPPORT_PATH, new History(true), null);
160 putPage(UserTrainings.PATH, new UserTrainings(false), "My Account");
161 putPage(MyDetails.PATH, new MyDetails(), "My Account");
162 putPage(UserTrainings.SUPPORT_PATH, new UserTrainings(true), null);
164 putPage(PasswordResetPage.PATH, new PasswordResetPage(), null);
168 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
169 Page p = (Page) manager.getMethod("getInstance").invoke(null);
170 String pa = (String) manager.getField("PATH").get(null);
171 putPage(pa + "/*", p, "Gigi test server");
172 } catch (ReflectiveOperationException e) {
178 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
179 } catch (UnsupportedEncodingException e) {
180 throw new ServletException(e);
182 baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
183 rootMenu = new MenuCollector();
185 Menu languages = new Menu("Language");
186 for (Locale l : Language.getSupportedLocales()) {
187 languages.addItem(new SimpleMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
189 categories.add(languages);
190 for (Menu menu : categories) {
195 // rootMenu.prepare();
199 public Map<String, Page> getPages() {
200 return Collections.unmodifiableMap(pages);
204 public static final String LOGGEDIN = "loggedin";
206 public static final String CERT_SERIAL = "org.cacert.gigi.serial";
208 public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
210 public static final String AUTH_CONTEXT = "auth";
212 public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
214 private static final long serialVersionUID = -6386785421902852904L;
216 private static Gigi instance;
218 private Template baseTemplate;
220 private PingerDaemon pinger;
222 private KeyStore truststore;
224 private boolean testing;
226 private MenuCollector rootMenu;
228 private Map<String, Page> pages;
230 private boolean firstInstanceInited = false;
232 public Gigi(Properties conf, KeyStore truststore) {
233 synchronized (Gigi.class) {
234 if (instance != null) {
235 throw new IllegalStateException("Multiple Gigi instances!");
237 testing = conf.getProperty("testing") != null;
239 DomainAssessment.init(conf);
240 DatabaseConnection.init(conf);
241 this.truststore = truststore;
242 pinger = new PingerDaemon(truststore);
248 public synchronized void init() throws ServletException {
249 if (firstInstanceInited) {
253 // ensure those static initializers are finished
254 try (Link l = DatabaseConnection.newLink(false)) {
255 CACertificate.getById(1);
256 CertificateProfile.getById(1);
257 CATSType.ASSURER_CHALLENGE.getDisplayName();
258 } catch (InterruptedException e) {
262 MenuBuilder mb = new MenuBuilder();
263 rootMenu = mb.generateMenu();
264 pages = mb.getPages();
266 firstInstanceInited = true;
270 private Page getPage(String pathInfo) {
271 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
272 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
274 Page page = pages.get(pathInfo);
278 page = pages.get(pathInfo + "/*");
282 int idx = pathInfo.lastIndexOf('/');
283 if (idx == -1 || idx == 0) {
287 page = pages.get(pathInfo.substring(0, idx) + "/*");
291 int lIdx = pathInfo.lastIndexOf('/', idx - 1);
295 String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
296 page = pages.get(lastResort);
301 private static String staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
303 private static String staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
305 private static String getStaticTemplateVar(boolean https) {
307 return staticTemplateVarHttps;
309 return staticTemplateVarHttp;
314 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
315 if ("/error".equals(req.getPathInfo()) || "/denied".equals(req.getPathInfo())) {
316 if (DatabaseConnection.hasInstance()) {
317 serviceWithConnection(req, resp);
321 try (DatabaseConnection.Link l = DatabaseConnection.newLink( !req.getMethod().equals("POST"))) {
322 serviceWithConnection(req, resp);
323 } catch (InterruptedException e) {
328 protected void serviceWithConnection(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
329 boolean isSecure = req.isSecure();
330 addXSSHeaders(resp, isSecure);
331 // Firefox only sends this, if it's a cross domain access; safari sends
333 String originHeader = req.getHeader("Origin");
334 if (originHeader != null //
335 && !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
336 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
337 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
338 resp.setContentType("text/html; charset=utf-8");
339 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>");
342 HttpSession hs = req.getSession();
343 String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
344 if (clientSerial != null) {
345 X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
346 if (cert == null || cert[0] == null//
347 || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial) //
348 || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
350 resp.sendError(403, "Certificate mismatch.");
355 if (req.getParameter("lang") != null) {
356 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
357 Language lu = Language.getInstance(l);
358 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
360 final Page p = getPage(req.getPathInfo());
363 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
364 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
367 AuthorizationContext currentAuthContext = LoginPage.getAuthorizationContext(req);
368 if ( !p.isPermitted(currentAuthContext)) {
369 if (hs.getAttribute("loggedin") == null) {
370 String request = req.getPathInfo();
371 request = request.split("\\?")[0];
372 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
373 resp.sendRedirect("/login");
379 if (p.beforeTemplate(req, resp)) {
382 HashMap<String, Object> vars = new HashMap<String, Object>();
383 // System.out.println(req.getMethod() + ": " + req.getPathInfo() +
385 Outputable content = new Outputable() {
388 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
390 if (req.getMethod().equals("POST")) {
391 if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
398 } catch (CSRFException err) {
400 resp.sendError(500, "CSRF invalid");
401 } catch (IOException e) {
404 } catch (IOException e) {
410 Language lang = Page.getLanguage(req);
412 vars.put(Menu.AUTH_VALUE, currentAuthContext);
413 vars.put("menu", rootMenu);
414 vars.put("title", lang.getTranslation(p.getTitle()));
415 vars.put("static", getStaticTemplateVar(isSecure));
416 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
417 vars.put("content", content);
418 if (currentAuthContext != null) {
419 // TODO maybe move this information into the AuthContext object
420 vars.put("loginMethod", req.getSession().getAttribute(LOGIN_METHOD));
421 vars.put("authContext", currentAuthContext);
424 resp.setContentType("text/html; charset=utf-8");
425 baseTemplate.output(resp.getWriter(), lang, vars);
427 resp.sendError(404, "Page not found.");
432 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
433 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
434 hsr.addHeader("Access-Control-Max-Age", "60");
436 hsr.addHeader("Content-Security-Policy", httpsCSP);
438 hsr.addHeader("Content-Security-Policy", httpCSP);
440 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
444 private static String httpsCSP = genHttpsCSP();
446 private static String httpCSP = genHttpCSP();
448 private static String genHttpsCSP() {
449 StringBuffer csp = new StringBuffer();
450 csp.append("default-src 'none'");
451 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
452 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
453 csp.append(";media-src 'none'; object-src 'none'");
454 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
455 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
456 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
457 // csp.append(";report-url https://api.cacert.org/security/csp/report");
458 return csp.toString();
461 private static String genHttpCSP() {
462 StringBuffer csp = new StringBuffer();
463 csp.append("default-src 'none'");
464 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
465 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
466 csp.append(";media-src 'none'; object-src 'none'");
467 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
468 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
469 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
470 // csp.append(";report-url http://api.cacert.org/security/csp/report");
471 return csp.toString();
475 * Requests Pinging of domains.
478 * if not null, the {@link DomainPingConfiguration} to test, if
479 * null, just re-check if there is something to do.
481 public static void notifyPinger(DomainPingConfiguration toReping) {
482 if (toReping != null) {
483 instance.pinger.queue(toReping);
485 instance.pinger.interrupt();