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