7c720bd712beedd1a13f45ea35e07b13485c37d0
[gigi.git] / src / org / cacert / gigi / Gigi.java
1 package org.cacert.gigi;
2
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;
13 import java.util.Map;
14 import java.util.Properties;
15 import java.util.regex.Pattern;
16
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;
22
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.PasswordResetPage;
40 import org.cacert.gigi.pages.PolicyIndex;
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;
70
71 public final class Gigi extends HttpServlet {
72
73     private class MenuBuilder {
74
75         private LinkedList<Menu> categories = new LinkedList<Menu>();
76
77         private HashMap<String, Page> pages = new HashMap<String, Page>();
78
79         private Menu rootMenu;
80
81         public MenuBuilder() {}
82
83         private void putPage(String path, Page p, String category) {
84             pages.put(path, p);
85             if (category == null) {
86                 return;
87             }
88             Menu m = getMenu(category);
89             m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
90
91         }
92
93         private Menu getMenu(String category) {
94             Menu m = null;
95             for (Menu menu : categories) {
96                 if (menu.getMenuName().equals(category)) {
97                     m = menu;
98                     break;
99                 }
100             }
101             if (m == null) {
102                 m = new Menu(category);
103                 categories.add(m);
104             }
105             return m;
106         }
107
108         public Menu 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("CAcert.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getWwwHostNamePort() + "/login", "Password Login") {
113
114                 @Override
115                 public boolean isPermitted(AuthorizationContext ac) {
116                     return ac == null;
117                 }
118             });
119             getMenu("CAcert.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
120
121                 @Override
122                 public boolean isPermitted(AuthorizationContext ac) {
123                     return ac == null;
124                 }
125             });
126             putPage("/", new MainPage("CAcert - Home"), null);
127             putPage("/roots", new RootCertPage(truststore), "CAcert.org");
128             putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
129             putPage(LogoutPage.PATH, new LogoutPage("Logout"), "My Account");
130             putPage("/secure", new TestSecure(), null);
131             putPage(Verify.PATH, new Verify(), null);
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
139             putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
140             putPage(MyPoints.PATH, new MyPoints("My Points"), "Web of Trust");
141             putPage(MyListingPage.PATH, new MyListingPage(), "Web of Trust");
142             putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
143
144             putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
145             putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
146             putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
147
148             putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "Support Console");
149             putPage(FindUserPage.PATH, new FindUserPage("Find User"), "Support Console");
150             putPage(FindDomainPage.PATH, new FindDomainPage("Find Domain"), "Support Console");
151
152             putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage("Support: User Details"), null);
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(UserTrainings.SUPPORT_PATH, new UserTrainings(true), null);
157
158             putPage(PasswordResetPage.PATH, new PasswordResetPage(), null);
159
160             if (testing) {
161                 try {
162                     Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
163                     Page p = (Page) manager.getMethod("getInstance").invoke(null);
164                     String pa = (String) manager.getField("PATH").get(null);
165                     putPage(pa + "/*", p, "Gigi test server");
166                 } catch (ReflectiveOperationException e) {
167                     e.printStackTrace();
168                 }
169             }
170
171             try {
172                 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
173             } catch (UnsupportedEncodingException e) {
174                 throw new ServletException(e);
175             }
176             baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
177             rootMenu = new Menu("Main");
178             Menu about = new Menu("About CAcert.org");
179             categories.add(about);
180
181             about.addItem(new SimpleMenuItem("//blog.cacert.org/", "CAcert News"));
182             about.addItem(new SimpleMenuItem("//wiki.cacert.org/", "Wiki Documentation"));
183             putPage(PolicyIndex.DEFAULT_PATH, new PolicyIndex(), "About CAcert.org");
184             about.addItem(new SimpleMenuItem("//wiki.cacert.org/FAQ/Privileges", "Point System"));
185             about.addItem(new SimpleMenuItem("//bugs.cacert.org/", "Bug Database"));
186             about.addItem(new SimpleMenuItem("//wiki.cacert.org/Board", "CAcert Board"));
187             about.addItem(new SimpleMenuItem("//lists.cacert.org/wws", "Mailing Lists"));
188             about.addItem(new SimpleMenuItem("//blog.CAcert.org/feed", "RSS News Feed"));
189             about.addItem(new SimpleMenuItem("//wiki.cacert.org/Impress", "Impress"));
190
191             Menu languages = new Menu("Translations");
192             for (Locale l : Language.getSupportedLocales()) {
193                 languages.addItem(new SimpleMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
194             }
195             categories.add(languages);
196             for (Menu menu : categories) {
197                 menu.prepare();
198                 rootMenu.addItem(menu);
199             }
200
201             rootMenu.prepare();
202             return rootMenu;
203         }
204
205         public Map<String, Page> getPages() {
206             return Collections.unmodifiableMap(pages);
207         }
208     }
209
210     public static final String LOGGEDIN = "loggedin";
211
212     public static final String CERT_SERIAL = "org.cacert.gigi.serial";
213
214     public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
215
216     public static final String AUTH_CONTEXT = "auth";
217
218     public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
219
220     private static final long serialVersionUID = -6386785421902852904L;
221
222     private static Gigi instance;
223
224     private Template baseTemplate;
225
226     private PingerDaemon pinger;
227
228     private KeyStore truststore;
229
230     private boolean testing;
231
232     private Menu rootMenu;
233
234     private Map<String, Page> pages;
235
236     private boolean firstInstanceInited = false;
237
238     public Gigi(Properties conf, KeyStore truststore) {
239         synchronized (Gigi.class) {
240             if (instance != null) {
241                 throw new IllegalStateException("Multiple Gigi instances!");
242             }
243             testing = conf.getProperty("testing") != null;
244             instance = this;
245             DatabaseConnection.init(conf);
246             this.truststore = truststore;
247             pinger = new PingerDaemon(truststore);
248             pinger.start();
249         }
250     }
251
252     @Override
253     public synchronized void init() throws ServletException {
254         if (firstInstanceInited) {
255             super.init();
256             return;
257         }
258         // ensure those static initializers are finished
259         CACertificate.getById(1);
260         CertificateProfile.getById(1);
261
262         MenuBuilder mb = new MenuBuilder();
263         rootMenu = mb.generateMenu();
264         pages = mb.getPages();
265
266         firstInstanceInited = true;
267         super.init();
268     }
269
270     private Page getPage(String pathInfo) {
271         if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
272             pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
273         }
274         Page page = pages.get(pathInfo);
275         if (page != null) {
276             return page;
277         }
278         page = pages.get(pathInfo + "/*");
279         if (page != null) {
280             return page;
281         }
282         int idx = pathInfo.lastIndexOf('/');
283         if (idx == -1 || idx == 0) {
284             return null;
285         }
286
287         page = pages.get(pathInfo.substring(0, idx) + "/*");
288         if (page != null) {
289             return page;
290         }
291         int lIdx = pathInfo.lastIndexOf('/', idx - 1);
292         if (lIdx == -1) {
293             return null;
294         }
295         String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
296         page = pages.get(lastResort);
297         return page;
298
299     }
300
301     private static String staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
302
303     private static String staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
304
305     private static String getStaticTemplateVar(boolean https) {
306         if (https) {
307             return staticTemplateVarHttps;
308         } else {
309             return staticTemplateVarHttp;
310         }
311     }
312
313     @Override
314     protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
315         boolean isSecure = req.isSecure();
316         addXSSHeaders(resp, isSecure);
317         // Firefox only sends this, if it's a cross domain access; safari sends
318         // it always
319         String originHeader = req.getHeader("Origin");
320         if (originHeader != null //
321                 &&
322                 !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
323                         originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
324                 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
325             resp.setContentType("text/html; charset=utf-8");
326             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>");
327             return;
328         }
329         HttpSession hs = req.getSession();
330         String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
331         if (clientSerial != null) {
332             X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
333             if (cert == null || cert[0] == null//
334                     || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial) //
335                     || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
336                 hs.invalidate();
337                 resp.sendError(403, "Certificate mismatch.");
338                 return;
339             }
340
341         }
342         if (req.getParameter("lang") != null) {
343             Locale l = Language.getLocaleFromString(req.getParameter("lang"));
344             Language lu = Language.getInstance(l);
345             req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
346         }
347         final Page p = getPage(req.getPathInfo());
348
349         if (p != null) {
350             if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
351                 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
352                 return;
353             }
354             AuthorizationContext currentAuthContext = LoginPage.getAuthorizationContext(req);
355             if ( !p.isPermitted(currentAuthContext)) {
356                 if (hs.getAttribute("loggedin") == null) {
357                     String request = req.getPathInfo();
358                     request = request.split("\\?")[0];
359                     hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
360                     resp.sendRedirect("/login");
361                     return;
362                 }
363                 resp.sendError(403);
364                 return;
365             }
366             if (p.beforeTemplate(req, resp)) {
367                 return;
368             }
369             HashMap<String, Object> vars = new HashMap<String, Object>();
370             // System.out.println(req.getMethod() + ": " + req.getPathInfo() +
371             // " -> " + p);
372             Outputable content = new Outputable() {
373
374                 @Override
375                 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
376                     try {
377                         if (req.getMethod().equals("POST")) {
378                             if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
379                                 return;
380                             }
381                             p.doPost(req, resp);
382                         } else {
383                             p.doGet(req, resp);
384                         }
385                     } catch (CSRFException err) {
386                         try {
387                             resp.sendError(500, "CSRF invalid");
388                         } catch (IOException e) {
389                             e.printStackTrace();
390                         }
391                     } catch (IOException e) {
392                         e.printStackTrace();
393                     }
394
395                 }
396             };
397             Language lang = Page.getLanguage(req);
398
399             vars.put(Menu.AUTH_VALUE, currentAuthContext);
400             vars.put("menu", rootMenu);
401             vars.put("title", lang.getTranslation(p.getTitle()));
402             vars.put("static", getStaticTemplateVar(isSecure));
403             vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
404             vars.put("content", content);
405             if (currentAuthContext != null) {
406                 // TODO maybe move this information into the AuthContext object
407                 vars.put("loginMethod", lang.getTranslation((String) req.getSession().getAttribute(LOGIN_METHOD)));
408                 vars.put("authContext", currentAuthContext);
409
410             }
411             resp.setContentType("text/html; charset=utf-8");
412             baseTemplate.output(resp.getWriter(), lang, vars);
413         } else {
414             resp.sendError(404, "Page not found.");
415         }
416
417     }
418
419     public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
420         hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
421         hsr.addHeader("Access-Control-Max-Age", "60");
422         if (doHttps) {
423             hsr.addHeader("Content-Security-Policy", httpsCSP);
424         } else {
425             hsr.addHeader("Content-Security-Policy", httpCSP);
426         }
427         hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
428
429     }
430
431     private static String httpsCSP = genHttpsCSP();
432
433     private static String httpCSP = genHttpCSP();
434
435     private static String genHttpsCSP() {
436         StringBuffer csp = new StringBuffer();
437         csp.append("default-src 'none'");
438         csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
439         csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
440         csp.append(";media-src 'none'; object-src 'none'");
441         csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
442         csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
443         csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
444         csp.append(";report-url https://api.cacert.org/security/csp/report");
445         return csp.toString();
446     }
447
448     private static String genHttpCSP() {
449         StringBuffer csp = new StringBuffer();
450         csp.append("default-src 'none'");
451         csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
452         csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
453         csp.append(";media-src 'none'; object-src 'none'");
454         csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
455         csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
456         csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
457         csp.append(";report-url http://api.cacert.org/security/csp/report");
458         return csp.toString();
459     }
460
461     /**
462      * Requests Pinging of domains.
463      * 
464      * @param toReping
465      *            if not null, the {@link DomainPingConfiguration} to test, if
466      *            null, just re-check if there is something to do.
467      */
468     public static void notifyPinger(DomainPingConfiguration toReping) {
469         if (toReping != null) {
470             instance.pinger.queue(toReping);
471         }
472         instance.pinger.interrupt();
473     }
474
475 }