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.SimpleUntranslatedMenuItem;
35 import org.cacert.gigi.output.template.Form;
36 import org.cacert.gigi.output.template.Form.CSRFException;
37 import org.cacert.gigi.output.template.Outputable;
38 import org.cacert.gigi.output.template.Template;
39 import org.cacert.gigi.pages.AboutPage;
40 import org.cacert.gigi.pages.HandlesMixedRequest;
41 import org.cacert.gigi.pages.LoginPage;
42 import org.cacert.gigi.pages.LogoutPage;
43 import org.cacert.gigi.pages.MainPage;
44 import org.cacert.gigi.pages.OneFormPage;
45 import org.cacert.gigi.pages.Page;
46 import org.cacert.gigi.pages.PasswordResetPage;
47 import org.cacert.gigi.pages.RootCertPage;
48 import org.cacert.gigi.pages.StaticPage;
49 import org.cacert.gigi.pages.TestSecure;
50 import org.cacert.gigi.pages.Verify;
51 import org.cacert.gigi.pages.account.ChangePasswordPage;
52 import org.cacert.gigi.pages.account.FindAgentAccess;
53 import org.cacert.gigi.pages.account.History;
54 import org.cacert.gigi.pages.account.MyDetails;
55 import org.cacert.gigi.pages.account.UserTrainings;
56 import org.cacert.gigi.pages.account.certs.CertificateAdd;
57 import org.cacert.gigi.pages.account.certs.Certificates;
58 import org.cacert.gigi.pages.account.domain.DomainOverview;
59 import org.cacert.gigi.pages.account.mail.MailOverview;
60 import org.cacert.gigi.pages.admin.TTPAdminPage;
61 import org.cacert.gigi.pages.admin.support.FindDomainPage;
62 import org.cacert.gigi.pages.admin.support.FindUserPage;
63 import org.cacert.gigi.pages.admin.support.SupportEnterTicketPage;
64 import org.cacert.gigi.pages.admin.support.SupportUserDetailsPage;
65 import org.cacert.gigi.pages.error.AccessDenied;
66 import org.cacert.gigi.pages.error.PageNotFound;
67 import org.cacert.gigi.pages.main.RegisterPage;
68 import org.cacert.gigi.pages.orga.CreateOrgPage;
69 import org.cacert.gigi.pages.orga.ViewOrgPage;
70 import org.cacert.gigi.pages.wot.AssurePage;
71 import org.cacert.gigi.pages.wot.MyPoints;
72 import org.cacert.gigi.pages.wot.RequestTTPPage;
73 import org.cacert.gigi.ping.PingerDaemon;
74 import org.cacert.gigi.util.AuthorizationContext;
75 import org.cacert.gigi.util.DomainAssessment;
76 import org.cacert.gigi.util.ServerConstants;
78 public final class Gigi extends HttpServlet {
80 private class MenuBuilder {
82 private LinkedList<Menu> categories = new LinkedList<Menu>();
84 private HashMap<String, Page> pages = new HashMap<String, Page>();
86 private MenuCollector rootMenu;
88 public MenuBuilder() {}
90 private void putPage(String path, Page p, String category) {
92 if (category == null) {
95 Menu m = getMenu(category);
96 m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
100 private Menu getMenu(String category) {
102 for (Menu menu : categories) {
103 if (menu.getMenuName().equals(category)) {
109 m = new Menu(category);
115 public MenuCollector generateMenu() throws ServletException {
116 putPage("/denied", new AccessDenied(), null);
117 putPage("/error", new PageNotFound(), null);
118 putPage("/login", new LoginPage(), null);
119 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getWwwHostNamePort() + "/login", "Password Login") {
122 public boolean isPermitted(AuthorizationContext ac) {
126 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
129 public boolean isPermitted(AuthorizationContext ac) {
133 putPage("/", new MainPage(), null);
134 putPage("/roots", new RootCertPage(truststore), "SomeCA.org");
135 putPage("/about", new AboutPage(), "SomeCA.org");
137 putPage("/secure", new TestSecure(), null);
138 putPage(Verify.PATH, new Verify(), null);
139 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
140 putPage(RegisterPage.PATH, new RegisterPage(), "SomeCA.org");
141 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
142 putPage(MailOverview.DEFAULT_PATH, new MailOverview(), "Certificates");
143 putPage(DomainOverview.PATH + "*", new DomainOverview(), "Certificates");
145 putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
146 putPage(MyPoints.PATH, new MyPoints(), "Web of Trust");
147 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
149 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
150 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
151 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
153 putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "Support Console");
154 putPage(FindUserPage.PATH, new FindUserPage(), "Support Console");
155 putPage(FindDomainPage.PATH, new FindDomainPage(), "Support Console");
157 putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage(), null);
158 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "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);
173 putPage(LogoutPage.PATH, new LogoutPage(), null);
177 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
178 Page p = (Page) manager.getMethod("getInstance").invoke(null);
179 String pa = (String) manager.getField("PATH").get(null);
180 putPage(pa + "/*", p, "Gigi test server");
181 } catch (ReflectiveOperationException e) {
187 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
188 } catch (UnsupportedEncodingException e) {
189 throw new ServletException(e);
191 rootMenu = new MenuCollector();
193 Menu languages = new Menu("Language");
194 addLanguages(languages);
195 categories.add(languages);
196 for (Menu menu : categories) {
201 // rootMenu.prepare();
205 private void addLanguages(Menu languages) {
206 for (Locale l : Language.getSupportedLocales()) {
207 languages.addItem(new SimpleUntranslatedMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
211 public Map<String, Page> getPages() {
212 return Collections.unmodifiableMap(pages);
216 public static final String LOGGEDIN = "loggedin";
218 public static final String CERT_SERIAL = "org.cacert.gigi.serial";
220 public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
222 public static final String AUTH_CONTEXT = "auth";
224 public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
226 private static final long serialVersionUID = -6386785421902852904L;
228 private static Gigi instance;
230 private static final Template baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));;
232 private PingerDaemon pinger;
234 private KeyStore truststore;
236 private boolean testing;
238 private MenuCollector rootMenu;
240 private Map<String, Page> pages;
242 private boolean firstInstanceInited = false;
244 public Gigi(Properties conf, KeyStore truststore) {
245 synchronized (Gigi.class) {
246 if (instance != null) {
247 throw new IllegalStateException("Multiple Gigi instances!");
249 testing = conf.getProperty("testing") != null;
251 DomainAssessment.init(conf);
252 DatabaseConnection.init(conf);
253 this.truststore = truststore;
254 pinger = new PingerDaemon(truststore);
260 public synchronized void init() throws ServletException {
261 if (firstInstanceInited) {
265 // ensure those static initializers are finished
266 try (Link l = DatabaseConnection.newLink(false)) {
267 CACertificate.getById(1);
268 CertificateProfile.getById(1);
269 CATSType.ASSURER_CHALLENGE.getDisplayName();
270 } catch (InterruptedException e) {
274 MenuBuilder mb = new MenuBuilder();
275 rootMenu = mb.generateMenu();
276 pages = mb.getPages();
278 firstInstanceInited = true;
282 private Page getPage(String pathInfo) {
283 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
284 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
286 Page page = pages.get(pathInfo);
290 page = pages.get(pathInfo + "/*");
294 int idx = pathInfo.lastIndexOf('/');
295 if (idx == -1 || idx == 0) {
299 page = pages.get(pathInfo.substring(0, idx) + "/*");
303 int lIdx = pathInfo.lastIndexOf('/', idx - 1);
307 String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
308 page = pages.get(lastResort);
313 private static String staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
315 private static String staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
317 private static String getStaticTemplateVar(boolean https) {
319 return staticTemplateVarHttps;
321 return staticTemplateVarHttp;
326 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
327 if ("/error".equals(req.getPathInfo()) || "/denied".equals(req.getPathInfo())) {
328 if (DatabaseConnection.hasInstance()) {
329 serviceWithConnection(req, resp);
333 try (DatabaseConnection.Link l = DatabaseConnection.newLink( !req.getMethod().equals("POST"))) {
334 serviceWithConnection(req, resp);
335 } catch (InterruptedException e) {
340 protected void serviceWithConnection(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
341 boolean isSecure = req.isSecure();
342 addXSSHeaders(resp, isSecure);
343 // Firefox only sends this, if it's a cross domain access; safari sends
345 String originHeader = req.getHeader("Origin");
346 if (originHeader != null //
347 && !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
348 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
349 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
350 resp.setContentType("text/html; charset=utf-8");
351 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>");
354 HttpSession hs = req.getSession();
355 String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
356 if (clientSerial != null) {
357 X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
358 if (cert == null || cert[0] == null//
359 || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial) //
360 || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
362 resp.sendError(403, "Certificate mismatch.");
367 if (req.getParameter("lang") != null) {
368 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
369 Language lu = Language.getInstance(l);
370 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
372 final Page p = getPage(req.getPathInfo());
375 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
376 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
379 AuthorizationContext currentAuthContext = LoginPage.getAuthorizationContext(req);
380 if ( !p.isPermitted(currentAuthContext)) {
381 if (hs.getAttribute("loggedin") == null) {
382 String request = req.getPathInfo();
383 request = request.split("\\?")[0];
384 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
385 resp.sendRedirect("/login");
391 if (p.beforeTemplate(req, resp)) {
394 HashMap<String, Object> vars = new HashMap<String, Object>();
395 // System.out.println(req.getMethod() + ": " + req.getPathInfo() +
397 Outputable content = new Outputable() {
400 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
402 if (req.getMethod().equals("POST")) {
403 if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
410 } catch (CSRFException err) {
412 resp.sendError(500, "CSRF invalid");
413 } catch (IOException e) {
416 } catch (IOException e) {
422 Language lang = Page.getLanguage(req);
424 vars.put(Menu.AUTH_VALUE, currentAuthContext);
425 vars.put("menu", rootMenu);
426 vars.put("title", lang.getTranslation(p.getTitle()));
427 vars.put("static", getStaticTemplateVar(isSecure));
428 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
429 vars.put("content", content);
430 if (currentAuthContext != null) {
431 // TODO maybe move this information into the AuthContext object
432 vars.put("loginMethod", req.getSession().getAttribute(LOGIN_METHOD));
433 vars.put("authContext", currentAuthContext);
436 resp.setContentType("text/html; charset=utf-8");
437 baseTemplate.output(resp.getWriter(), lang, vars);
439 resp.sendError(404, "Page not found.");
444 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
445 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
446 hsr.addHeader("Access-Control-Max-Age", "60");
448 hsr.addHeader("Content-Security-Policy", httpsCSP);
450 hsr.addHeader("Content-Security-Policy", httpCSP);
452 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
456 private static String httpsCSP = genHttpsCSP();
458 private static String httpCSP = genHttpCSP();
460 private static String genHttpsCSP() {
461 StringBuffer csp = new StringBuffer();
462 csp.append("default-src 'none'");
463 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
464 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
465 csp.append(";media-src 'none'; object-src 'none'");
466 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
467 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
468 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
469 // csp.append(";report-url https://api.cacert.org/security/csp/report");
470 return csp.toString();
473 private static String genHttpCSP() {
474 StringBuffer csp = new StringBuffer();
475 csp.append("default-src 'none'");
476 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
477 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
478 csp.append(";media-src 'none'; object-src 'none'");
479 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
480 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
481 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
482 // csp.append(";report-url http://api.cacert.org/security/csp/report");
483 return csp.toString();
487 * Requests Pinging of domains.
490 * if not null, the {@link DomainPingConfiguration} to test, if
491 * null, just re-check if there is something to do.
493 public static void notifyPinger(DomainPingConfiguration toReping) {
494 if (toReping != null) {
495 instance.pinger.queue(toReping);
497 instance.pinger.interrupt();