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