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.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.domain.EditDomain;
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.FindCertPage;
62 import org.cacert.gigi.pages.admin.support.FindUserByDomainPage;
63 import org.cacert.gigi.pages.admin.support.FindUserByEmailPage;
64 import org.cacert.gigi.pages.admin.support.SupportEnterTicketPage;
65 import org.cacert.gigi.pages.admin.support.SupportUserDetailsPage;
66 import org.cacert.gigi.pages.error.AccessDenied;
67 import org.cacert.gigi.pages.error.PageNotFound;
68 import org.cacert.gigi.pages.main.RegisterPage;
69 import org.cacert.gigi.pages.orga.CreateOrgPage;
70 import org.cacert.gigi.pages.orga.ViewOrgPage;
71 import org.cacert.gigi.pages.statistics.StatisticsRoles;
72 import org.cacert.gigi.pages.wot.AssurePage;
73 import org.cacert.gigi.pages.wot.Points;
74 import org.cacert.gigi.pages.wot.RequestTTPPage;
75 import org.cacert.gigi.ping.PingerDaemon;
76 import org.cacert.gigi.util.AuthorizationContext;
77 import org.cacert.gigi.util.DomainAssessment;
78 import org.cacert.gigi.util.PasswordHash;
79 import org.cacert.gigi.util.ServerConstants;
80 import org.cacert.gigi.util.TimeConditions;
82 public final class Gigi extends HttpServlet {
84 private class MenuBuilder {
86 private LinkedList<Menu> categories = new LinkedList<Menu>();
88 private HashMap<String, Page> pages = new HashMap<String, Page>();
90 private MenuCollector rootMenu;
92 public MenuBuilder() {}
94 private void putPage(String path, Page p, String category) {
96 if (category == null) {
99 Menu m = getMenu(category);
100 m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
104 private Menu getMenu(String category) {
106 for (Menu menu : categories) {
107 if (menu.getMenuName().equals(category)) {
113 m = new Menu(category);
119 public MenuCollector generateMenu() throws ServletException {
120 putPage("/denied", new AccessDenied(), null);
121 putPage("/error", new PageNotFound(), null);
122 putPage("/login", new LoginPage(), null);
123 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getWwwHostNamePort() + "/login", "Password Login") {
126 public boolean isPermitted(AuthorizationContext ac) {
130 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
133 public boolean isPermitted(AuthorizationContext ac) {
137 putPage("/", new MainPage(), null);
138 putPage("/roots", new RootCertPage(truststore), "SomeCA.org");
139 putPage(StatisticsRoles.PATH, new StatisticsRoles(), "SomeCA.org");
140 putPage("/about", new AboutPage(), "SomeCA.org");
142 putPage("/secure", new TestSecure(), null);
143 putPage(Verify.PATH, new Verify(), null);
144 putPage(Certificates.PATH + "/*", new Certificates(false), "Certificates");
145 putPage(RegisterPage.PATH, new RegisterPage(), "SomeCA.org");
146 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
147 putPage(MailOverview.DEFAULT_PATH, new MailOverview(), "Certificates");
148 putPage(DomainOverview.PATH, new DomainOverview(), "Certificates");
149 putPage(EditDomain.PATH + "*", new EditDomain(), null);
151 putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
152 putPage(Points.PATH, new Points(false), "Web of Trust");
153 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
155 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
156 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
157 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
159 putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "Support Console");
160 putPage(FindUserByEmailPage.PATH, new FindUserByEmailPage(), "Support Console");
161 putPage(FindUserByDomainPage.PATH, new FindUserByDomainPage(), "Support Console");
162 putPage(FindCertPage.PATH, new FindCertPage(), "Support Console");
164 putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage(), null);
165 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
166 putPage(History.PATH, new History(false), "My Account");
167 putPage(FindAgentAccess.PATH, new OneFormPage("Access to Find Agent", FindAgentAccess.class), "My Account");
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);
172 putPage(Points.SUPPORT_PATH, new Points(true), null);
173 putPage(Certificates.SUPPORT_PATH + "/*", new Certificates(true), null);
175 putPage(PasswordResetPage.PATH, new PasswordResetPage(), null);
176 putPage(LogoutPage.PATH, new LogoutPage(), null);
180 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
181 Page p = (Page) manager.getMethod("getInstance").invoke(null);
182 String pa = (String) manager.getField("PATH").get(null);
183 putPage(pa + "/*", p, "Gigi test server");
184 } catch (ReflectiveOperationException e) {
190 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
191 } catch (UnsupportedEncodingException e) {
192 throw new ServletException(e);
194 rootMenu = new MenuCollector();
196 Menu languages = new Menu("Language");
197 addLanguages(languages);
198 categories.add(languages);
199 for (Menu menu : categories) {
204 // rootMenu.prepare();
208 private void addLanguages(Menu languages) {
209 for (Locale l : Language.getSupportedLocales()) {
210 languages.addItem(new SimpleUntranslatedMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
214 public Map<String, Page> getPages() {
215 return Collections.unmodifiableMap(pages);
219 public static final String LOGGEDIN = "loggedin";
221 public static final String CERT_SERIAL = "org.cacert.gigi.serial";
223 public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
225 public static final String AUTH_CONTEXT = "auth";
227 public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
229 private static final long serialVersionUID = -6386785421902852904L;
231 private static Gigi instance;
233 private static final Template baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));;
235 private PingerDaemon pinger;
237 private KeyStore truststore;
239 private boolean testing;
241 private MenuCollector rootMenu;
243 private Map<String, Page> pages;
245 private boolean firstInstanceInited = false;
247 public Gigi(Properties conf, KeyStore truststore) {
248 synchronized (Gigi.class) {
249 if (instance != null) {
250 throw new IllegalStateException("Multiple Gigi instances!");
252 testing = conf.getProperty("testing") != null;
254 DomainAssessment.init(conf);
255 DatabaseConnection.init(conf);
256 TimeConditions.init(conf);
257 PasswordHash.init(conf);
258 this.truststore = truststore;
259 pinger = new PingerDaemon(truststore);
265 public synchronized void init() throws ServletException {
266 if (firstInstanceInited) {
270 // ensure those static initializers are finished
271 try (Link l = DatabaseConnection.newLink(false)) {
272 CACertificate.getById(1);
273 CertificateProfile.getById(1);
274 CATSType.ASSURER_CHALLENGE.getDisplayName();
275 } catch (InterruptedException e) {
279 MenuBuilder mb = new MenuBuilder();
280 rootMenu = mb.generateMenu();
281 pages = mb.getPages();
283 firstInstanceInited = true;
287 private Page getPage(String pathInfo) {
288 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
289 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
291 Page page = pages.get(pathInfo);
295 page = pages.get(pathInfo + "/*");
299 int idx = pathInfo.lastIndexOf('/');
300 if (idx == -1 || idx == 0) {
304 page = pages.get(pathInfo.substring(0, idx) + "/*");
308 int lIdx = pathInfo.lastIndexOf('/', idx - 1);
312 String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
313 page = pages.get(lastResort);
318 private static String staticTemplateVar = "//" + ServerConstants.getStaticHostNamePort();
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).toLowerCase().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 != null ? lu.getLocale() : Locale.ENGLISH);
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", staticTemplateVar);
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();