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