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;
77 import org.cacert.gigi.util.TimeConditions;
79 public final class Gigi extends HttpServlet {
81 private class MenuBuilder {
83 private LinkedList<Menu> categories = new LinkedList<Menu>();
85 private HashMap<String, Page> pages = new HashMap<String, Page>();
87 private MenuCollector rootMenu;
89 public MenuBuilder() {}
91 private void putPage(String path, Page p, String category) {
93 if (category == null) {
96 Menu m = getMenu(category);
97 m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
101 private Menu getMenu(String category) {
103 for (Menu menu : categories) {
104 if (menu.getMenuName().equals(category)) {
110 m = new Menu(category);
116 public MenuCollector generateMenu() throws ServletException {
117 putPage("/denied", new AccessDenied(), null);
118 putPage("/error", new PageNotFound(), null);
119 putPage("/login", new LoginPage(), null);
120 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getWwwHostNamePort() + "/login", "Password Login") {
123 public boolean isPermitted(AuthorizationContext ac) {
127 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
130 public boolean isPermitted(AuthorizationContext ac) {
134 putPage("/", new MainPage(), null);
135 putPage("/roots", new RootCertPage(truststore), "SomeCA.org");
136 putPage("/about", new AboutPage(), "SomeCA.org");
138 putPage("/secure", new TestSecure(), null);
139 putPage(Verify.PATH, new Verify(), null);
140 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
141 putPage(RegisterPage.PATH, new RegisterPage(), "SomeCA.org");
142 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
143 putPage(MailOverview.DEFAULT_PATH, new MailOverview(), "Certificates");
144 putPage(DomainOverview.PATH + "*", new DomainOverview(), "Certificates");
146 putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
147 putPage(MyPoints.PATH, new MyPoints(), "Web of Trust");
148 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
150 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
151 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
152 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
154 putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "Support Console");
155 putPage(FindUserPage.PATH, new FindUserPage(), "Support Console");
156 putPage(FindDomainPage.PATH, new FindDomainPage(), "Support Console");
158 putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage(), null);
159 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
160 putPage(History.PATH, new History(false), "My Account");
161 putPage(FindAgentAccess.PATH, new OneFormPage("Access to Find Agent", FindAgentAccess.class) {
164 public String getSuccessPath(Form f) {
165 return FindAgentAccess.PATH;
168 putPage(History.SUPPORT_PATH, new History(true), null);
169 putPage(UserTrainings.PATH, new UserTrainings(false), "My Account");
170 putPage(MyDetails.PATH, new MyDetails(), "My Account");
171 putPage(UserTrainings.SUPPORT_PATH, new UserTrainings(true), null);
173 putPage(PasswordResetPage.PATH, new PasswordResetPage(), null);
174 putPage(LogoutPage.PATH, new LogoutPage(), null);
178 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
179 Page p = (Page) manager.getMethod("getInstance").invoke(null);
180 String pa = (String) manager.getField("PATH").get(null);
181 putPage(pa + "/*", p, "Gigi test server");
182 } catch (ReflectiveOperationException e) {
188 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
189 } catch (UnsupportedEncodingException e) {
190 throw new ServletException(e);
192 rootMenu = new MenuCollector();
194 Menu languages = new Menu("Language");
195 addLanguages(languages);
196 categories.add(languages);
197 for (Menu menu : categories) {
202 // rootMenu.prepare();
206 private void addLanguages(Menu languages) {
207 for (Locale l : Language.getSupportedLocales()) {
208 languages.addItem(new SimpleUntranslatedMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
212 public Map<String, Page> getPages() {
213 return Collections.unmodifiableMap(pages);
217 public static final String LOGGEDIN = "loggedin";
219 public static final String CERT_SERIAL = "org.cacert.gigi.serial";
221 public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
223 public static final String AUTH_CONTEXT = "auth";
225 public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
227 private static final long serialVersionUID = -6386785421902852904L;
229 private static Gigi instance;
231 private static final Template baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));;
233 private PingerDaemon pinger;
235 private KeyStore truststore;
237 private boolean testing;
239 private MenuCollector rootMenu;
241 private Map<String, Page> pages;
243 private boolean firstInstanceInited = false;
245 public Gigi(Properties conf, KeyStore truststore) {
246 synchronized (Gigi.class) {
247 if (instance != null) {
248 throw new IllegalStateException("Multiple Gigi instances!");
250 testing = conf.getProperty("testing") != null;
252 DomainAssessment.init(conf);
253 DatabaseConnection.init(conf);
254 TimeConditions.init(conf);
255 this.truststore = truststore;
256 pinger = new PingerDaemon(truststore);
262 public synchronized void init() throws ServletException {
263 if (firstInstanceInited) {
267 // ensure those static initializers are finished
268 try (Link l = DatabaseConnection.newLink(false)) {
269 CACertificate.getById(1);
270 CertificateProfile.getById(1);
271 CATSType.ASSURER_CHALLENGE.getDisplayName();
272 } catch (InterruptedException e) {
276 MenuBuilder mb = new MenuBuilder();
277 rootMenu = mb.generateMenu();
278 pages = mb.getPages();
280 firstInstanceInited = true;
284 private Page getPage(String pathInfo) {
285 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
286 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
288 Page page = pages.get(pathInfo);
292 page = pages.get(pathInfo + "/*");
296 int idx = pathInfo.lastIndexOf('/');
297 if (idx == -1 || idx == 0) {
301 page = pages.get(pathInfo.substring(0, idx) + "/*");
305 int lIdx = pathInfo.lastIndexOf('/', idx - 1);
309 String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
310 page = pages.get(lastResort);
315 private static String staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
317 private static String staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
319 private static String getStaticTemplateVar(boolean https) {
321 return staticTemplateVarHttps;
323 return staticTemplateVarHttp;
328 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
329 if ("/error".equals(req.getPathInfo()) || "/denied".equals(req.getPathInfo())) {
330 if (DatabaseConnection.hasInstance()) {
331 serviceWithConnection(req, resp);
335 try (DatabaseConnection.Link l = DatabaseConnection.newLink( !req.getMethod().equals("POST"))) {
336 serviceWithConnection(req, resp);
337 } catch (InterruptedException e) {
342 protected void serviceWithConnection(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
343 boolean isSecure = req.isSecure();
344 addXSSHeaders(resp, isSecure);
345 // Firefox only sends this, if it's a cross domain access; safari sends
347 String originHeader = req.getHeader("Origin");
348 if (originHeader != null //
349 && !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
350 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
351 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
352 resp.setContentType("text/html; charset=utf-8");
353 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>");
356 HttpSession hs = req.getSession();
357 String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
358 if (clientSerial != null) {
359 X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
360 if (cert == null || cert[0] == null//
361 || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial) //
362 || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
364 resp.sendError(403, "Certificate mismatch.");
369 if (req.getParameter("lang") != null) {
370 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
371 Language lu = Language.getInstance(l);
372 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
374 final Page p = getPage(req.getPathInfo());
377 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
378 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
381 AuthorizationContext currentAuthContext = LoginPage.getAuthorizationContext(req);
382 if ( !p.isPermitted(currentAuthContext)) {
383 if (hs.getAttribute("loggedin") == null) {
384 String request = req.getPathInfo();
385 request = request.split("\\?")[0];
386 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
387 resp.sendRedirect("/login");
393 if (p.beforeTemplate(req, resp)) {
396 HashMap<String, Object> vars = new HashMap<String, Object>();
397 // System.out.println(req.getMethod() + ": " + req.getPathInfo() +
399 Outputable content = new Outputable() {
402 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
404 if (req.getMethod().equals("POST")) {
405 if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
412 } catch (CSRFException err) {
414 resp.sendError(500, "CSRF invalid");
415 } catch (IOException e) {
418 } catch (IOException e) {
424 Language lang = Page.getLanguage(req);
426 vars.put(Menu.AUTH_VALUE, currentAuthContext);
427 vars.put("menu", rootMenu);
428 vars.put("title", lang.getTranslation(p.getTitle()));
429 vars.put("static", getStaticTemplateVar(isSecure));
430 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
431 vars.put("content", content);
432 if (currentAuthContext != null) {
433 // TODO maybe move this information into the AuthContext object
434 vars.put("loginMethod", req.getSession().getAttribute(LOGIN_METHOD));
435 vars.put("authContext", currentAuthContext);
438 resp.setContentType("text/html; charset=utf-8");
439 baseTemplate.output(resp.getWriter(), lang, vars);
441 resp.sendError(404, "Page not found.");
446 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
447 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
448 hsr.addHeader("Access-Control-Max-Age", "60");
450 hsr.addHeader("Content-Security-Policy", httpsCSP);
452 hsr.addHeader("Content-Security-Policy", httpCSP);
454 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
458 private static String httpsCSP = genHttpsCSP();
460 private static String httpCSP = genHttpCSP();
462 private static String genHttpsCSP() {
463 StringBuffer csp = new StringBuffer();
464 csp.append("default-src 'none'");
465 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
466 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
467 csp.append(";media-src 'none'; object-src 'none'");
468 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
469 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
470 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
471 // csp.append(";report-url https://api.cacert.org/security/csp/report");
472 return csp.toString();
475 private static String genHttpCSP() {
476 StringBuffer csp = new StringBuffer();
477 csp.append("default-src 'none'");
478 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
479 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
480 csp.append(";media-src 'none'; object-src 'none'");
481 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
482 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
483 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
484 // csp.append(";report-url http://api.cacert.org/security/csp/report");
485 return csp.toString();
489 * Requests Pinging of domains.
492 * if not null, the {@link DomainPingConfiguration} to test, if
493 * null, just re-check if there is something to do.
495 public static void notifyPinger(DomainPingConfiguration toReping) {
496 if (toReping != null) {
497 instance.pinger.queue(toReping);
499 instance.pinger.interrupt();