1 package club.wpia.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 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.Points;
73 import club.wpia.gigi.pages.wot.RequestTTPPage;
74 import club.wpia.gigi.pages.wot.VerifyPage;
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;
83 public final class Gigi extends HttpServlet {
85 public static final String LINK_HOST = "linkHost";
87 private class MenuBuilder {
89 private LinkedList<Menu> categories = new LinkedList<Menu>();
91 private HashMap<String, Page> pages = new HashMap<String, Page>();
93 private MenuCollector rootMenu;
95 public MenuBuilder() {}
97 private void putPage(String path, Page p, String category) {
99 if (category == null) {
102 Menu m = getMenu(category);
103 m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
107 private Menu getMenu(String category) {
109 for (Menu menu : categories) {
110 if (menu.getMenuName().equals(category)) {
116 m = new Menu(category);
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") {
129 public boolean isPermitted(AuthorizationContext ac) {
133 getMenu("SomeCA.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getHostNamePortSecure(Host.SECURE) + "/login", "Certificate Login") {
136 public boolean isPermitted(AuthorizationContext ac) {
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");
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);
154 putPage(VerifyPage.PATH + "/*", new VerifyPage(), "Verification");
155 putPage(Points.PATH, new Points(false), "Verification");
156 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Verification");
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");
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");
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);
178 putPage(PasswordResetPage.PATH, new PasswordResetPage(), null);
179 putPage(LogoutPage.PATH, new LogoutPage(), null);
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) {
193 putPage("/wot/rules", new StaticPage("Verification Rules", VerifyPage.class.getResourceAsStream("Rules.templ")), "Verification");
194 } catch (UnsupportedEncodingException e) {
195 throw new ServletException(e);
197 rootMenu = new MenuCollector();
199 Menu languages = new Menu("Language");
200 addLanguages(languages);
201 categories.add(languages);
202 for (Menu menu : categories) {
207 // rootMenu.prepare();
211 private void addLanguages(Menu languages) {
212 for (Locale l : Language.getSupportedLocales()) {
213 languages.addItem(new SimpleUntranslatedMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
217 public Map<String, Page> getPages() {
218 return Collections.unmodifiableMap(pages);
222 public static final String LOGGEDIN = "loggedin";
224 public static final String CERT_SERIAL = "club.wpia.gigi.serial";
226 public static final String CERT_ISSUER = "club.wpia.gigi.issuer";
228 public static final String AUTH_CONTEXT = "auth";
230 public static final String LOGIN_METHOD = "club.wpia.gigi.loginMethod";
232 private static final long serialVersionUID = -6386785421902852904L;
234 private static Gigi instance;
236 private static final Template baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
238 private PingerDaemon pinger;
240 private KeyStore truststore;
242 private boolean testing;
244 private MenuCollector rootMenu;
246 private Map<String, Page> pages;
248 private boolean firstInstanceInited = false;
250 public Gigi(Properties conf, KeyStore truststore) {
251 synchronized (Gigi.class) {
252 if (instance != null) {
253 throw new IllegalStateException("Multiple Gigi instances!");
255 testing = conf.getProperty("testing") != null;
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);
268 public synchronized void init() throws ServletException {
269 if (firstInstanceInited) {
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) {
282 MenuBuilder mb = new MenuBuilder();
283 rootMenu = mb.generateMenu();
284 pages = mb.getPages();
286 firstInstanceInited = true;
290 private Page getPage(String pathInfo) {
291 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
292 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
294 Page page = pages.get(pathInfo);
298 page = pages.get(pathInfo + "/*");
302 int idx = pathInfo.lastIndexOf('/');
303 if (idx == -1 || idx == 0) {
307 page = pages.get(pathInfo.substring(0, idx) + "/*");
311 int lIdx = pathInfo.lastIndexOf('/', idx - 1);
315 String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
316 page = pages.get(lastResort);
321 private static String staticTemplateVar = "//" + ServerConstants.getHostNamePort(Host.STATIC);
323 private static String staticTemplateVarSecure = "//" + ServerConstants.getHostNamePortSecure(Host.STATIC);
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);
333 try (DatabaseConnection.Link l = DatabaseConnection.newLink( !req.getMethod().equals("POST"))) {
334 serviceWithConnection(req, resp);
335 } catch (InterruptedException e) {
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
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>");
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))) {
362 resp.sendError(403, "Certificate mismatch.");
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);
372 final Page p = getPage(req.getPathInfo());
375 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
376 resp.sendRedirect("https://" + ServerConstants.getHostNamePortSecure(Host.WWW) + req.getPathInfo());
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");
391 if (p.beforeTemplate(req, resp)) {
394 HashMap<String, Object> vars = new HashMap<String, Object>();
395 // System.out.println(req.getMethod() + ": " + req.getPathInfo() +
397 Outputable content = new Outputable() {
400 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
402 if (req.getMethod().equals("POST")) {
403 if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
410 } catch (CSRFException err) {
412 resp.sendError(500, "CSRF invalid");
413 } catch (IOException e) {
416 } catch (IOException e) {
422 Language lang = Page.getLanguage(req);
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);
431 req.setAttribute(LINK_HOST, ServerConstants.getHostNamePortSecure(Host.LINK));
433 req.setAttribute(LINK_HOST, ServerConstants.getHostNamePort(Host.LINK));
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);
441 resp.setContentType("text/html; charset=utf-8");
442 baseTemplate.output(resp.getWriter(), lang, vars);
444 resp.sendError(404, "Page not found.");
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");
453 hsr.addHeader("Content-Security-Policy", httpsCSP);
455 hsr.addHeader("Content-Security-Policy", httpCSP);
457 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
461 private static String httpsCSP = genHttpsCSP();
463 private static String httpCSP = genHttpCSP();
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();
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();
492 * Requests Pinging of domains.
495 * if not null, the {@link DomainPingConfiguration} to test, if
496 * null, just re-check if there is something to do.
498 public static void notifyPinger(DomainPingConfiguration toReping) {
499 if (toReping != null) {
500 instance.pinger.queue(toReping);
502 instance.pinger.interrupt();