ADD: First attempt for a redesign
[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.dbObjects.CACertificate;
25 import org.cacert.gigi.dbObjects.CertificateProfile;
26 import org.cacert.gigi.dbObjects.DomainPingConfiguration;
27 import org.cacert.gigi.localisation.Language;
28 import org.cacert.gigi.output.Menu;
29 import org.cacert.gigi.output.MenuCollector;
30 import org.cacert.gigi.output.PageMenuItem;
31 import org.cacert.gigi.output.SimpleMenuItem;
32 import org.cacert.gigi.output.template.Form.CSRFException;
33 import org.cacert.gigi.output.template.Outputable;
34 import org.cacert.gigi.output.template.Template;
35 import org.cacert.gigi.pages.HandlesMixedRequest;
36 import org.cacert.gigi.pages.LoginPage;
37 import org.cacert.gigi.pages.LogoutPage;
38 import org.cacert.gigi.pages.MainPage;
39 import org.cacert.gigi.pages.Page;
40 import org.cacert.gigi.pages.PasswordResetPage;
41 import org.cacert.gigi.pages.PolicyIndex;
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("Password Login"), null);
113             getMenu("CAcert.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("CAcert.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("CAcert - Home"), null);
128             putPage("/roots", new RootCertPage(truststore), "CAcert.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(), "CAcert.org");
134             putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
135             putPage(MailOverview.DEFAULT_PATH, new MailOverview("Email addresses"), "Certificates");
136             putPage(DomainOverview.PATH + "*", new DomainOverview("Domains"), "Certificates");
137
138             putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
139             putPage(MyPoints.PATH, new MyPoints("My Points"), "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("Find User"), "Support Console");
149             putPage(FindDomainPage.PATH, new FindDomainPage("Find Domain"), "Support Console");
150
151             putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage("Support: User Details"), null);
152             putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
153             putPage(LogoutPage.PATH, new LogoutPage("Logout"), "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             Menu about = new Menu("About CAcert.org");
181             categories.add(about);
182
183             about.addItem(new SimpleMenuItem("//blog.cacert.org/", "CAcert News"));
184             about.addItem(new SimpleMenuItem("//wiki.cacert.org/", "Wiki Documentation"));
185             putPage(PolicyIndex.DEFAULT_PATH, new PolicyIndex(), "About CAcert.org");
186             about.addItem(new SimpleMenuItem("//wiki.cacert.org/FAQ/Privileges", "Point System"));
187             about.addItem(new SimpleMenuItem("//bugs.cacert.org/", "Bug Database"));
188             about.addItem(new SimpleMenuItem("//wiki.cacert.org/Board", "CAcert Board"));
189             about.addItem(new SimpleMenuItem("//lists.cacert.org/wws", "Mailing Lists"));
190             about.addItem(new SimpleMenuItem("//blog.CAcert.org/feed", "RSS News Feed"));
191             about.addItem(new SimpleMenuItem("//wiki.cacert.org/Impress", "Impress"));
192
193             Menu languages = new Menu("Translations");
194             for (Locale l : Language.getSupportedLocales()) {
195                 languages.addItem(new SimpleMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
196             }
197             categories.add(languages);
198             for (Menu menu : categories) {
199                 menu.prepare();
200                 rootMenu.put(menu);
201             }
202
203             // rootMenu.prepare();
204             return rootMenu;
205         }
206
207         public Map<String, Page> getPages() {
208             return Collections.unmodifiableMap(pages);
209         }
210     }
211
212     public static final String LOGGEDIN = "loggedin";
213
214     public static final String CERT_SERIAL = "org.cacert.gigi.serial";
215
216     public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
217
218     public static final String AUTH_CONTEXT = "auth";
219
220     public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
221
222     private static final long serialVersionUID = -6386785421902852904L;
223
224     private static Gigi instance;
225
226     private Template baseTemplate;
227
228     private PingerDaemon pinger;
229
230     private KeyStore truststore;
231
232     private boolean testing;
233
234     private MenuCollector rootMenu;
235
236     private Map<String, Page> pages;
237
238     private boolean firstInstanceInited = false;
239
240     public Gigi(Properties conf, KeyStore truststore) {
241         synchronized (Gigi.class) {
242             if (instance != null) {
243                 throw new IllegalStateException("Multiple Gigi instances!");
244             }
245             testing = conf.getProperty("testing") != null;
246             instance = this;
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         CACertificate.getById(1);
262         CertificateProfile.getById(1);
263
264         MenuBuilder mb = new MenuBuilder();
265         rootMenu = mb.generateMenu();
266         pages = mb.getPages();
267
268         firstInstanceInited = true;
269         super.init();
270     }
271
272     private Page getPage(String pathInfo) {
273         if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
274             pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
275         }
276         Page page = pages.get(pathInfo);
277         if (page != null) {
278             return page;
279         }
280         page = pages.get(pathInfo + "/*");
281         if (page != null) {
282             return page;
283         }
284         int idx = pathInfo.lastIndexOf('/');
285         if (idx == -1 || idx == 0) {
286             return null;
287         }
288
289         page = pages.get(pathInfo.substring(0, idx) + "/*");
290         if (page != null) {
291             return page;
292         }
293         int lIdx = pathInfo.lastIndexOf('/', idx - 1);
294         if (lIdx == -1) {
295             return null;
296         }
297         String lastResort = pathInfo.substring(0, lIdx) + "/*" + pathInfo.substring(idx);
298         page = pages.get(lastResort);
299         return page;
300
301     }
302
303     private static String staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
304
305     private static String staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
306
307     private static String getStaticTemplateVar(boolean https) {
308         if (https) {
309             return staticTemplateVarHttps;
310         } else {
311             return staticTemplateVarHttp;
312         }
313     }
314
315     @Override
316     protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
317         boolean isSecure = req.isSecure();
318         addXSSHeaders(resp, isSecure);
319         // Firefox only sends this, if it's a cross domain access; safari sends
320         // it always
321         String originHeader = req.getHeader("Origin");
322         if (originHeader != null //
323                 &&
324                 !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
325                         originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
326                 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
327             resp.setContentType("text/html; charset=utf-8");
328             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>");
329             return;
330         }
331         HttpSession hs = req.getSession();
332         String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
333         if (clientSerial != null) {
334             X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
335             if (cert == null || cert[0] == null//
336                     || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial) //
337                     || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
338                 hs.invalidate();
339                 resp.sendError(403, "Certificate mismatch.");
340                 return;
341             }
342
343         }
344         if (req.getParameter("lang") != null) {
345             Locale l = Language.getLocaleFromString(req.getParameter("lang"));
346             Language lu = Language.getInstance(l);
347             req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
348         }
349         final Page p = getPage(req.getPathInfo());
350
351         if (p != null) {
352             if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
353                 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
354                 return;
355             }
356             AuthorizationContext currentAuthContext = LoginPage.getAuthorizationContext(req);
357             if ( !p.isPermitted(currentAuthContext)) {
358                 if (hs.getAttribute("loggedin") == null) {
359                     String request = req.getPathInfo();
360                     request = request.split("\\?")[0];
361                     hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
362                     resp.sendRedirect("/login");
363                     return;
364                 }
365                 resp.sendError(403);
366                 return;
367             }
368             if (p.beforeTemplate(req, resp)) {
369                 return;
370             }
371             HashMap<String, Object> vars = new HashMap<String, Object>();
372             // System.out.println(req.getMethod() + ": " + req.getPathInfo() +
373             // " -> " + p);
374             Outputable content = new Outputable() {
375
376                 @Override
377                 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
378                     try {
379                         if (req.getMethod().equals("POST")) {
380                             if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
381                                 return;
382                             }
383                             p.doPost(req, resp);
384                         } else {
385                             p.doGet(req, resp);
386                         }
387                     } catch (CSRFException err) {
388                         try {
389                             resp.sendError(500, "CSRF invalid");
390                         } catch (IOException e) {
391                             e.printStackTrace();
392                         }
393                     } catch (IOException e) {
394                         e.printStackTrace();
395                     }
396
397                 }
398             };
399             Language lang = Page.getLanguage(req);
400
401             vars.put(Menu.AUTH_VALUE, currentAuthContext);
402             vars.put("menu", rootMenu);
403             vars.put("title", lang.getTranslation(p.getTitle()));
404             vars.put("static", getStaticTemplateVar(isSecure));
405             vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
406             vars.put("content", content);
407             if (currentAuthContext != null) {
408                 // TODO maybe move this information into the AuthContext object
409                 vars.put("loginMethod", lang.getTranslation((String) req.getSession().getAttribute(LOGIN_METHOD)));
410                 vars.put("authContext", currentAuthContext);
411
412             }
413             resp.setContentType("text/html; charset=utf-8");
414             baseTemplate.output(resp.getWriter(), lang, vars);
415         } else {
416             resp.sendError(404, "Page not found.");
417         }
418
419     }
420
421     public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
422         hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
423         hsr.addHeader("Access-Control-Max-Age", "60");
424         if (doHttps) {
425             hsr.addHeader("Content-Security-Policy", httpsCSP);
426         } else {
427             hsr.addHeader("Content-Security-Policy", httpCSP);
428         }
429         hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
430
431     }
432
433     private static String httpsCSP = genHttpsCSP();
434
435     private static String httpCSP = genHttpCSP();
436
437     private static String genHttpsCSP() {
438         StringBuffer csp = new StringBuffer();
439         csp.append("default-src 'none'");
440         csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
441         csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
442         csp.append(";media-src 'none'; object-src 'none'");
443         csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
444         csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
445         csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
446         csp.append(";report-url https://api.cacert.org/security/csp/report");
447         return csp.toString();
448     }
449
450     private static String genHttpCSP() {
451         StringBuffer csp = new StringBuffer();
452         csp.append("default-src 'none'");
453         csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
454         csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
455         csp.append(";media-src 'none'; object-src 'none'");
456         csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
457         csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
458         csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
459         csp.append(";report-url http://api.cacert.org/security/csp/report");
460         return csp.toString();
461     }
462
463     /**
464      * Requests Pinging of domains.
465      * 
466      * @param toReping
467      *            if not null, the {@link DomainPingConfiguration} to test, if
468      *            null, just re-check if there is something to do.
469      */
470     public static void notifyPinger(DomainPingConfiguration toReping) {
471         if (toReping != null) {
472             instance.pinger.queue(toReping);
473         }
474         instance.pinger.interrupt();
475     }
476
477 }