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