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.HandlesMixedRequest;
37 import org.cacert.gigi.pages.LoginPage;
38 import org.cacert.gigi.pages.LogoutPage;
39 import org.cacert.gigi.pages.MainPage;
40 import org.cacert.gigi.pages.Page;
41 import org.cacert.gigi.pages.PasswordResetPage;
42 import org.cacert.gigi.pages.RootCertPage;
43 import org.cacert.gigi.pages.StaticPage;
44 import org.cacert.gigi.pages.TestSecure;
45 import org.cacert.gigi.pages.Verify;
46 import org.cacert.gigi.pages.account.ChangePasswordPage;
47 import org.cacert.gigi.pages.account.History;
48 import org.cacert.gigi.pages.account.MyDetails;
49 import org.cacert.gigi.pages.account.UserTrainings;
50 import org.cacert.gigi.pages.account.certs.CertificateAdd;
51 import org.cacert.gigi.pages.account.certs.Certificates;
52 import org.cacert.gigi.pages.account.domain.DomainOverview;
53 import org.cacert.gigi.pages.account.mail.MailOverview;
54 import org.cacert.gigi.pages.admin.TTPAdminPage;
55 import org.cacert.gigi.pages.admin.support.FindDomainPage;
56 import org.cacert.gigi.pages.admin.support.FindUserPage;
57 import org.cacert.gigi.pages.admin.support.SupportEnterTicketPage;
58 import org.cacert.gigi.pages.admin.support.SupportUserDetailsPage;
59 import org.cacert.gigi.pages.error.AccessDenied;
60 import org.cacert.gigi.pages.error.PageNotFound;
61 import org.cacert.gigi.pages.main.RegisterPage;
62 import org.cacert.gigi.pages.orga.CreateOrgPage;
63 import org.cacert.gigi.pages.orga.ViewOrgPage;
64 import org.cacert.gigi.pages.wot.AssurePage;
65 import org.cacert.gigi.pages.wot.MyListingPage;
66 import org.cacert.gigi.pages.wot.MyPoints;
67 import org.cacert.gigi.pages.wot.RequestTTPPage;
68 import org.cacert.gigi.ping.PingerDaemon;
69 import org.cacert.gigi.util.AuthorizationContext;
70 import org.cacert.gigi.util.ServerConstants;
72 public final class Gigi extends HttpServlet {
74 private class MenuBuilder {
76 private LinkedList<Menu> categories = new LinkedList<Menu>();
78 private HashMap<String, Page> pages = new HashMap<String, Page>();
80 private MenuCollector rootMenu;
82 public MenuBuilder() {}
84 private void putPage(String path, Page p, String category) {
86 if (category == null) {
89 Menu m = getMenu(category);
90 m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
94 private Menu getMenu(String category) {
96 for (Menu menu : categories) {
97 if (menu.getMenuName().equals(category)) {
103 m = new Menu(category);
109 public MenuCollector generateMenu() throws ServletException {
110 putPage("/denied", new AccessDenied(), null);
111 putPage("/error", new PageNotFound(), null);
112 putPage("/login", new LoginPage(), null);
113 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getWwwHostNamePort() + "/login", "Password Login") {
116 public boolean isPermitted(AuthorizationContext ac) {
120 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
123 public boolean isPermitted(AuthorizationContext ac) {
127 putPage("/", new MainPage(), null);
128 putPage("/roots", new RootCertPage(truststore), "SomeCA.org");
130 putPage("/secure", new TestSecure(), null);
131 putPage(Verify.PATH, new Verify(), null);
132 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
133 putPage(RegisterPage.PATH, new RegisterPage(), "SomeCA.org");
134 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
135 putPage(MailOverview.DEFAULT_PATH, new MailOverview(), "Certificates");
136 putPage(DomainOverview.PATH + "*", new DomainOverview(), "Certificates");
138 putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
139 putPage(MyPoints.PATH, new MyPoints(), "Web of Trust");
140 putPage(MyListingPage.PATH, new MyListingPage(), "Web of Trust");
141 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
143 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
144 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
145 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
147 putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "Support Console");
148 putPage(FindUserPage.PATH, new FindUserPage(), "Support Console");
149 putPage(FindDomainPage.PATH, new FindDomainPage(), "Support Console");
151 putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage(), null);
152 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
153 putPage(LogoutPage.PATH, new LogoutPage(), "My Account");
154 putPage(History.PATH, new History(false), "My Account");
155 putPage(History.SUPPORT_PATH, new History(true), null);
156 putPage(UserTrainings.PATH, new UserTrainings(false), "My Account");
157 putPage(MyDetails.PATH, new MyDetails(), "My Account");
158 putPage(UserTrainings.SUPPORT_PATH, new UserTrainings(true), null);
160 putPage(PasswordResetPage.PATH, new PasswordResetPage(), null);
164 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
165 Page p = (Page) manager.getMethod("getInstance").invoke(null);
166 String pa = (String) manager.getField("PATH").get(null);
167 putPage(pa + "/*", p, "Gigi test server");
168 } catch (ReflectiveOperationException e) {
174 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
175 } catch (UnsupportedEncodingException e) {
176 throw new ServletException(e);
178 baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
179 rootMenu = new MenuCollector();
181 Menu languages = new Menu("Language");
182 for (Locale l : Language.getSupportedLocales()) {
183 languages.addItem(new SimpleMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
185 categories.add(languages);
186 for (Menu menu : categories) {
191 // rootMenu.prepare();
195 public Map<String, Page> getPages() {
196 return Collections.unmodifiableMap(pages);
200 public static final String LOGGEDIN = "loggedin";
202 public static final String CERT_SERIAL = "org.cacert.gigi.serial";
204 public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
206 public static final String AUTH_CONTEXT = "auth";
208 public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
210 private static final long serialVersionUID = -6386785421902852904L;
212 private static Gigi instance;
214 private Template baseTemplate;
216 private PingerDaemon pinger;
218 private KeyStore truststore;
220 private boolean testing;
222 private MenuCollector rootMenu;
224 private Map<String, Page> pages;
226 private boolean firstInstanceInited = false;
228 public Gigi(Properties conf, KeyStore truststore) {
229 synchronized (Gigi.class) {
230 if (instance != null) {
231 throw new IllegalStateException("Multiple Gigi instances!");
233 testing = conf.getProperty("testing") != null;
235 DatabaseConnection.init(conf);
236 this.truststore = truststore;
237 pinger = new PingerDaemon(truststore);
243 public synchronized void init() throws ServletException {
244 if (firstInstanceInited) {
248 // ensure those static initializers are finished
249 try (Link l = DatabaseConnection.newLink(false)) {
250 CACertificate.getById(1);
251 CertificateProfile.getById(1);
252 } catch (InterruptedException e) {
256 MenuBuilder mb = new MenuBuilder();
257 rootMenu = mb.generateMenu();
258 pages = mb.getPages();
260 firstInstanceInited = true;
264 private Page getPage(String pathInfo) {
265 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
266 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
268 Page page = pages.get(pathInfo);
272 page = pages.get(pathInfo + "/*");
276 int idx = pathInfo.lastIndexOf('/');
277 if (idx == -1 || idx == 0) {
281 page = pages.get(pathInfo.substring(0, idx) + "/*");
285 int lIdx = pathInfo.lastIndexOf('/', idx - 1);
289 String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
290 page = pages.get(lastResort);
295 private static String staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
297 private static String staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
299 private static String getStaticTemplateVar(boolean https) {
301 return staticTemplateVarHttps;
303 return staticTemplateVarHttp;
308 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
309 if ("/error".equals(req.getPathInfo()) || "/denied".equals(req.getPathInfo())) {
310 if (DatabaseConnection.hasInstance()) {
311 serviceWithConnection(req, resp);
315 try (DatabaseConnection.Link l = DatabaseConnection.newLink( !req.getMethod().equals("POST"))) {
316 serviceWithConnection(req, resp);
317 } catch (InterruptedException e) {
322 protected void serviceWithConnection(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
323 boolean isSecure = req.isSecure();
324 addXSSHeaders(resp, isSecure);
325 // Firefox only sends this, if it's a cross domain access; safari sends
327 String originHeader = req.getHeader("Origin");
328 if (originHeader != null //
330 !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
331 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
332 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
333 resp.setContentType("text/html; charset=utf-8");
334 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>");
337 HttpSession hs = req.getSession();
338 String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
339 if (clientSerial != null) {
340 X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
341 if (cert == null || cert[0] == null//
342 || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial) //
343 || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
345 resp.sendError(403, "Certificate mismatch.");
350 if (req.getParameter("lang") != null) {
351 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
352 Language lu = Language.getInstance(l);
353 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
355 final Page p = getPage(req.getPathInfo());
358 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
359 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
362 AuthorizationContext currentAuthContext = LoginPage.getAuthorizationContext(req);
363 if ( !p.isPermitted(currentAuthContext)) {
364 if (hs.getAttribute("loggedin") == null) {
365 String request = req.getPathInfo();
366 request = request.split("\\?")[0];
367 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
368 resp.sendRedirect("/login");
374 if (p.beforeTemplate(req, resp)) {
377 HashMap<String, Object> vars = new HashMap<String, Object>();
378 // System.out.println(req.getMethod() + ": " + req.getPathInfo() +
380 Outputable content = new Outputable() {
383 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
385 if (req.getMethod().equals("POST")) {
386 if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
393 } catch (CSRFException err) {
395 resp.sendError(500, "CSRF invalid");
396 } catch (IOException e) {
399 } catch (IOException e) {
405 Language lang = Page.getLanguage(req);
407 vars.put(Menu.AUTH_VALUE, currentAuthContext);
408 vars.put("menu", rootMenu);
409 vars.put("title", lang.getTranslation(p.getTitle()));
410 vars.put("static", getStaticTemplateVar(isSecure));
411 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
412 vars.put("content", content);
413 if (currentAuthContext != null) {
414 // TODO maybe move this information into the AuthContext object
415 vars.put("loginMethod", req.getSession().getAttribute(LOGIN_METHOD));
416 vars.put("authContext", currentAuthContext);
419 resp.setContentType("text/html; charset=utf-8");
420 baseTemplate.output(resp.getWriter(), lang, vars);
422 resp.sendError(404, "Page not found.");
427 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
428 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
429 hsr.addHeader("Access-Control-Max-Age", "60");
431 hsr.addHeader("Content-Security-Policy", httpsCSP);
433 hsr.addHeader("Content-Security-Policy", httpCSP);
435 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
439 private static String httpsCSP = genHttpsCSP();
441 private static String httpCSP = genHttpCSP();
443 private static String genHttpsCSP() {
444 StringBuffer csp = new StringBuffer();
445 csp.append("default-src 'none'");
446 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
447 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
448 csp.append(";media-src 'none'; object-src 'none'");
449 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
450 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
451 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
452 // csp.append(";report-url https://api.cacert.org/security/csp/report");
453 return csp.toString();
456 private static String genHttpCSP() {
457 StringBuffer csp = new StringBuffer();
458 csp.append("default-src 'none'");
459 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
460 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
461 csp.append(";media-src 'none'; object-src 'none'");
462 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
463 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
464 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
465 // csp.append(";report-url http://api.cacert.org/security/csp/report");
466 return csp.toString();
470 * Requests Pinging of domains.
473 * if not null, the {@link DomainPingConfiguration} to test, if
474 * null, just re-check if there is something to do.
476 public static void notifyPinger(DomainPingConfiguration toReping) {
477 if (toReping != null) {
478 instance.pinger.queue(toReping);
480 instance.pinger.interrupt();