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;
35 import org.cacert.gigi.output.template.Form.CSRFException;
36 import org.cacert.gigi.output.template.Outputable;
37 import org.cacert.gigi.output.template.Template;
38 import org.cacert.gigi.pages.AboutPage;
39 import org.cacert.gigi.pages.HandlesMixedRequest;
40 import org.cacert.gigi.pages.LoginPage;
41 import org.cacert.gigi.pages.LogoutPage;
42 import org.cacert.gigi.pages.MainPage;
43 import org.cacert.gigi.pages.OneFormPage;
44 import org.cacert.gigi.pages.Page;
45 import org.cacert.gigi.pages.PasswordResetPage;
46 import org.cacert.gigi.pages.RootCertPage;
47 import org.cacert.gigi.pages.StaticPage;
48 import org.cacert.gigi.pages.TestSecure;
49 import org.cacert.gigi.pages.Verify;
50 import org.cacert.gigi.pages.account.ChangePasswordPage;
51 import org.cacert.gigi.pages.account.FindAgentAccess;
52 import org.cacert.gigi.pages.account.History;
53 import org.cacert.gigi.pages.account.MyDetails;
54 import org.cacert.gigi.pages.account.UserTrainings;
55 import org.cacert.gigi.pages.account.certs.CertificateAdd;
56 import org.cacert.gigi.pages.account.certs.Certificates;
57 import org.cacert.gigi.pages.account.domain.DomainOverview;
58 import org.cacert.gigi.pages.account.mail.MailOverview;
59 import org.cacert.gigi.pages.admin.TTPAdminPage;
60 import org.cacert.gigi.pages.admin.support.FindDomainPage;
61 import org.cacert.gigi.pages.admin.support.FindUserPage;
62 import org.cacert.gigi.pages.admin.support.SupportEnterTicketPage;
63 import org.cacert.gigi.pages.admin.support.SupportUserDetailsPage;
64 import org.cacert.gigi.pages.error.AccessDenied;
65 import org.cacert.gigi.pages.error.PageNotFound;
66 import org.cacert.gigi.pages.main.RegisterPage;
67 import org.cacert.gigi.pages.orga.CreateOrgPage;
68 import org.cacert.gigi.pages.orga.ViewOrgPage;
69 import org.cacert.gigi.pages.wot.AssurePage;
70 import org.cacert.gigi.pages.wot.MyPoints;
71 import org.cacert.gigi.pages.wot.RequestTTPPage;
72 import org.cacert.gigi.ping.PingerDaemon;
73 import org.cacert.gigi.util.AuthorizationContext;
74 import org.cacert.gigi.util.DomainAssessment;
75 import org.cacert.gigi.util.ServerConstants;
77 public final class Gigi extends HttpServlet {
79 private class MenuBuilder {
81 private LinkedList<Menu> categories = new LinkedList<Menu>();
83 private HashMap<String, Page> pages = new HashMap<String, Page>();
85 private MenuCollector rootMenu;
87 public MenuBuilder() {}
89 private void putPage(String path, Page p, String category) {
91 if (category == null) {
94 Menu m = getMenu(category);
95 m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
99 private Menu getMenu(String category) {
101 for (Menu menu : categories) {
102 if (menu.getMenuName().equals(category)) {
108 m = new Menu(category);
114 public MenuCollector generateMenu() throws ServletException {
115 putPage("/denied", new AccessDenied(), null);
116 putPage("/error", new PageNotFound(), null);
117 putPage("/login", new LoginPage(), null);
118 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getWwwHostNamePort() + "/login", "Password Login") {
121 public boolean isPermitted(AuthorizationContext ac) {
125 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
128 public boolean isPermitted(AuthorizationContext ac) {
132 putPage("/", new MainPage(), null);
133 putPage("/roots", new RootCertPage(truststore), "SomeCA.org");
134 putPage("/about", new AboutPage(), "SomeCA.org");
136 putPage("/secure", new TestSecure(), null);
137 putPage(Verify.PATH, new Verify(), null);
138 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
139 putPage(RegisterPage.PATH, new RegisterPage(), "SomeCA.org");
140 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
141 putPage(MailOverview.DEFAULT_PATH, new MailOverview(), "Certificates");
142 putPage(DomainOverview.PATH + "*", new DomainOverview(), "Certificates");
144 putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
145 putPage(MyPoints.PATH, new MyPoints(), "Web of Trust");
146 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
148 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
149 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
150 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
152 putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "Support Console");
153 putPage(FindUserPage.PATH, new FindUserPage(), "Support Console");
154 putPage(FindDomainPage.PATH, new FindDomainPage(), "Support Console");
156 putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage(), null);
157 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
158 putPage(History.PATH, new History(false), "My Account");
159 putPage(FindAgentAccess.PATH, new OneFormPage("Access to Find Agent", FindAgentAccess.class) {
162 public String getSuccessPath(Form f) {
163 return FindAgentAccess.PATH;
166 putPage(History.SUPPORT_PATH, new History(true), null);
167 putPage(UserTrainings.PATH, new UserTrainings(false), "My Account");
168 putPage(MyDetails.PATH, new MyDetails(), "My Account");
169 putPage(UserTrainings.SUPPORT_PATH, new UserTrainings(true), null);
171 putPage(PasswordResetPage.PATH, new PasswordResetPage(), null);
172 putPage(LogoutPage.PATH, new LogoutPage(), null);
176 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
177 Page p = (Page) manager.getMethod("getInstance").invoke(null);
178 String pa = (String) manager.getField("PATH").get(null);
179 putPage(pa + "/*", p, "Gigi test server");
180 } catch (ReflectiveOperationException e) {
186 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
187 } catch (UnsupportedEncodingException e) {
188 throw new ServletException(e);
190 rootMenu = new MenuCollector();
192 Menu languages = new Menu("Language");
193 for (Locale l : Language.getSupportedLocales()) {
194 languages.addItem(new SimpleMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
196 categories.add(languages);
197 for (Menu menu : categories) {
202 // rootMenu.prepare();
206 public Map<String, Page> getPages() {
207 return Collections.unmodifiableMap(pages);
211 public static final String LOGGEDIN = "loggedin";
213 public static final String CERT_SERIAL = "org.cacert.gigi.serial";
215 public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
217 public static final String AUTH_CONTEXT = "auth";
219 public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
221 private static final long serialVersionUID = -6386785421902852904L;
223 private static Gigi instance;
225 private static final Template baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));;
227 private PingerDaemon pinger;
229 private KeyStore truststore;
231 private boolean testing;
233 private MenuCollector rootMenu;
235 private Map<String, Page> pages;
237 private boolean firstInstanceInited = false;
239 public Gigi(Properties conf, KeyStore truststore) {
240 synchronized (Gigi.class) {
241 if (instance != null) {
242 throw new IllegalStateException("Multiple Gigi instances!");
244 testing = conf.getProperty("testing") != null;
246 DomainAssessment.init(conf);
247 DatabaseConnection.init(conf);
248 this.truststore = truststore;
249 pinger = new PingerDaemon(truststore);
255 public synchronized void init() throws ServletException {
256 if (firstInstanceInited) {
260 // ensure those static initializers are finished
261 try (Link l = DatabaseConnection.newLink(false)) {
262 CACertificate.getById(1);
263 CertificateProfile.getById(1);
264 CATSType.ASSURER_CHALLENGE.getDisplayName();
265 } catch (InterruptedException e) {
269 MenuBuilder mb = new MenuBuilder();
270 rootMenu = mb.generateMenu();
271 pages = mb.getPages();
273 firstInstanceInited = true;
277 private Page getPage(String pathInfo) {
278 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
279 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
281 Page page = pages.get(pathInfo);
285 page = pages.get(pathInfo + "/*");
289 int idx = pathInfo.lastIndexOf('/');
290 if (idx == -1 || idx == 0) {
294 page = pages.get(pathInfo.substring(0, idx) + "/*");
298 int lIdx = pathInfo.lastIndexOf('/', idx - 1);
302 String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
303 page = pages.get(lastResort);
308 private static String staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
310 private static String staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
312 private static String getStaticTemplateVar(boolean https) {
314 return staticTemplateVarHttps;
316 return staticTemplateVarHttp;
321 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
322 if ("/error".equals(req.getPathInfo()) || "/denied".equals(req.getPathInfo())) {
323 if (DatabaseConnection.hasInstance()) {
324 serviceWithConnection(req, resp);
328 try (DatabaseConnection.Link l = DatabaseConnection.newLink( !req.getMethod().equals("POST"))) {
329 serviceWithConnection(req, resp);
330 } catch (InterruptedException e) {
335 protected void serviceWithConnection(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
336 boolean isSecure = req.isSecure();
337 addXSSHeaders(resp, isSecure);
338 // Firefox only sends this, if it's a cross domain access; safari sends
340 String originHeader = req.getHeader("Origin");
341 if (originHeader != null //
342 && !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
343 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
344 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
345 resp.setContentType("text/html; charset=utf-8");
346 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>");
349 HttpSession hs = req.getSession();
350 String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
351 if (clientSerial != null) {
352 X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
353 if (cert == null || cert[0] == null//
354 || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial) //
355 || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
357 resp.sendError(403, "Certificate mismatch.");
362 if (req.getParameter("lang") != null) {
363 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
364 Language lu = Language.getInstance(l);
365 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
367 final Page p = getPage(req.getPathInfo());
370 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
371 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
374 AuthorizationContext currentAuthContext = LoginPage.getAuthorizationContext(req);
375 if ( !p.isPermitted(currentAuthContext)) {
376 if (hs.getAttribute("loggedin") == null) {
377 String request = req.getPathInfo();
378 request = request.split("\\?")[0];
379 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
380 resp.sendRedirect("/login");
386 if (p.beforeTemplate(req, resp)) {
389 HashMap<String, Object> vars = new HashMap<String, Object>();
390 // System.out.println(req.getMethod() + ": " + req.getPathInfo() +
392 Outputable content = new Outputable() {
395 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
397 if (req.getMethod().equals("POST")) {
398 if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
405 } catch (CSRFException err) {
407 resp.sendError(500, "CSRF invalid");
408 } catch (IOException e) {
411 } catch (IOException e) {
417 Language lang = Page.getLanguage(req);
419 vars.put(Menu.AUTH_VALUE, currentAuthContext);
420 vars.put("menu", rootMenu);
421 vars.put("title", lang.getTranslation(p.getTitle()));
422 vars.put("static", getStaticTemplateVar(isSecure));
423 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
424 vars.put("content", content);
425 if (currentAuthContext != null) {
426 // TODO maybe move this information into the AuthContext object
427 vars.put("loginMethod", req.getSession().getAttribute(LOGIN_METHOD));
428 vars.put("authContext", currentAuthContext);
431 resp.setContentType("text/html; charset=utf-8");
432 baseTemplate.output(resp.getWriter(), lang, vars);
434 resp.sendError(404, "Page not found.");
439 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
440 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
441 hsr.addHeader("Access-Control-Max-Age", "60");
443 hsr.addHeader("Content-Security-Policy", httpsCSP);
445 hsr.addHeader("Content-Security-Policy", httpCSP);
447 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
451 private static String httpsCSP = genHttpsCSP();
453 private static String httpCSP = genHttpCSP();
455 private static String genHttpsCSP() {
456 StringBuffer csp = new StringBuffer();
457 csp.append("default-src 'none'");
458 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
459 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
460 csp.append(";media-src 'none'; object-src 'none'");
461 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
462 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
463 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
464 // csp.append(";report-url https://api.cacert.org/security/csp/report");
465 return csp.toString();
468 private static String genHttpCSP() {
469 StringBuffer csp = new StringBuffer();
470 csp.append("default-src 'none'");
471 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
472 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
473 csp.append(";media-src 'none'; object-src 'none'");
474 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
475 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
476 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
477 // csp.append(";report-url http://api.cacert.org/security/csp/report");
478 return csp.toString();
482 * Requests Pinging of domains.
485 * if not null, the {@link DomainPingConfiguration} to test, if
486 * null, just re-check if there is something to do.
488 public static void notifyPinger(DomainPingConfiguration toReping) {
489 if (toReping != null) {
490 instance.pinger.queue(toReping);
492 instance.pinger.interrupt();