1 package org.cacert.gigi;
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.security.KeyStore;
6 import java.security.cert.X509Certificate;
7 import java.util.Calendar;
8 import java.util.HashMap;
9 import java.util.LinkedList;
10 import java.util.Locale;
12 import java.util.Properties;
13 import java.util.regex.Pattern;
15 import javax.servlet.ServletException;
16 import javax.servlet.http.HttpServlet;
17 import javax.servlet.http.HttpServletRequest;
18 import javax.servlet.http.HttpServletResponse;
19 import javax.servlet.http.HttpSession;
21 import org.cacert.gigi.database.DatabaseConnection;
22 import org.cacert.gigi.dbObjects.User;
23 import org.cacert.gigi.localisation.Language;
24 import org.cacert.gigi.output.Form.CSRFException;
25 import org.cacert.gigi.output.Menu;
26 import org.cacert.gigi.output.Outputable;
27 import org.cacert.gigi.output.PageMenuItem;
28 import org.cacert.gigi.output.SimpleMenuItem;
29 import org.cacert.gigi.output.template.Template;
30 import org.cacert.gigi.pages.LoginPage;
31 import org.cacert.gigi.pages.LogoutPage;
32 import org.cacert.gigi.pages.MainPage;
33 import org.cacert.gigi.pages.Page;
34 import org.cacert.gigi.pages.PolicyIndex;
35 import org.cacert.gigi.pages.RootCertPage;
36 import org.cacert.gigi.pages.StaticPage;
37 import org.cacert.gigi.pages.TestSecure;
38 import org.cacert.gigi.pages.Verify;
39 import org.cacert.gigi.pages.account.ChangePasswordPage;
40 import org.cacert.gigi.pages.account.MyDetails;
41 import org.cacert.gigi.pages.account.certs.CertificateAdd;
42 import org.cacert.gigi.pages.account.certs.Certificates;
43 import org.cacert.gigi.pages.account.domain.DomainOverview;
44 import org.cacert.gigi.pages.account.mail.MailOverview;
45 import org.cacert.gigi.pages.admin.TTPAdminPage;
46 import org.cacert.gigi.pages.error.AccessDenied;
47 import org.cacert.gigi.pages.error.PageNotFound;
48 import org.cacert.gigi.pages.main.RegisterPage;
49 import org.cacert.gigi.pages.orga.CreateOrgPage;
50 import org.cacert.gigi.pages.orga.ViewOrgPage;
51 import org.cacert.gigi.pages.wot.AssurePage;
52 import org.cacert.gigi.pages.wot.MyPoints;
53 import org.cacert.gigi.pages.wot.RequestTTPPage;
54 import org.cacert.gigi.ping.PingerDaemon;
55 import org.cacert.gigi.util.ServerConstants;
57 public class Gigi extends HttpServlet {
59 private boolean firstInstanceInited = false;
61 public static final String LOGGEDIN = "loggedin";
63 public static final String CERT_SERIAL = "org.cacert.gigi.serial";
65 public static final String USER = "user";
67 private static final long serialVersionUID = -6386785421902852904L;
69 private Template baseTemplate;
71 private LinkedList<Menu> categories = new LinkedList<Menu>();
73 private HashMap<String, Page> pages = new HashMap<String, Page>();
75 private HashMap<Page, String> reveresePages = new HashMap<Page, String>();
77 private Menu rootMenu;
79 private static Gigi instance;
81 private PingerDaemon pinger;
83 private KeyStore truststore;
85 private boolean testing;
87 public Gigi(Properties conf, KeyStore truststore) {
88 if (instance != null) {
89 throw new IllegalStateException("Multiple Gigi instances!");
91 testing = conf.getProperty("testing") != null;
93 DatabaseConnection.init(conf);
94 this.truststore = truststore;
95 pinger = new PingerDaemon(truststore);
100 public void init() throws ServletException {
101 if ( !firstInstanceInited) {
102 putPage("/denied", new AccessDenied(), null);
103 putPage("/error", new PageNotFound(), null);
104 putPage("/login", new LoginPage("Password Login"), "CAcert.org");
105 getMenu("CAcert.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
108 public boolean isPermitted(User u) {
112 putPage("/", new MainPage("CAcert - Home"), null);
113 putPage("/roots", new RootCertPage(truststore), "CAcert.org");
114 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
115 putPage(LogoutPage.PATH, new LogoutPage("Logout"), "My Account");
116 putPage("/secure", new TestSecure(), null);
117 putPage(Verify.PATH, new Verify(), null);
118 putPage(AssurePage.PATH + "/*", new AssurePage(), "CAcert Web of Trust");
119 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
120 putPage(MyDetails.PATH, new MyDetails(), "My Account");
121 putPage(RegisterPage.PATH, new RegisterPage(), "CAcert.org");
122 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
123 putPage(MailOverview.DEFAULT_PATH, new MailOverview("My email addresses"), "Certificates");
124 putPage(DomainOverview.PATH + "*", new DomainOverview("Domains"), "Certificates");
125 putPage(MyPoints.PATH, new MyPoints("My Points"), "CAcert Web of Trust");
126 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "CAcert Web of Trust");
127 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
128 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
129 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
132 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
133 Page p = (Page) manager.getMethod("getInstance").invoke(null);
134 String pa = (String) manager.getField("PATH").get(null);
135 putPage(pa + "/*", p, "Gigi test server");
136 } catch (ReflectiveOperationException e) {
141 putPage("/wot/rules", new StaticPage("CAcert Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "CAcert Web of Trust");
142 baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
143 rootMenu = new Menu("Main");
144 Menu about = new Menu("About CAcert.org");
145 categories.add(about);
147 about.addItem(new SimpleMenuItem("//blog.cacert.org/", "CAcert News"));
148 about.addItem(new SimpleMenuItem("//wiki.cacert.org/", "Wiki Documentation"));
149 putPage(PolicyIndex.DEFAULT_PATH, new PolicyIndex(), "About CAcert.org");
150 about.addItem(new SimpleMenuItem("//wiki.cacert.org/FAQ/Privileges", "Point System"));
151 about.addItem(new SimpleMenuItem("//bugs.cacert.org/", "Bug Database"));
152 about.addItem(new SimpleMenuItem("//wiki.cacert.org/Board", "CAcert Board"));
153 about.addItem(new SimpleMenuItem("//lists.cacert.org/wws", "Mailing Lists"));
154 about.addItem(new SimpleMenuItem("//blog.CAcert.org/feed", "RSS News Feed"));
156 Menu languages = new Menu("Translations");
157 for (Locale l : Language.getSupportedLocales()) {
158 languages.addItem(new SimpleMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
160 categories.add(languages);
161 for (Menu menu : categories) {
163 rootMenu.addItem(menu);
167 firstInstanceInited = true;
172 private void putPage(String path, Page p, String category) {
174 reveresePages.put(p, path);
175 if (category == null) {
178 Menu m = getMenu(category);
179 m.addItem(new PageMenuItem(p));
183 private Menu getMenu(String category) {
185 for (Menu menu : categories) {
186 if (menu.getMenuName().equals(category)) {
192 m = new Menu(category);
198 private static String staticTemplateVarHttp;
200 private static String staticTemplateVarHttps;
202 private static String getStaticTemplateVar(boolean https) {
204 if (staticTemplateVarHttps == null) {
205 staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
207 return staticTemplateVarHttps;
209 if (staticTemplateVarHttp == null) {
210 staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
212 return staticTemplateVarHttp;
217 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
218 boolean isSecure = req.getServerPort() == ServerConstants.getSecurePort();
219 addXSSHeaders(resp, isSecure);
220 // Firefox only sends this, if it's a cross domain access; safari sends
222 String originHeader = req.getHeader("Origin");
223 if (originHeader != null //
225 !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
226 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
227 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
228 resp.setContentType("text/html; charset=utf-8");
229 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>");
232 HttpSession hs = req.getSession();
233 String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
234 if (clientSerial != null) {
235 X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
236 if (cert == null || cert[0] == null || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial)) {
238 resp.sendError(403, "Certificate mismatch.");
243 if (req.getParameter("lang") != null) {
244 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
245 Language lu = Language.getInstance(l);
246 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
248 final Page p = getPage(req.getPathInfo());
251 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
252 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
255 User currentPageUser = LoginPage.getUser(req);
256 if ( !p.isPermitted(currentPageUser)) {
257 if (hs.getAttribute("loggedin") == null) {
258 String request = req.getPathInfo();
259 request = request.split("\\?")[0];
260 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
261 resp.sendRedirect("/login");
267 if (p.beforeTemplate(req, resp)) {
270 HashMap<String, Object> vars = new HashMap<String, Object>();
271 Outputable content = new Outputable() {
274 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
276 if (req.getMethod().equals("POST")) {
277 if (req.getQueryString() != null) {
284 } catch (CSRFException err) {
286 resp.sendError(500, "CSRF invalid");
287 } catch (IOException e) {
290 } catch (IOException e) {
296 vars.put(Menu.USER_VALUE, currentPageUser);
297 vars.put("menu", rootMenu);
298 vars.put("title", Page.getLanguage(req).getTranslation(p.getTitle()));
299 vars.put("static", getStaticTemplateVar(isSecure));
300 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
301 vars.put("content", content);
302 if (currentPageUser != null) {
303 vars.put("loggedInAs", currentPageUser.getName().toString());
305 resp.setContentType("text/html; charset=utf-8");
306 baseTemplate.output(resp.getWriter(), Page.getLanguage(req), vars);
308 resp.sendError(404, "Page not found.");
313 private Page getPage(String pathInfo) {
314 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
315 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
317 Page page = pages.get(pathInfo);
321 page = pages.get(pathInfo + "/*");
325 int idx = pathInfo.lastIndexOf('/');
326 pathInfo = pathInfo.substring(0, idx);
328 page = pages.get(pathInfo + "/*");
336 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
337 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
338 hsr.addHeader("Access-Control-Max-Age", "60");
340 hsr.addHeader("Content-Security-Policy", getHttpsCSP());
342 hsr.addHeader("Content-Security-Policy", getHttpCSP());
344 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
348 private static String httpsCSP = null;
350 private static String httpCSP = null;
352 private static String getHttpsCSP() {
353 if (httpsCSP == null) {
354 StringBuffer csp = new StringBuffer();
355 csp.append("default-src 'none'");
356 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
357 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
358 csp.append(";media-src 'none'; object-src 'none'");
359 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
360 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
361 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
362 csp.append(";report-url https://api.cacert.org/security/csp/report");
363 httpsCSP = csp.toString();
368 private static String getHttpCSP() {
369 if (httpCSP == null) {
370 StringBuffer csp = new StringBuffer();
371 csp.append("default-src 'none'");
372 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
373 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
374 csp.append(";media-src 'none'; object-src 'none'");
375 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
376 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
377 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
378 csp.append(";report-url http://api.cacert.org/security/csp/report");
379 httpCSP = csp.toString();
384 public static String getPathByPage(Page p) {
385 return instance.reveresePages.get(p).replaceFirst("/?\\*$", "");
388 public static void notifyPinger() {
389 instance.pinger.interrupt();