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