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.dbObjects.CACertificate;
25 import org.cacert.gigi.dbObjects.CertificateProfile;
26 import org.cacert.gigi.dbObjects.DomainPingConfiguration;
27 import org.cacert.gigi.localisation.Language;
28 import org.cacert.gigi.output.Menu;
29 import org.cacert.gigi.output.MenuCollector;
30 import org.cacert.gigi.output.PageMenuItem;
31 import org.cacert.gigi.output.SimpleMenuItem;
32 import org.cacert.gigi.output.template.Form.CSRFException;
33 import org.cacert.gigi.output.template.Outputable;
34 import org.cacert.gigi.output.template.Template;
35 import org.cacert.gigi.pages.HandlesMixedRequest;
36 import org.cacert.gigi.pages.LoginPage;
37 import org.cacert.gigi.pages.LogoutPage;
38 import org.cacert.gigi.pages.MainPage;
39 import org.cacert.gigi.pages.Page;
40 import org.cacert.gigi.pages.PasswordResetPage;
41 import org.cacert.gigi.pages.RootCertPage;
42 import org.cacert.gigi.pages.StaticPage;
43 import org.cacert.gigi.pages.TestSecure;
44 import org.cacert.gigi.pages.Verify;
45 import org.cacert.gigi.pages.account.ChangePasswordPage;
46 import org.cacert.gigi.pages.account.History;
47 import org.cacert.gigi.pages.account.MyDetails;
48 import org.cacert.gigi.pages.account.UserTrainings;
49 import org.cacert.gigi.pages.account.certs.CertificateAdd;
50 import org.cacert.gigi.pages.account.certs.Certificates;
51 import org.cacert.gigi.pages.account.domain.DomainOverview;
52 import org.cacert.gigi.pages.account.mail.MailOverview;
53 import org.cacert.gigi.pages.admin.TTPAdminPage;
54 import org.cacert.gigi.pages.admin.support.FindDomainPage;
55 import org.cacert.gigi.pages.admin.support.FindUserPage;
56 import org.cacert.gigi.pages.admin.support.SupportEnterTicketPage;
57 import org.cacert.gigi.pages.admin.support.SupportUserDetailsPage;
58 import org.cacert.gigi.pages.error.AccessDenied;
59 import org.cacert.gigi.pages.error.PageNotFound;
60 import org.cacert.gigi.pages.main.RegisterPage;
61 import org.cacert.gigi.pages.orga.CreateOrgPage;
62 import org.cacert.gigi.pages.orga.ViewOrgPage;
63 import org.cacert.gigi.pages.wot.AssurePage;
64 import org.cacert.gigi.pages.wot.MyListingPage;
65 import org.cacert.gigi.pages.wot.MyPoints;
66 import org.cacert.gigi.pages.wot.RequestTTPPage;
67 import org.cacert.gigi.ping.PingerDaemon;
68 import org.cacert.gigi.util.AuthorizationContext;
69 import org.cacert.gigi.util.ServerConstants;
71 public final class Gigi extends HttpServlet {
73 private class MenuBuilder {
75 private LinkedList<Menu> categories = new LinkedList<Menu>();
77 private HashMap<String, Page> pages = new HashMap<String, Page>();
79 private MenuCollector rootMenu;
81 public MenuBuilder() {}
83 private void putPage(String path, Page p, String category) {
85 if (category == null) {
88 Menu m = getMenu(category);
89 m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
93 private Menu getMenu(String category) {
95 for (Menu menu : categories) {
96 if (menu.getMenuName().equals(category)) {
102 m = new Menu(category);
108 public MenuCollector generateMenu() throws ServletException {
109 putPage("/denied", new AccessDenied(), null);
110 putPage("/error", new PageNotFound(), null);
111 putPage("/login", new LoginPage("Password Login"), null);
112 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getWwwHostNamePort() + "/login", "Password Login") {
115 public boolean isPermitted(AuthorizationContext ac) {
119 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
122 public boolean isPermitted(AuthorizationContext ac) {
126 putPage("/", new MainPage("SomeCA - Home"), null);
127 putPage("/roots", new RootCertPage(truststore), "SomeCA.org");
129 putPage("/secure", new TestSecure(), null);
130 putPage(Verify.PATH, new Verify(), null);
131 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
132 putPage(RegisterPage.PATH, new RegisterPage(), "SomeCA.org");
133 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
134 putPage(MailOverview.DEFAULT_PATH, new MailOverview("Email addresses"), "Certificates");
135 putPage(DomainOverview.PATH + "*", new DomainOverview("Domains"), "Certificates");
137 putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
138 putPage(MyPoints.PATH, new MyPoints(), "Web of Trust");
139 putPage(MyListingPage.PATH, new MyListingPage(), "Web of Trust");
140 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
142 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
143 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
144 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
146 putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "Support Console");
147 putPage(FindUserPage.PATH, new FindUserPage("Find User"), "Support Console");
148 putPage(FindDomainPage.PATH, new FindDomainPage("Find Domain"), "Support Console");
150 putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage("Support: User Details"), null);
151 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
152 putPage(LogoutPage.PATH, new LogoutPage("Logout"), "My Account");
153 putPage(History.PATH, new History(false), "My Account");
154 putPage(History.SUPPORT_PATH, new History(true), null);
155 putPage(UserTrainings.PATH, new UserTrainings(false), "My Account");
156 putPage(MyDetails.PATH, new MyDetails(), "My Account");
157 putPage(UserTrainings.SUPPORT_PATH, new UserTrainings(true), null);
159 putPage(PasswordResetPage.PATH, new PasswordResetPage(), null);
163 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
164 Page p = (Page) manager.getMethod("getInstance").invoke(null);
165 String pa = (String) manager.getField("PATH").get(null);
166 putPage(pa + "/*", p, "Gigi test server");
167 } catch (ReflectiveOperationException e) {
173 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
174 } catch (UnsupportedEncodingException e) {
175 throw new ServletException(e);
177 baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
178 rootMenu = new MenuCollector();
180 Menu languages = new Menu("Translations");
181 for (Locale l : Language.getSupportedLocales()) {
182 languages.addItem(new SimpleMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
184 categories.add(languages);
185 for (Menu menu : categories) {
190 // rootMenu.prepare();
194 public Map<String, Page> getPages() {
195 return Collections.unmodifiableMap(pages);
199 public static final String LOGGEDIN = "loggedin";
201 public static final String CERT_SERIAL = "org.cacert.gigi.serial";
203 public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
205 public static final String AUTH_CONTEXT = "auth";
207 public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
209 private static final long serialVersionUID = -6386785421902852904L;
211 private static Gigi instance;
213 private Template baseTemplate;
215 private PingerDaemon pinger;
217 private KeyStore truststore;
219 private boolean testing;
221 private MenuCollector rootMenu;
223 private Map<String, Page> pages;
225 private boolean firstInstanceInited = false;
227 public Gigi(Properties conf, KeyStore truststore) {
228 synchronized (Gigi.class) {
229 if (instance != null) {
230 throw new IllegalStateException("Multiple Gigi instances!");
232 testing = conf.getProperty("testing") != null;
234 DatabaseConnection.init(conf);
235 this.truststore = truststore;
236 pinger = new PingerDaemon(truststore);
242 public synchronized void init() throws ServletException {
243 if (firstInstanceInited) {
247 // ensure those static initializers are finished
248 CACertificate.getById(1);
249 CertificateProfile.getById(1);
251 MenuBuilder mb = new MenuBuilder();
252 rootMenu = mb.generateMenu();
253 pages = mb.getPages();
255 firstInstanceInited = true;
259 private Page getPage(String pathInfo) {
260 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
261 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
263 Page page = pages.get(pathInfo);
267 page = pages.get(pathInfo + "/*");
271 int idx = pathInfo.lastIndexOf('/');
272 if (idx == -1 || idx == 0) {
276 page = pages.get(pathInfo.substring(0, idx) + "/*");
280 int lIdx = pathInfo.lastIndexOf('/', idx - 1);
284 String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
285 page = pages.get(lastResort);
290 private static String staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
292 private static String staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
294 private static String getStaticTemplateVar(boolean https) {
296 return staticTemplateVarHttps;
298 return staticTemplateVarHttp;
303 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
304 boolean isSecure = req.isSecure();
305 addXSSHeaders(resp, isSecure);
306 // Firefox only sends this, if it's a cross domain access; safari sends
308 String originHeader = req.getHeader("Origin");
309 if (originHeader != null //
311 !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
312 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
313 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
314 resp.setContentType("text/html; charset=utf-8");
315 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>");
318 HttpSession hs = req.getSession();
319 String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
320 if (clientSerial != null) {
321 X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
322 if (cert == null || cert[0] == null//
323 || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial) //
324 || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
326 resp.sendError(403, "Certificate mismatch.");
331 if (req.getParameter("lang") != null) {
332 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
333 Language lu = Language.getInstance(l);
334 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
336 final Page p = getPage(req.getPathInfo());
339 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
340 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
343 AuthorizationContext currentAuthContext = LoginPage.getAuthorizationContext(req);
344 if ( !p.isPermitted(currentAuthContext)) {
345 if (hs.getAttribute("loggedin") == null) {
346 String request = req.getPathInfo();
347 request = request.split("\\?")[0];
348 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
349 resp.sendRedirect("/login");
355 if (p.beforeTemplate(req, resp)) {
358 HashMap<String, Object> vars = new HashMap<String, Object>();
359 // System.out.println(req.getMethod() + ": " + req.getPathInfo() +
361 Outputable content = new Outputable() {
364 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
366 if (req.getMethod().equals("POST")) {
367 if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
374 } catch (CSRFException err) {
376 resp.sendError(500, "CSRF invalid");
377 } catch (IOException e) {
380 } catch (IOException e) {
386 Language lang = Page.getLanguage(req);
388 vars.put(Menu.AUTH_VALUE, currentAuthContext);
389 vars.put("menu", rootMenu);
390 vars.put("title", lang.getTranslation(p.getTitle()));
391 vars.put("static", getStaticTemplateVar(isSecure));
392 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
393 vars.put("content", content);
394 if (currentAuthContext != null) {
395 // TODO maybe move this information into the AuthContext object
396 vars.put("loginMethod", lang.getTranslation((String) req.getSession().getAttribute(LOGIN_METHOD)));
397 vars.put("authContext", currentAuthContext);
400 resp.setContentType("text/html; charset=utf-8");
401 baseTemplate.output(resp.getWriter(), lang, vars);
403 resp.sendError(404, "Page not found.");
408 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
409 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
410 hsr.addHeader("Access-Control-Max-Age", "60");
412 hsr.addHeader("Content-Security-Policy", httpsCSP);
414 hsr.addHeader("Content-Security-Policy", httpCSP);
416 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
420 private static String httpsCSP = genHttpsCSP();
422 private static String httpCSP = genHttpCSP();
424 private static String genHttpsCSP() {
425 StringBuffer csp = new StringBuffer();
426 csp.append("default-src 'none'");
427 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
428 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
429 csp.append(";media-src 'none'; object-src 'none'");
430 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
431 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
432 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
433 //csp.append(";report-url https://api.cacert.org/security/csp/report");
434 return csp.toString();
437 private static String genHttpCSP() {
438 StringBuffer csp = new StringBuffer();
439 csp.append("default-src 'none'");
440 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
441 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
442 csp.append(";media-src 'none'; object-src 'none'");
443 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
444 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
445 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
446 //csp.append(";report-url http://api.cacert.org/security/csp/report");
447 return csp.toString();
451 * Requests Pinging of domains.
454 * if not null, the {@link DomainPingConfiguration} to test, if
455 * null, just re-check if there is something to do.
457 public static void notifyPinger(DomainPingConfiguration toReping) {
458 if (toReping != null) {
459 instance.pinger.queue(toReping);
461 instance.pinger.interrupt();