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