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