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.CertificateProfile;
27 import org.cacert.gigi.dbObjects.DomainPingConfiguration;
28 import org.cacert.gigi.localisation.Language;
29 import org.cacert.gigi.output.Menu;
30 import org.cacert.gigi.output.MenuCollector;
31 import org.cacert.gigi.output.PageMenuItem;
32 import org.cacert.gigi.output.SimpleMenuItem;
33 import org.cacert.gigi.output.template.Form.CSRFException;
34 import org.cacert.gigi.output.template.Outputable;
35 import org.cacert.gigi.output.template.Template;
36 import org.cacert.gigi.pages.AboutPage;
37 import org.cacert.gigi.pages.HandlesMixedRequest;
38 import org.cacert.gigi.pages.LoginPage;
39 import org.cacert.gigi.pages.LogoutPage;
40 import org.cacert.gigi.pages.MainPage;
41 import org.cacert.gigi.pages.Page;
42 import org.cacert.gigi.pages.PasswordResetPage;
43 import org.cacert.gigi.pages.RootCertPage;
44 import org.cacert.gigi.pages.StaticPage;
45 import org.cacert.gigi.pages.TestSecure;
46 import org.cacert.gigi.pages.Verify;
47 import org.cacert.gigi.pages.account.ChangePasswordPage;
48 import org.cacert.gigi.pages.account.History;
49 import org.cacert.gigi.pages.account.MyDetails;
50 import org.cacert.gigi.pages.account.UserTrainings;
51 import org.cacert.gigi.pages.account.certs.CertificateAdd;
52 import org.cacert.gigi.pages.account.certs.Certificates;
53 import org.cacert.gigi.pages.account.domain.DomainOverview;
54 import org.cacert.gigi.pages.account.mail.MailOverview;
55 import org.cacert.gigi.pages.admin.TTPAdminPage;
56 import org.cacert.gigi.pages.admin.support.FindDomainPage;
57 import org.cacert.gigi.pages.admin.support.FindUserPage;
58 import org.cacert.gigi.pages.admin.support.SupportEnterTicketPage;
59 import org.cacert.gigi.pages.admin.support.SupportUserDetailsPage;
60 import org.cacert.gigi.pages.error.AccessDenied;
61 import org.cacert.gigi.pages.error.PageNotFound;
62 import org.cacert.gigi.pages.main.RegisterPage;
63 import org.cacert.gigi.pages.orga.CreateOrgPage;
64 import org.cacert.gigi.pages.orga.ViewOrgPage;
65 import org.cacert.gigi.pages.wot.AssurePage;
66 import org.cacert.gigi.pages.wot.MyListingPage;
67 import org.cacert.gigi.pages.wot.MyPoints;
68 import org.cacert.gigi.pages.wot.RequestTTPPage;
69 import org.cacert.gigi.ping.PingerDaemon;
70 import org.cacert.gigi.util.AuthorizationContext;
71 import org.cacert.gigi.util.ServerConstants;
73 public final class Gigi extends HttpServlet {
75 private class MenuBuilder {
77 private LinkedList<Menu> categories = new LinkedList<Menu>();
79 private HashMap<String, Page> pages = new HashMap<String, Page>();
81 private MenuCollector rootMenu;
83 public MenuBuilder() {}
85 private void putPage(String path, Page p, String category) {
87 if (category == null) {
90 Menu m = getMenu(category);
91 m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
95 private Menu getMenu(String category) {
97 for (Menu menu : categories) {
98 if (menu.getMenuName().equals(category)) {
104 m = new Menu(category);
110 public MenuCollector generateMenu() throws ServletException {
111 putPage("/denied", new AccessDenied(), null);
112 putPage("/error", new PageNotFound(), null);
113 putPage("/login", new LoginPage(), null);
114 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getWwwHostNamePort() + "/login", "Password Login") {
117 public boolean isPermitted(AuthorizationContext ac) {
121 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
124 public boolean isPermitted(AuthorizationContext ac) {
128 putPage("/", new MainPage(), null);
129 putPage("/roots", new RootCertPage(truststore), "SomeCA.org");
130 putPage("/about", new AboutPage(), "SomeCA.org");
132 putPage("/secure", new TestSecure(), null);
133 putPage(Verify.PATH, new Verify(), null);
134 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
135 putPage(RegisterPage.PATH, new RegisterPage(), "SomeCA.org");
136 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
137 putPage(MailOverview.DEFAULT_PATH, new MailOverview(), "Certificates");
138 putPage(DomainOverview.PATH + "*", new DomainOverview(), "Certificates");
140 putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
141 putPage(MyPoints.PATH, new MyPoints(), "Web of Trust");
142 putPage(MyListingPage.PATH, new MyListingPage(), "Web of Trust");
143 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
145 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
146 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
147 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
149 putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "Support Console");
150 putPage(FindUserPage.PATH, new FindUserPage(), "Support Console");
151 putPage(FindDomainPage.PATH, new FindDomainPage(), "Support Console");
153 putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage(), null);
154 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
155 putPage(LogoutPage.PATH, new LogoutPage(), "My Account");
156 putPage(History.PATH, new History(false), "My Account");
157 putPage(History.SUPPORT_PATH, new History(true), null);
158 putPage(UserTrainings.PATH, new UserTrainings(false), "My Account");
159 putPage(MyDetails.PATH, new MyDetails(), "My Account");
160 putPage(UserTrainings.SUPPORT_PATH, new UserTrainings(true), null);
162 putPage(PasswordResetPage.PATH, new PasswordResetPage(), null);
166 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
167 Page p = (Page) manager.getMethod("getInstance").invoke(null);
168 String pa = (String) manager.getField("PATH").get(null);
169 putPage(pa + "/*", p, "Gigi test server");
170 } catch (ReflectiveOperationException e) {
176 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
177 } catch (UnsupportedEncodingException e) {
178 throw new ServletException(e);
180 baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
181 rootMenu = new MenuCollector();
183 Menu languages = new Menu("Language");
184 for (Locale l : Language.getSupportedLocales()) {
185 languages.addItem(new SimpleMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
187 categories.add(languages);
188 for (Menu menu : categories) {
193 // rootMenu.prepare();
197 public Map<String, Page> getPages() {
198 return Collections.unmodifiableMap(pages);
202 public static final String LOGGEDIN = "loggedin";
204 public static final String CERT_SERIAL = "org.cacert.gigi.serial";
206 public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
208 public static final String AUTH_CONTEXT = "auth";
210 public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
212 private static final long serialVersionUID = -6386785421902852904L;
214 private static Gigi instance;
216 private Template baseTemplate;
218 private PingerDaemon pinger;
220 private KeyStore truststore;
222 private boolean testing;
224 private MenuCollector rootMenu;
226 private Map<String, Page> pages;
228 private boolean firstInstanceInited = false;
230 public Gigi(Properties conf, KeyStore truststore) {
231 synchronized (Gigi.class) {
232 if (instance != null) {
233 throw new IllegalStateException("Multiple Gigi instances!");
235 testing = conf.getProperty("testing") != null;
237 DatabaseConnection.init(conf);
238 this.truststore = truststore;
239 pinger = new PingerDaemon(truststore);
245 public synchronized void init() throws ServletException {
246 if (firstInstanceInited) {
250 // ensure those static initializers are finished
251 try (Link l = DatabaseConnection.newLink(false)) {
252 CACertificate.getById(1);
253 CertificateProfile.getById(1);
254 } catch (InterruptedException e) {
258 MenuBuilder mb = new MenuBuilder();
259 rootMenu = mb.generateMenu();
260 pages = mb.getPages();
262 firstInstanceInited = true;
266 private Page getPage(String pathInfo) {
267 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
268 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
270 Page page = pages.get(pathInfo);
274 page = pages.get(pathInfo + "/*");
278 int idx = pathInfo.lastIndexOf('/');
279 if (idx == -1 || idx == 0) {
283 page = pages.get(pathInfo.substring(0, idx) + "/*");
287 int lIdx = pathInfo.lastIndexOf('/', idx - 1);
291 String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
292 page = pages.get(lastResort);
297 private static String staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
299 private static String staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
301 private static String getStaticTemplateVar(boolean https) {
303 return staticTemplateVarHttps;
305 return staticTemplateVarHttp;
310 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
311 if ("/error".equals(req.getPathInfo()) || "/denied".equals(req.getPathInfo())) {
312 if (DatabaseConnection.hasInstance()) {
313 serviceWithConnection(req, resp);
317 try (DatabaseConnection.Link l = DatabaseConnection.newLink( !req.getMethod().equals("POST"))) {
318 serviceWithConnection(req, resp);
319 } catch (InterruptedException e) {
324 protected void serviceWithConnection(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
325 boolean isSecure = req.isSecure();
326 addXSSHeaders(resp, isSecure);
327 // Firefox only sends this, if it's a cross domain access; safari sends
329 String originHeader = req.getHeader("Origin");
330 if (originHeader != null //
332 !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
333 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
334 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
335 resp.setContentType("text/html; charset=utf-8");
336 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>");
339 HttpSession hs = req.getSession();
340 String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
341 if (clientSerial != null) {
342 X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
343 if (cert == null || cert[0] == null//
344 || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial) //
345 || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
347 resp.sendError(403, "Certificate mismatch.");
352 if (req.getParameter("lang") != null) {
353 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
354 Language lu = Language.getInstance(l);
355 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
357 final Page p = getPage(req.getPathInfo());
360 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
361 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
364 AuthorizationContext currentAuthContext = LoginPage.getAuthorizationContext(req);
365 if ( !p.isPermitted(currentAuthContext)) {
366 if (hs.getAttribute("loggedin") == null) {
367 String request = req.getPathInfo();
368 request = request.split("\\?")[0];
369 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
370 resp.sendRedirect("/login");
376 if (p.beforeTemplate(req, resp)) {
379 HashMap<String, Object> vars = new HashMap<String, Object>();
380 // System.out.println(req.getMethod() + ": " + req.getPathInfo() +
382 Outputable content = new Outputable() {
385 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
387 if (req.getMethod().equals("POST")) {
388 if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
395 } catch (CSRFException err) {
397 resp.sendError(500, "CSRF invalid");
398 } catch (IOException e) {
401 } catch (IOException e) {
407 Language lang = Page.getLanguage(req);
409 vars.put(Menu.AUTH_VALUE, currentAuthContext);
410 vars.put("menu", rootMenu);
411 vars.put("title", lang.getTranslation(p.getTitle()));
412 vars.put("static", getStaticTemplateVar(isSecure));
413 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
414 vars.put("content", content);
415 if (currentAuthContext != null) {
416 // TODO maybe move this information into the AuthContext object
417 vars.put("loginMethod", req.getSession().getAttribute(LOGIN_METHOD));
418 vars.put("authContext", currentAuthContext);
421 resp.setContentType("text/html; charset=utf-8");
422 baseTemplate.output(resp.getWriter(), lang, vars);
424 resp.sendError(404, "Page not found.");
429 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
430 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
431 hsr.addHeader("Access-Control-Max-Age", "60");
433 hsr.addHeader("Content-Security-Policy", httpsCSP);
435 hsr.addHeader("Content-Security-Policy", httpCSP);
437 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
441 private static String httpsCSP = genHttpsCSP();
443 private static String httpCSP = genHttpCSP();
445 private static String genHttpsCSP() {
446 StringBuffer csp = new StringBuffer();
447 csp.append("default-src 'none'");
448 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
449 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
450 csp.append(";media-src 'none'; object-src 'none'");
451 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
452 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
453 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
454 // csp.append(";report-url https://api.cacert.org/security/csp/report");
455 return csp.toString();
458 private static String genHttpCSP() {
459 StringBuffer csp = new StringBuffer();
460 csp.append("default-src 'none'");
461 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
462 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
463 csp.append(";media-src 'none'; object-src 'none'");
464 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
465 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
466 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
467 // csp.append(";report-url http://api.cacert.org/security/csp/report");
468 return csp.toString();
472 * Requests Pinging of domains.
475 * if not null, the {@link DomainPingConfiguration} to test, if
476 * null, just re-check if there is something to do.
478 public static void notifyPinger(DomainPingConfiguration toReping) {
479 if (toReping != null) {
480 instance.pinger.queue(toReping);
482 instance.pinger.interrupt();