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.PageMenuItem;
30 import org.cacert.gigi.output.SimpleMenuItem;
31 import org.cacert.gigi.output.template.Form.CSRFException;
32 import org.cacert.gigi.output.template.Outputable;
33 import org.cacert.gigi.output.template.Template;
34 import org.cacert.gigi.pages.HandlesMixedRequest;
35 import org.cacert.gigi.pages.LoginPage;
36 import org.cacert.gigi.pages.LogoutPage;
37 import org.cacert.gigi.pages.MainPage;
38 import org.cacert.gigi.pages.Page;
39 import org.cacert.gigi.pages.PolicyIndex;
40 import org.cacert.gigi.pages.RootCertPage;
41 import org.cacert.gigi.pages.StaticPage;
42 import org.cacert.gigi.pages.TestSecure;
43 import org.cacert.gigi.pages.Verify;
44 import org.cacert.gigi.pages.account.ChangePasswordPage;
45 import org.cacert.gigi.pages.account.MyDetails;
46 import org.cacert.gigi.pages.account.UserHistory;
47 import org.cacert.gigi.pages.account.UserTrainings;
48 import org.cacert.gigi.pages.account.certs.CertificateAdd;
49 import org.cacert.gigi.pages.account.certs.Certificates;
50 import org.cacert.gigi.pages.account.domain.DomainOverview;
51 import org.cacert.gigi.pages.account.mail.MailOverview;
52 import org.cacert.gigi.pages.admin.TTPAdminPage;
53 import org.cacert.gigi.pages.admin.support.FindDomainPage;
54 import org.cacert.gigi.pages.admin.support.FindUserPage;
55 import org.cacert.gigi.pages.admin.support.SupportEnterTicketPage;
56 import org.cacert.gigi.pages.admin.support.SupportUserDetailsPage;
57 import org.cacert.gigi.pages.error.AccessDenied;
58 import org.cacert.gigi.pages.error.PageNotFound;
59 import org.cacert.gigi.pages.main.RegisterPage;
60 import org.cacert.gigi.pages.orga.CreateOrgPage;
61 import org.cacert.gigi.pages.orga.ViewOrgPage;
62 import org.cacert.gigi.pages.wot.AssurePage;
63 import org.cacert.gigi.pages.wot.MyListingPage;
64 import org.cacert.gigi.pages.wot.MyPoints;
65 import org.cacert.gigi.pages.wot.RequestTTPPage;
66 import org.cacert.gigi.ping.PingerDaemon;
67 import org.cacert.gigi.util.AuthorizationContext;
68 import org.cacert.gigi.util.ServerConstants;
70 public class Gigi extends HttpServlet {
72 private class MenuBuilder {
74 private LinkedList<Menu> categories = new LinkedList<Menu>();
76 private HashMap<String, Page> pages = new HashMap<String, Page>();
78 private Menu rootMenu;
80 public MenuBuilder() {}
82 private void putPage(String path, Page p, String category) {
84 if (category == null) {
87 Menu m = getMenu(category);
88 m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
92 private Menu getMenu(String category) {
94 for (Menu menu : categories) {
95 if (menu.getMenuName().equals(category)) {
101 m = new Menu(category);
107 public Menu generateMenu() throws ServletException {
108 putPage("/denied", new AccessDenied(), null);
109 putPage("/error", new PageNotFound(), null);
110 putPage("/login", new LoginPage("Password Login"), null);
111 getMenu("CAcert.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getWwwHostNamePort() + "/login", "Password Login") {
114 public boolean isPermitted(AuthorizationContext ac) {
118 getMenu("CAcert.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
121 public boolean isPermitted(AuthorizationContext ac) {
125 putPage("/", new MainPage("CAcert - Home"), null);
126 putPage("/roots", new RootCertPage(truststore), "CAcert.org");
127 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
128 putPage(LogoutPage.PATH, new LogoutPage("Logout"), "My Account");
129 putPage("/secure", new TestSecure(), null);
130 putPage(Verify.PATH, new Verify(), null);
131 putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
132 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
133 putPage(MyDetails.PATH, new MyDetails(), "My Account");
134 putPage(RegisterPage.PATH, new RegisterPage(), "CAcert.org");
135 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
136 putPage(MailOverview.DEFAULT_PATH, new MailOverview("Email addresses"), "Certificates");
137 putPage(DomainOverview.PATH + "*", new DomainOverview("Domains"), "Certificates");
138 putPage(MyPoints.PATH, new MyPoints("My Points"), "Web of Trust");
139 putPage(MyListingPage.PATH, new MyListingPage(), "Web of Trust");
140 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
141 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
142 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
143 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
145 putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "Support Console");
146 putPage(FindUserPage.PATH, new FindUserPage("Find User"), "Support Console");
147 putPage(FindDomainPage.PATH, new FindDomainPage("Find Domain"), "Support Console");
149 putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage("Support: User Details"), null);
150 putPage(UserHistory.PATH, new UserHistory(false), "My Account");
151 putPage(UserHistory.SUPPORT_PATH, new UserHistory(true), null);
152 putPage(UserTrainings.PATH, new UserTrainings(false), "My Account");
153 putPage(UserTrainings.SUPPORT_PATH, new UserTrainings(true), null);
156 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
157 Page p = (Page) manager.getMethod("getInstance").invoke(null);
158 String pa = (String) manager.getField("PATH").get(null);
159 putPage(pa + "/*", p, "Gigi test server");
160 } catch (ReflectiveOperationException e) {
166 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
167 } catch (UnsupportedEncodingException e) {
168 throw new ServletException(e);
170 baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
171 rootMenu = new Menu("Main");
172 Menu about = new Menu("About CAcert.org");
173 categories.add(about);
175 about.addItem(new SimpleMenuItem("//blog.cacert.org/", "CAcert News"));
176 about.addItem(new SimpleMenuItem("//wiki.cacert.org/", "Wiki Documentation"));
177 putPage(PolicyIndex.DEFAULT_PATH, new PolicyIndex(), "About CAcert.org");
178 about.addItem(new SimpleMenuItem("//wiki.cacert.org/FAQ/Privileges", "Point System"));
179 about.addItem(new SimpleMenuItem("//bugs.cacert.org/", "Bug Database"));
180 about.addItem(new SimpleMenuItem("//wiki.cacert.org/Board", "CAcert Board"));
181 about.addItem(new SimpleMenuItem("//lists.cacert.org/wws", "Mailing Lists"));
182 about.addItem(new SimpleMenuItem("//blog.CAcert.org/feed", "RSS News Feed"));
184 Menu languages = new Menu("Translations");
185 for (Locale l : Language.getSupportedLocales()) {
186 languages.addItem(new SimpleMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
188 categories.add(languages);
189 for (Menu menu : categories) {
191 rootMenu.addItem(menu);
198 public Map<String, Page> getPages() {
199 return Collections.unmodifiableMap(pages);
203 public static final String LOGGEDIN = "loggedin";
205 public static final String CERT_SERIAL = "org.cacert.gigi.serial";
207 public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
209 public static final String AUTH_CONTEXT = "auth";
211 public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
213 private static final long serialVersionUID = -6386785421902852904L;
215 private static Gigi instance;
217 private Template baseTemplate;
219 private PingerDaemon pinger;
221 private KeyStore truststore;
223 private boolean testing;
225 private Menu rootMenu;
227 private Map<String, Page> pages;
229 private boolean firstInstanceInited = false;
231 public Gigi(Properties conf, KeyStore truststore) {
232 synchronized (Gigi.class) {
233 if (instance != null) {
234 throw new IllegalStateException("Multiple Gigi instances!");
236 testing = conf.getProperty("testing") != null;
238 DatabaseConnection.init(conf);
239 this.truststore = truststore;
240 pinger = new PingerDaemon(truststore);
246 public synchronized void init() throws ServletException {
247 if (firstInstanceInited) {
251 // ensure those static initializers are finished
252 CACertificate.getById(1);
253 CertificateProfile.getById(1);
255 MenuBuilder mb = new MenuBuilder();
256 rootMenu = mb.generateMenu();
257 pages = mb.getPages();
259 firstInstanceInited = true;
263 private Page getPage(String pathInfo) {
264 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
265 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
267 Page page = pages.get(pathInfo);
271 page = pages.get(pathInfo + "/*");
275 int idx = pathInfo.lastIndexOf('/');
276 if (idx == -1 || idx == 0) {
280 page = pages.get(pathInfo.substring(0, idx) + "/*");
284 int lIdx = pathInfo.lastIndexOf('/', idx - 1);
288 String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
289 page = pages.get(lastResort);
294 private static String staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
296 private static String staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
298 private static String getStaticTemplateVar(boolean https) {
300 return staticTemplateVarHttps;
302 return staticTemplateVarHttp;
307 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
308 boolean isSecure = req.isSecure();
309 addXSSHeaders(resp, isSecure);
310 // Firefox only sends this, if it's a cross domain access; safari sends
312 String originHeader = req.getHeader("Origin");
313 if (originHeader != null //
315 !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
316 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
317 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
318 resp.setContentType("text/html; charset=utf-8");
319 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>");
322 HttpSession hs = req.getSession();
323 String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
324 if (clientSerial != null) {
325 X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
326 if (cert == null || cert[0] == null//
327 || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial) //
328 || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
330 resp.sendError(403, "Certificate mismatch.");
335 if (req.getParameter("lang") != null) {
336 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
337 Language lu = Language.getInstance(l);
338 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
340 final Page p = getPage(req.getPathInfo());
343 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
344 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
347 AuthorizationContext currentAuthContext = LoginPage.getAuthorizationContext(req);
348 if ( !p.isPermitted(currentAuthContext)) {
349 if (hs.getAttribute("loggedin") == null) {
350 String request = req.getPathInfo();
351 request = request.split("\\?")[0];
352 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
353 resp.sendRedirect("/login");
359 if (p.beforeTemplate(req, resp)) {
362 HashMap<String, Object> vars = new HashMap<String, Object>();
363 Outputable content = new Outputable() {
366 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
368 if (req.getMethod().equals("POST")) {
369 if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
376 } catch (CSRFException err) {
378 resp.sendError(500, "CSRF invalid");
379 } catch (IOException e) {
382 } catch (IOException e) {
388 Language lang = Page.getLanguage(req);
390 vars.put(Menu.AUTH_VALUE, currentAuthContext);
391 vars.put("menu", rootMenu);
392 vars.put("title", lang.getTranslation(p.getTitle()));
393 vars.put("static", getStaticTemplateVar(isSecure));
394 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
395 vars.put("content", content);
396 if (currentAuthContext != null) {
397 // TODO maybe move this information into the AuthContext object
398 vars.put("loginMethod", lang.getTranslation((String) req.getSession().getAttribute(LOGIN_METHOD)));
399 vars.put("authContext", currentAuthContext);
402 resp.setContentType("text/html; charset=utf-8");
403 baseTemplate.output(resp.getWriter(), lang, vars);
405 resp.sendError(404, "Page not found.");
410 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
411 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
412 hsr.addHeader("Access-Control-Max-Age", "60");
414 hsr.addHeader("Content-Security-Policy", httpsCSP);
416 hsr.addHeader("Content-Security-Policy", httpCSP);
418 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
422 private static String httpsCSP = genHttpsCSP();
424 private static String httpCSP = genHttpCSP();
426 private static String genHttpsCSP() {
427 StringBuffer csp = new StringBuffer();
428 csp.append("default-src 'none'");
429 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
430 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
431 csp.append(";media-src 'none'; object-src 'none'");
432 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
433 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
434 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
435 csp.append(";report-url https://api.cacert.org/security/csp/report");
436 return csp.toString();
439 private static String genHttpCSP() {
440 StringBuffer csp = new StringBuffer();
441 csp.append("default-src 'none'");
442 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
443 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
444 csp.append(";media-src 'none'; object-src 'none'");
445 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
446 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
447 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
448 csp.append(";report-url http://api.cacert.org/security/csp/report");
449 return csp.toString();
453 * Requests Pinging of domains.
456 * if not null, the {@link DomainPingConfiguration} to test, if
457 * null, just re-check if there is something to do.
459 public static void notifyPinger(DomainPingConfiguration toReping) {
460 if (toReping != null) {
461 instance.pinger.queue(toReping);
463 instance.pinger.interrupt();