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