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;
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.ServerConstants;
74 public final class Gigi extends HttpServlet {
76 private class MenuBuilder {
78 private LinkedList<Menu> categories = new LinkedList<Menu>();
80 private HashMap<String, Page> pages = new HashMap<String, Page>();
82 private MenuCollector rootMenu;
84 public MenuBuilder() {}
86 private void putPage(String path, Page p, String category) {
88 if (category == null) {
91 Menu m = getMenu(category);
92 m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
96 private Menu getMenu(String category) {
98 for (Menu menu : categories) {
99 if (menu.getMenuName().equals(category)) {
105 m = new Menu(category);
111 public MenuCollector generateMenu() throws ServletException {
112 putPage("/denied", new AccessDenied(), null);
113 putPage("/error", new PageNotFound(), null);
114 putPage("/login", new LoginPage(), null);
115 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getWwwHostNamePort() + "/login", "Password Login") {
118 public boolean isPermitted(AuthorizationContext ac) {
122 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
125 public boolean isPermitted(AuthorizationContext ac) {
129 putPage("/", new MainPage(), null);
130 putPage("/roots", new RootCertPage(truststore), "SomeCA.org");
131 putPage("/about", new AboutPage(), "SomeCA.org");
133 putPage("/secure", new TestSecure(), null);
134 putPage(Verify.PATH, new Verify(), null);
135 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
136 putPage(RegisterPage.PATH, new RegisterPage(), "SomeCA.org");
137 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
138 putPage(MailOverview.DEFAULT_PATH, new MailOverview(), "Certificates");
139 putPage(DomainOverview.PATH + "*", new DomainOverview(), "Certificates");
141 putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
142 putPage(MyPoints.PATH, new MyPoints(), "Web of Trust");
143 putPage(MyListingPage.PATH, new MyListingPage(), "Web of Trust");
144 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
146 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
147 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
148 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
150 putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "Support Console");
151 putPage(FindUserPage.PATH, new FindUserPage(), "Support Console");
152 putPage(FindDomainPage.PATH, new FindDomainPage(), "Support Console");
154 putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage(), null);
155 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
156 putPage(LogoutPage.PATH, new LogoutPage(), "My Account");
157 putPage(History.PATH, new History(false), "My Account");
158 putPage(History.SUPPORT_PATH, new History(true), null);
159 putPage(UserTrainings.PATH, new UserTrainings(false), "My Account");
160 putPage(MyDetails.PATH, new MyDetails(), "My Account");
161 putPage(UserTrainings.SUPPORT_PATH, new UserTrainings(true), null);
163 putPage(PasswordResetPage.PATH, new PasswordResetPage(), null);
167 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
168 Page p = (Page) manager.getMethod("getInstance").invoke(null);
169 String pa = (String) manager.getField("PATH").get(null);
170 putPage(pa + "/*", p, "Gigi test server");
171 } catch (ReflectiveOperationException e) {
177 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
178 } catch (UnsupportedEncodingException e) {
179 throw new ServletException(e);
181 baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
182 rootMenu = new MenuCollector();
184 Menu languages = new Menu("Language");
185 for (Locale l : Language.getSupportedLocales()) {
186 languages.addItem(new SimpleMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
188 categories.add(languages);
189 for (Menu menu : categories) {
194 // rootMenu.prepare();
198 public Map<String, Page> getPages() {
199 return Collections.unmodifiableMap(pages);
203 public static final String LOGGEDIN = "loggedin";
205 public static final String CERT_SERIAL = "org.cacert.gigi.serial";
207 public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
209 public static final String AUTH_CONTEXT = "auth";
211 public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
213 private static final long serialVersionUID = -6386785421902852904L;
215 private static Gigi instance;
217 private Template baseTemplate;
219 private PingerDaemon pinger;
221 private KeyStore truststore;
223 private boolean testing;
225 private MenuCollector rootMenu;
227 private Map<String, Page> pages;
229 private boolean firstInstanceInited = false;
231 public Gigi(Properties conf, KeyStore truststore) {
232 synchronized (Gigi.class) {
233 if (instance != null) {
234 throw new IllegalStateException("Multiple Gigi instances!");
236 testing = conf.getProperty("testing") != null;
238 DatabaseConnection.init(conf);
239 this.truststore = truststore;
240 pinger = new PingerDaemon(truststore);
246 public synchronized void init() throws ServletException {
247 if (firstInstanceInited) {
251 // ensure those static initializers are finished
252 try (Link l = DatabaseConnection.newLink(false)) {
253 CACertificate.getById(1);
254 CertificateProfile.getById(1);
255 CATS.getID(CATS.ASSURER_CHALLENGE_NAME);
256 } catch (InterruptedException e) {
260 MenuBuilder mb = new MenuBuilder();
261 rootMenu = mb.generateMenu();
262 pages = mb.getPages();
264 firstInstanceInited = true;
268 private Page getPage(String pathInfo) {
269 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
270 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
272 Page page = pages.get(pathInfo);
276 page = pages.get(pathInfo + "/*");
280 int idx = pathInfo.lastIndexOf('/');
281 if (idx == -1 || idx == 0) {
285 page = pages.get(pathInfo.substring(0, idx) + "/*");
289 int lIdx = pathInfo.lastIndexOf('/', idx - 1);
293 String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
294 page = pages.get(lastResort);
299 private static String staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
301 private static String staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
303 private static String getStaticTemplateVar(boolean https) {
305 return staticTemplateVarHttps;
307 return staticTemplateVarHttp;
312 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
313 if ("/error".equals(req.getPathInfo()) || "/denied".equals(req.getPathInfo())) {
314 if (DatabaseConnection.hasInstance()) {
315 serviceWithConnection(req, resp);
319 try (DatabaseConnection.Link l = DatabaseConnection.newLink( !req.getMethod().equals("POST"))) {
320 serviceWithConnection(req, resp);
321 } catch (InterruptedException e) {
326 protected void serviceWithConnection(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
327 boolean isSecure = req.isSecure();
328 addXSSHeaders(resp, isSecure);
329 // Firefox only sends this, if it's a cross domain access; safari sends
331 String originHeader = req.getHeader("Origin");
332 if (originHeader != null //
333 && !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
334 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
335 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
336 resp.setContentType("text/html; charset=utf-8");
337 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>");
340 HttpSession hs = req.getSession();
341 String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
342 if (clientSerial != null) {
343 X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
344 if (cert == null || cert[0] == null//
345 || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial) //
346 || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
348 resp.sendError(403, "Certificate mismatch.");
353 if (req.getParameter("lang") != null) {
354 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
355 Language lu = Language.getInstance(l);
356 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
358 final Page p = getPage(req.getPathInfo());
361 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
362 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
365 AuthorizationContext currentAuthContext = LoginPage.getAuthorizationContext(req);
366 if ( !p.isPermitted(currentAuthContext)) {
367 if (hs.getAttribute("loggedin") == null) {
368 String request = req.getPathInfo();
369 request = request.split("\\?")[0];
370 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
371 resp.sendRedirect("/login");
377 if (p.beforeTemplate(req, resp)) {
380 HashMap<String, Object> vars = new HashMap<String, Object>();
381 // System.out.println(req.getMethod() + ": " + req.getPathInfo() +
383 Outputable content = new Outputable() {
386 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
388 if (req.getMethod().equals("POST")) {
389 if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
396 } catch (CSRFException err) {
398 resp.sendError(500, "CSRF invalid");
399 } catch (IOException e) {
402 } catch (IOException e) {
408 Language lang = Page.getLanguage(req);
410 vars.put(Menu.AUTH_VALUE, currentAuthContext);
411 vars.put("menu", rootMenu);
412 vars.put("title", lang.getTranslation(p.getTitle()));
413 vars.put("static", getStaticTemplateVar(isSecure));
414 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
415 vars.put("content", content);
416 if (currentAuthContext != null) {
417 // TODO maybe move this information into the AuthContext object
418 vars.put("loginMethod", req.getSession().getAttribute(LOGIN_METHOD));
419 vars.put("authContext", currentAuthContext);
422 resp.setContentType("text/html; charset=utf-8");
423 baseTemplate.output(resp.getWriter(), lang, vars);
425 resp.sendError(404, "Page not found.");
430 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
431 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
432 hsr.addHeader("Access-Control-Max-Age", "60");
434 hsr.addHeader("Content-Security-Policy", httpsCSP);
436 hsr.addHeader("Content-Security-Policy", httpCSP);
438 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
442 private static String httpsCSP = genHttpsCSP();
444 private static String httpCSP = genHttpCSP();
446 private static String genHttpsCSP() {
447 StringBuffer csp = new StringBuffer();
448 csp.append("default-src 'none'");
449 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
450 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
451 csp.append(";media-src 'none'; object-src 'none'");
452 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
453 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
454 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
455 // csp.append(";report-url https://api.cacert.org/security/csp/report");
456 return csp.toString();
459 private static String genHttpCSP() {
460 StringBuffer csp = new StringBuffer();
461 csp.append("default-src 'none'");
462 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
463 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
464 csp.append(";media-src 'none'; object-src 'none'");
465 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
466 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
467 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
468 // csp.append(";report-url http://api.cacert.org/security/csp/report");
469 return csp.toString();
473 * Requests Pinging of domains.
476 * if not null, the {@link DomainPingConfiguration} to test, if
477 * null, just re-check if there is something to do.
479 public static void notifyPinger(DomainPingConfiguration toReping) {
480 if (toReping != null) {
481 instance.pinger.queue(toReping);
483 instance.pinger.interrupt();