ebd6471ffd8934dcba1c1b0218db50ff80da2525
[gigi.git] / src / club / wpia / gigi / Gigi.java
1 package club.wpia.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 club.wpia.gigi.database.DatabaseConnection;
24 import club.wpia.gigi.database.DatabaseConnection.Link;
25 import club.wpia.gigi.dbObjects.CACertificate;
26 import club.wpia.gigi.dbObjects.CATS.CATSType;
27 import club.wpia.gigi.dbObjects.CertificateProfile;
28 import club.wpia.gigi.dbObjects.DomainPingConfiguration;
29 import club.wpia.gigi.localisation.Language;
30 import club.wpia.gigi.output.Menu;
31 import club.wpia.gigi.output.MenuCollector;
32 import club.wpia.gigi.output.PageMenuItem;
33 import club.wpia.gigi.output.SimpleMenuItem;
34 import club.wpia.gigi.output.SimpleUntranslatedMenuItem;
35 import club.wpia.gigi.output.template.Form.CSRFException;
36 import club.wpia.gigi.output.template.Outputable;
37 import club.wpia.gigi.output.template.Template;
38 import club.wpia.gigi.pages.AboutPage;
39 import club.wpia.gigi.pages.HandlesMixedRequest;
40 import club.wpia.gigi.pages.LoginPage;
41 import club.wpia.gigi.pages.LogoutPage;
42 import club.wpia.gigi.pages.MainPage;
43 import club.wpia.gigi.pages.OneFormPage;
44 import club.wpia.gigi.pages.Page;
45 import club.wpia.gigi.pages.PasswordResetPage;
46 import club.wpia.gigi.pages.RootCertPage;
47 import club.wpia.gigi.pages.StaticPage;
48 import club.wpia.gigi.pages.TestSecure;
49 import club.wpia.gigi.pages.Verify;
50 import club.wpia.gigi.pages.account.ChangePasswordPage;
51 import club.wpia.gigi.pages.account.FindAgentAccess;
52 import club.wpia.gigi.pages.account.History;
53 import club.wpia.gigi.pages.account.MyDetails;
54 import club.wpia.gigi.pages.account.UserTrainings;
55 import club.wpia.gigi.pages.account.certs.CertificateAdd;
56 import club.wpia.gigi.pages.account.certs.Certificates;
57 import club.wpia.gigi.pages.account.domain.DomainOverview;
58 import club.wpia.gigi.pages.account.domain.EditDomain;
59 import club.wpia.gigi.pages.account.mail.MailOverview;
60 import club.wpia.gigi.pages.admin.TTPAdminPage;
61 import club.wpia.gigi.pages.admin.support.FindCertPage;
62 import club.wpia.gigi.pages.admin.support.FindUserByDomainPage;
63 import club.wpia.gigi.pages.admin.support.FindUserByEmailPage;
64 import club.wpia.gigi.pages.admin.support.SupportEnterTicketPage;
65 import club.wpia.gigi.pages.admin.support.SupportUserDetailsPage;
66 import club.wpia.gigi.pages.error.AccessDenied;
67 import club.wpia.gigi.pages.error.PageNotFound;
68 import club.wpia.gigi.pages.main.RegisterPage;
69 import club.wpia.gigi.pages.orga.CreateOrgPage;
70 import club.wpia.gigi.pages.orga.ViewOrgPage;
71 import club.wpia.gigi.pages.statistics.StatisticsRoles;
72 import club.wpia.gigi.pages.wot.VerifyPage;
73 import club.wpia.gigi.pages.wot.Points;
74 import club.wpia.gigi.pages.wot.RequestTTPPage;
75 import club.wpia.gigi.ping.PingerDaemon;
76 import club.wpia.gigi.util.AuthorizationContext;
77 import club.wpia.gigi.util.DomainAssessment;
78 import club.wpia.gigi.util.PasswordHash;
79 import club.wpia.gigi.util.ServerConstants;
80 import club.wpia.gigi.util.ServerConstants.Host;
81 import club.wpia.gigi.util.TimeConditions;
82
83 public final class Gigi extends HttpServlet {
84
85     public static final String LINK_HOST = "linkHost";
86
87     private class MenuBuilder {
88
89         private LinkedList<Menu> categories = new LinkedList<Menu>();
90
91         private HashMap<String, Page> pages = new HashMap<String, Page>();
92
93         private MenuCollector rootMenu;
94
95         public MenuBuilder() {}
96
97         private void putPage(String path, Page p, String category) {
98             pages.put(path, p);
99             if (category == null) {
100                 return;
101             }
102             Menu m = getMenu(category);
103             m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
104
105         }
106
107         private Menu getMenu(String category) {
108             Menu m = null;
109             for (Menu menu : categories) {
110                 if (menu.getMenuName().equals(category)) {
111                     m = menu;
112                     break;
113                 }
114             }
115             if (m == null) {
116                 m = new Menu(category);
117                 categories.add(m);
118             }
119             return m;
120         }
121
122         public MenuCollector generateMenu() throws ServletException {
123             putPage("/denied", new AccessDenied(), null);
124             putPage("/error", new PageNotFound(), null);
125             putPage("/login", new LoginPage(), null);
126             getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getHostNamePort(Host.WWW) + "/login", "Password Login") {
127
128                 @Override
129                 public boolean isPermitted(AuthorizationContext ac) {
130                     return ac == null;
131                 }
132             });
133             getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getHostNamePortSecure(Host.SECURE) + "/login", "Certificate Login") {
134
135                 @Override
136                 public boolean isPermitted(AuthorizationContext ac) {
137                     return ac == null;
138                 }
139             });
140             putPage("/", new MainPage(), null);
141             putPage("/roots", new RootCertPage(truststore), "SomeCA.org");
142             putPage(StatisticsRoles.PATH, new StatisticsRoles(), "SomeCA.org");
143             putPage("/about", new AboutPage(), "SomeCA.org");
144
145             putPage("/secure", new TestSecure(), null);
146             putPage(Verify.PATH, new Verify(), null);
147             putPage(Certificates.PATH + "/*", new Certificates(false), "Certificates");
148             putPage(RegisterPage.PATH, new RegisterPage(), "SomeCA.org");
149             putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
150             putPage(MailOverview.DEFAULT_PATH, new MailOverview(), "Certificates");
151             putPage(DomainOverview.PATH, new DomainOverview(), "Certificates");
152             putPage(EditDomain.PATH + "*", new EditDomain(), null);
153
154             putPage(VerifyPage.PATH + "/*", new VerifyPage(), "Web of Trust");
155             putPage(Points.PATH, new Points(false), "Web of Trust");
156             putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
157
158             putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
159             putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
160             putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
161
162             putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "Support Console");
163             putPage(FindUserByEmailPage.PATH, new FindUserByEmailPage(), "Support Console");
164             putPage(FindUserByDomainPage.PATH, new FindUserByDomainPage(), "Support Console");
165             putPage(FindCertPage.PATH, new FindCertPage(), "Support Console");
166
167             putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage(), null);
168             putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
169             putPage(History.PATH, new History(false), "My Account");
170             putPage(FindAgentAccess.PATH, new OneFormPage("Access to Find Agent", FindAgentAccess.class), "My Account");
171             putPage(History.SUPPORT_PATH, new History(true), null);
172             putPage(UserTrainings.PATH, new UserTrainings(false), "My Account");
173             putPage(MyDetails.PATH, new MyDetails(), "My Account");
174             putPage(UserTrainings.SUPPORT_PATH, new UserTrainings(true), null);
175             putPage(Points.SUPPORT_PATH, new Points(true), null);
176             putPage(Certificates.SUPPORT_PATH + "/*", new Certificates(true), null);
177
178             putPage(PasswordResetPage.PATH, new PasswordResetPage(), null);
179             putPage(LogoutPage.PATH, new LogoutPage(), null);
180
181             if (testing) {
182                 try {
183                     Class<?> manager = Class.forName("club.wpia.gigi.pages.Manager");
184                     Page p = (Page) manager.getMethod("getInstance").invoke(null);
185                     String pa = (String) manager.getField("PATH").get(null);
186                     putPage(pa + "/*", p, "Gigi test server");
187                 } catch (ReflectiveOperationException e) {
188                     e.printStackTrace();
189                 }
190             }
191
192             try {
193                 putPage("/wot/rules", new StaticPage("Web of Trust Rules", VerifyPage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
194             } catch (UnsupportedEncodingException e) {
195                 throw new ServletException(e);
196             }
197             rootMenu = new MenuCollector();
198
199             Menu languages = new Menu("Language");
200             addLanguages(languages);
201             categories.add(languages);
202             for (Menu menu : categories) {
203                 menu.prepare();
204                 rootMenu.put(menu);
205             }
206
207             // rootMenu.prepare();
208             return rootMenu;
209         }
210
211         private void addLanguages(Menu languages) {
212             for (Locale l : Language.getSupportedLocales()) {
213                 languages.addItem(new SimpleUntranslatedMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
214             }
215         }
216
217         public Map<String, Page> getPages() {
218             return Collections.unmodifiableMap(pages);
219         }
220     }
221
222     public static final String LOGGEDIN = "loggedin";
223
224     public static final String CERT_SERIAL = "club.wpia.gigi.serial";
225
226     public static final String CERT_ISSUER = "club.wpia.gigi.issuer";
227
228     public static final String AUTH_CONTEXT = "auth";
229
230     public static final String LOGIN_METHOD = "club.wpia.gigi.loginMethod";
231
232     private static final long serialVersionUID = -6386785421902852904L;
233
234     private static Gigi instance;
235
236     private static final Template baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
237
238     private PingerDaemon pinger;
239
240     private KeyStore truststore;
241
242     private boolean testing;
243
244     private MenuCollector rootMenu;
245
246     private Map<String, Page> pages;
247
248     private boolean firstInstanceInited = false;
249
250     public Gigi(Properties conf, KeyStore truststore) {
251         synchronized (Gigi.class) {
252             if (instance != null) {
253                 throw new IllegalStateException("Multiple Gigi instances!");
254             }
255             testing = conf.getProperty("testing") != null;
256             instance = this;
257             DomainAssessment.init(conf);
258             DatabaseConnection.init(conf);
259             TimeConditions.init(conf);
260             PasswordHash.init(conf);
261             this.truststore = truststore;
262             pinger = new PingerDaemon(truststore);
263             pinger.start();
264         }
265     }
266
267     @Override
268     public synchronized void init() throws ServletException {
269         if (firstInstanceInited) {
270             super.init();
271             return;
272         }
273         // ensure those static initializers are finished
274         try (Link l = DatabaseConnection.newLink(false)) {
275             CACertificate.getById(1);
276             CertificateProfile.getById(1);
277             CATSType.AGENT_CHALLENGE.getDisplayName();
278         } catch (InterruptedException e) {
279             throw new Error(e);
280         }
281
282         MenuBuilder mb = new MenuBuilder();
283         rootMenu = mb.generateMenu();
284         pages = mb.getPages();
285
286         firstInstanceInited = true;
287         super.init();
288     }
289
290     private Page getPage(String pathInfo) {
291         if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
292             pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
293         }
294         Page page = pages.get(pathInfo);
295         if (page != null) {
296             return page;
297         }
298         page = pages.get(pathInfo + "/*");
299         if (page != null) {
300             return page;
301         }
302         int idx = pathInfo.lastIndexOf('/');
303         if (idx == -1 || idx == 0) {
304             return null;
305         }
306
307         page = pages.get(pathInfo.substring(0, idx) + "/*");
308         if (page != null) {
309             return page;
310         }
311         int lIdx = pathInfo.lastIndexOf('/', idx - 1);
312         if (lIdx == -1) {
313             return null;
314         }
315         String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
316         page = pages.get(lastResort);
317         return page;
318
319     }
320
321     private static String staticTemplateVar = "//" + ServerConstants.getHostNamePort(Host.STATIC);
322
323     private static String staticTemplateVarSecure = "//" + ServerConstants.getHostNamePortSecure(Host.STATIC);
324
325     @Override
326     protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
327         if ("/error".equals(req.getPathInfo()) || "/denied".equals(req.getPathInfo())) {
328             if (DatabaseConnection.hasInstance()) {
329                 serviceWithConnection(req, resp);
330                 return;
331             }
332         }
333         try (DatabaseConnection.Link l = DatabaseConnection.newLink( !req.getMethod().equals("POST"))) {
334             serviceWithConnection(req, resp);
335         } catch (InterruptedException e) {
336             e.printStackTrace();
337         }
338     }
339
340     protected void serviceWithConnection(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
341         boolean isSecure = req.isSecure();
342         addXSSHeaders(resp, isSecure);
343         // Firefox only sends this, if it's a cross domain access; safari sends
344         // it always
345         String originHeader = req.getHeader("Origin");
346         if (originHeader != null //
347                 && !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getHostNamePortSecure(Host.WWW)) + "(/.*|)") || //
348                         originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getHostNamePort(Host.WWW)) + "(/.*|)") || //
349                         originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getHostNamePortSecure(Host.SECURE)) + "(/.*|)"))) {
350             resp.setContentType("text/html; charset=utf-8");
351             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>");
352             return;
353         }
354         HttpSession hs = req.getSession();
355         String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
356         if (clientSerial != null) {
357             X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
358             if (cert == null || cert[0] == null//
359                     || !cert[0].getSerialNumber().toString(16).toLowerCase().equals(clientSerial) //
360                     || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
361                 hs.invalidate();
362                 resp.sendError(403, "Certificate mismatch.");
363                 return;
364             }
365
366         }
367         if (req.getParameter("lang") != null) {
368             Locale l = Language.getLocaleFromString(req.getParameter("lang"));
369             Language lu = Language.getInstance(l);
370             req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu != null ? lu.getLocale() : Locale.ENGLISH);
371         }
372         final Page p = getPage(req.getPathInfo());
373
374         if (p != null) {
375             if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
376                 resp.sendRedirect("https://" + ServerConstants.getHostNamePortSecure(Host.WWW) + req.getPathInfo());
377                 return;
378             }
379             AuthorizationContext currentAuthContext = LoginPage.getAuthorizationContext(req);
380             if ( !p.isPermitted(currentAuthContext)) {
381                 if (hs.getAttribute("loggedin") == null) {
382                     String request = req.getPathInfo();
383                     request = request.split("\\?")[0];
384                     hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
385                     resp.sendRedirect("/login");
386                     return;
387                 }
388                 resp.sendError(403);
389                 return;
390             }
391             if (p.beforeTemplate(req, resp)) {
392                 return;
393             }
394             HashMap<String, Object> vars = new HashMap<String, Object>();
395             // System.out.println(req.getMethod() + ": " + req.getPathInfo() +
396             // " -> " + p);
397             Outputable content = new Outputable() {
398
399                 @Override
400                 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
401                     try {
402                         if (req.getMethod().equals("POST")) {
403                             if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
404                                 return;
405                             }
406                             p.doPost(req, resp);
407                         } else {
408                             p.doGet(req, resp);
409                         }
410                     } catch (CSRFException err) {
411                         try {
412                             resp.sendError(500, "CSRF invalid");
413                         } catch (IOException e) {
414                             e.printStackTrace();
415                         }
416                     } catch (IOException e) {
417                         e.printStackTrace();
418                     }
419
420                 }
421             };
422             Language lang = Page.getLanguage(req);
423
424             vars.put(Menu.AUTH_VALUE, currentAuthContext);
425             vars.put("menu", rootMenu);
426             vars.put("title", lang.getTranslation(p.getTitle()));
427             vars.put("static", isSecure ? staticTemplateVarSecure : staticTemplateVar);
428             vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
429             vars.put("content", content);
430             if (isSecure) {
431                 req.setAttribute(LINK_HOST, ServerConstants.getHostNamePortSecure(Host.LINK));
432             } else {
433                 req.setAttribute(LINK_HOST, ServerConstants.getHostNamePort(Host.LINK));
434             }
435             if (currentAuthContext != null) {
436                 // TODO maybe move this information into the AuthContext object
437                 vars.put("loginMethod", req.getSession().getAttribute(LOGIN_METHOD));
438                 vars.put("authContext", currentAuthContext);
439
440             }
441             resp.setContentType("text/html; charset=utf-8");
442             baseTemplate.output(resp.getWriter(), lang, vars);
443         } else {
444             resp.sendError(404, "Page not found.");
445         }
446
447     }
448
449     public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
450         hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getHostNamePortSecure(Host.WWW) + " https://" + ServerConstants.getHostNamePortSecure(Host.SECURE));
451         hsr.addHeader("Access-Control-Max-Age", "60");
452         if (doHttps) {
453             hsr.addHeader("Content-Security-Policy", httpsCSP);
454         } else {
455             hsr.addHeader("Content-Security-Policy", httpCSP);
456         }
457         hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
458
459     }
460
461     private static String httpsCSP = genHttpsCSP();
462
463     private static String httpCSP = genHttpCSP();
464
465     private static String genHttpsCSP() {
466         StringBuffer csp = new StringBuffer();
467         csp.append("default-src 'none'");
468         csp.append(";font-src https://" + ServerConstants.getHostNamePortSecure(Host.STATIC));
469         csp.append(";img-src https://" + ServerConstants.getHostNamePortSecure(Host.STATIC));
470         csp.append(";media-src 'none'; object-src 'none'");
471         csp.append(";script-src https://" + ServerConstants.getHostNamePortSecure(Host.STATIC));
472         csp.append(";style-src https://" + ServerConstants.getHostNamePortSecure(Host.STATIC));
473         csp.append(";form-action https://" + ServerConstants.getHostNamePortSecure(Host.SECURE) + " https://" + ServerConstants.getHostNamePortSecure(Host.WWW));
474         // csp.append(";report-url https://api.wpia.club/security/csp/report");
475         return csp.toString();
476     }
477
478     private static String genHttpCSP() {
479         StringBuffer csp = new StringBuffer();
480         csp.append("default-src 'none'");
481         csp.append(";font-src http://" + ServerConstants.getHostNamePort(Host.STATIC));
482         csp.append(";img-src http://" + ServerConstants.getHostNamePort(Host.STATIC));
483         csp.append(";media-src 'none'; object-src 'none'");
484         csp.append(";script-src http://" + ServerConstants.getHostNamePort(Host.STATIC));
485         csp.append(";style-src http://" + ServerConstants.getHostNamePort(Host.STATIC));
486         csp.append(";form-action http://" + ServerConstants.getHostNamePortSecure(Host.SECURE) + " http://" + ServerConstants.getHostNamePort(Host.WWW));
487         // csp.append(";report-url http://api.wpia.club/security/csp/report");
488         return csp.toString();
489     }
490
491     /**
492      * Requests Pinging of domains.
493      * 
494      * @param toReping
495      *            if not null, the {@link DomainPingConfiguration} to test, if
496      *            null, just re-check if there is something to do.
497      */
498     public static void notifyPinger(DomainPingConfiguration toReping) {
499         if (toReping != null) {
500             instance.pinger.queue(toReping);
501         }
502         instance.pinger.interrupt();
503     }
504
505 }