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