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