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.PasswordHash;
77 import org.cacert.gigi.util.ServerConstants;
78 import org.cacert.gigi.util.TimeConditions;
80 public final class Gigi extends HttpServlet {
82 private class MenuBuilder {
84 private LinkedList<Menu> categories = new LinkedList<Menu>();
86 private HashMap<String, Page> pages = new HashMap<String, Page>();
88 private MenuCollector rootMenu;
90 public MenuBuilder() {}
92 private void putPage(String path, Page p, String category) {
94 if (category == null) {
97 Menu m = getMenu(category);
98 m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
102 private Menu getMenu(String category) {
104 for (Menu menu : categories) {
105 if (menu.getMenuName().equals(category)) {
111 m = new Menu(category);
117 public MenuCollector generateMenu() throws ServletException {
118 putPage("/denied", new AccessDenied(), null);
119 putPage("/error", new PageNotFound(), null);
120 putPage("/login", new LoginPage(), null);
121 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getWwwHostNamePort() + "/login", "Password Login") {
124 public boolean isPermitted(AuthorizationContext ac) {
128 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
131 public boolean isPermitted(AuthorizationContext ac) {
135 putPage("/", new MainPage(), null);
136 putPage("/roots", new RootCertPage(truststore), "SomeCA.org");
137 putPage("/about", new AboutPage(), "SomeCA.org");
139 putPage("/secure", new TestSecure(), null);
140 putPage(Verify.PATH, new Verify(), null);
141 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
142 putPage(RegisterPage.PATH, new RegisterPage(), "SomeCA.org");
143 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
144 putPage(MailOverview.DEFAULT_PATH, new MailOverview(), "Certificates");
145 putPage(DomainOverview.PATH + "*", new DomainOverview(), "Certificates");
147 putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
148 putPage(MyPoints.PATH, new MyPoints(), "Web of Trust");
149 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
151 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
152 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
153 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
155 putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "Support Console");
156 putPage(FindUserPage.PATH, new FindUserPage(), "Support Console");
157 putPage(FindDomainPage.PATH, new FindDomainPage(), "Support Console");
159 putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage(), null);
160 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
161 putPage(History.PATH, new History(false), "My Account");
162 putPage(FindAgentAccess.PATH, new OneFormPage("Access to Find Agent", FindAgentAccess.class) {
165 public String getSuccessPath(Form f) {
166 return FindAgentAccess.PATH;
169 putPage(History.SUPPORT_PATH, new History(true), null);
170 putPage(UserTrainings.PATH, new UserTrainings(false), "My Account");
171 putPage(MyDetails.PATH, new MyDetails(), "My Account");
172 putPage(UserTrainings.SUPPORT_PATH, new UserTrainings(true), null);
174 putPage(PasswordResetPage.PATH, new PasswordResetPage(), null);
175 putPage(LogoutPage.PATH, new LogoutPage(), null);
179 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
180 Page p = (Page) manager.getMethod("getInstance").invoke(null);
181 String pa = (String) manager.getField("PATH").get(null);
182 putPage(pa + "/*", p, "Gigi test server");
183 } catch (ReflectiveOperationException e) {
189 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
190 } catch (UnsupportedEncodingException e) {
191 throw new ServletException(e);
193 rootMenu = new MenuCollector();
195 Menu languages = new Menu("Language");
196 addLanguages(languages);
197 categories.add(languages);
198 for (Menu menu : categories) {
203 // rootMenu.prepare();
207 private void addLanguages(Menu languages) {
208 for (Locale l : Language.getSupportedLocales()) {
209 languages.addItem(new SimpleUntranslatedMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
213 public Map<String, Page> getPages() {
214 return Collections.unmodifiableMap(pages);
218 public static final String LOGGEDIN = "loggedin";
220 public static final String CERT_SERIAL = "org.cacert.gigi.serial";
222 public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
224 public static final String AUTH_CONTEXT = "auth";
226 public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
228 private static final long serialVersionUID = -6386785421902852904L;
230 private static Gigi instance;
232 private static final Template baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));;
234 private PingerDaemon pinger;
236 private KeyStore truststore;
238 private boolean testing;
240 private MenuCollector rootMenu;
242 private Map<String, Page> pages;
244 private boolean firstInstanceInited = false;
246 public Gigi(Properties conf, KeyStore truststore) {
247 synchronized (Gigi.class) {
248 if (instance != null) {
249 throw new IllegalStateException("Multiple Gigi instances!");
251 testing = conf.getProperty("testing") != null;
253 DomainAssessment.init(conf);
254 DatabaseConnection.init(conf);
255 TimeConditions.init(conf);
256 PasswordHash.init(conf);
257 this.truststore = truststore;
258 pinger = new PingerDaemon(truststore);
264 public synchronized void init() throws ServletException {
265 if (firstInstanceInited) {
269 // ensure those static initializers are finished
270 try (Link l = DatabaseConnection.newLink(false)) {
271 CACertificate.getById(1);
272 CertificateProfile.getById(1);
273 CATSType.ASSURER_CHALLENGE.getDisplayName();
274 } catch (InterruptedException e) {
278 MenuBuilder mb = new MenuBuilder();
279 rootMenu = mb.generateMenu();
280 pages = mb.getPages();
282 firstInstanceInited = true;
286 private Page getPage(String pathInfo) {
287 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
288 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
290 Page page = pages.get(pathInfo);
294 page = pages.get(pathInfo + "/*");
298 int idx = pathInfo.lastIndexOf('/');
299 if (idx == -1 || idx == 0) {
303 page = pages.get(pathInfo.substring(0, idx) + "/*");
307 int lIdx = pathInfo.lastIndexOf('/', idx - 1);
311 String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
312 page = pages.get(lastResort);
317 private static String staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
319 private static String staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
321 private static String getStaticTemplateVar(boolean https) {
323 return staticTemplateVarHttps;
325 return staticTemplateVarHttp;
330 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
331 if ("/error".equals(req.getPathInfo()) || "/denied".equals(req.getPathInfo())) {
332 if (DatabaseConnection.hasInstance()) {
333 serviceWithConnection(req, resp);
337 try (DatabaseConnection.Link l = DatabaseConnection.newLink( !req.getMethod().equals("POST"))) {
338 serviceWithConnection(req, resp);
339 } catch (InterruptedException e) {
344 protected void serviceWithConnection(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
345 boolean isSecure = req.isSecure();
346 addXSSHeaders(resp, isSecure);
347 // Firefox only sends this, if it's a cross domain access; safari sends
349 String originHeader = req.getHeader("Origin");
350 if (originHeader != null //
351 && !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
352 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
353 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
354 resp.setContentType("text/html; charset=utf-8");
355 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>");
358 HttpSession hs = req.getSession();
359 String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
360 if (clientSerial != null) {
361 X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
362 if (cert == null || cert[0] == null//
363 || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial) //
364 || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
366 resp.sendError(403, "Certificate mismatch.");
371 if (req.getParameter("lang") != null) {
372 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
373 Language lu = Language.getInstance(l);
374 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
376 final Page p = getPage(req.getPathInfo());
379 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
380 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
383 AuthorizationContext currentAuthContext = LoginPage.getAuthorizationContext(req);
384 if ( !p.isPermitted(currentAuthContext)) {
385 if (hs.getAttribute("loggedin") == null) {
386 String request = req.getPathInfo();
387 request = request.split("\\?")[0];
388 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
389 resp.sendRedirect("/login");
395 if (p.beforeTemplate(req, resp)) {
398 HashMap<String, Object> vars = new HashMap<String, Object>();
399 // System.out.println(req.getMethod() + ": " + req.getPathInfo() +
401 Outputable content = new Outputable() {
404 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
406 if (req.getMethod().equals("POST")) {
407 if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
414 } catch (CSRFException err) {
416 resp.sendError(500, "CSRF invalid");
417 } catch (IOException e) {
420 } catch (IOException e) {
426 Language lang = Page.getLanguage(req);
428 vars.put(Menu.AUTH_VALUE, currentAuthContext);
429 vars.put("menu", rootMenu);
430 vars.put("title", lang.getTranslation(p.getTitle()));
431 vars.put("static", getStaticTemplateVar(isSecure));
432 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
433 vars.put("content", content);
434 if (currentAuthContext != null) {
435 // TODO maybe move this information into the AuthContext object
436 vars.put("loginMethod", req.getSession().getAttribute(LOGIN_METHOD));
437 vars.put("authContext", currentAuthContext);
440 resp.setContentType("text/html; charset=utf-8");
441 baseTemplate.output(resp.getWriter(), lang, vars);
443 resp.sendError(404, "Page not found.");
448 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
449 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
450 hsr.addHeader("Access-Control-Max-Age", "60");
452 hsr.addHeader("Content-Security-Policy", httpsCSP);
454 hsr.addHeader("Content-Security-Policy", httpCSP);
456 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
460 private static String httpsCSP = genHttpsCSP();
462 private static String httpCSP = genHttpCSP();
464 private static String genHttpsCSP() {
465 StringBuffer csp = new StringBuffer();
466 csp.append("default-src 'none'");
467 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
468 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
469 csp.append(";media-src 'none'; object-src 'none'");
470 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
471 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
472 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
473 // csp.append(";report-url https://api.cacert.org/security/csp/report");
474 return csp.toString();
477 private static String genHttpCSP() {
478 StringBuffer csp = new StringBuffer();
479 csp.append("default-src 'none'");
480 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
481 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
482 csp.append(";media-src 'none'; object-src 'none'");
483 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
484 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
485 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
486 // csp.append(";report-url http://api.cacert.org/security/csp/report");
487 return csp.toString();
491 * Requests Pinging of domains.
494 * if not null, the {@link DomainPingConfiguration} to test, if
495 * null, just re-check if there is something to do.
497 public static void notifyPinger(DomainPingConfiguration toReping) {
498 if (toReping != null) {
499 instance.pinger.queue(toReping);
501 instance.pinger.interrupt();