]> WPIA git - gigi.git/blob - src/org/cacert/gigi/Gigi.java
add: show support and user the account history and the trainings.
[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.MyPoints;
64 import org.cacert.gigi.pages.wot.RequestTTPPage;
65 import org.cacert.gigi.ping.PingerDaemon;
66 import org.cacert.gigi.util.AuthorizationContext;
67 import org.cacert.gigi.util.ServerConstants;
68
69 public class Gigi extends HttpServlet {
70
71     private class MenuBuilder {
72
73         private LinkedList<Menu> categories = new LinkedList<Menu>();
74
75         private HashMap<String, Page> pages = new HashMap<String, Page>();
76
77         private Menu rootMenu;
78
79         public MenuBuilder() {}
80
81         private void putPage(String path, Page p, String category) {
82             pages.put(path, p);
83             if (category == null) {
84                 return;
85             }
86             Menu m = getMenu(category);
87             m.addItem(new PageMenuItem(p, path.replaceFirst("/?\\*$", "")));
88
89         }
90
91         private Menu getMenu(String category) {
92             Menu m = null;
93             for (Menu menu : categories) {
94                 if (menu.getMenuName().equals(category)) {
95                     m = menu;
96                     break;
97                 }
98             }
99             if (m == null) {
100                 m = new Menu(category);
101                 categories.add(m);
102             }
103             return m;
104         }
105
106         public Menu generateMenu() throws ServletException {
107             putPage("/denied", new AccessDenied(), null);
108             putPage("/error", new PageNotFound(), null);
109             putPage("/login", new LoginPage("Password Login"), null);
110             getMenu("CAcert.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getWwwHostNamePort() + "/login", "Password Login") {
111
112                 @Override
113                 public boolean isPermitted(AuthorizationContext ac) {
114                     return ac == null;
115                 }
116             });
117             getMenu("CAcert.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
118
119                 @Override
120                 public boolean isPermitted(AuthorizationContext ac) {
121                     return ac == null;
122                 }
123             });
124             putPage("/", new MainPage("CAcert - Home"), null);
125             putPage("/roots", new RootCertPage(truststore), "CAcert.org");
126             putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
127             putPage(LogoutPage.PATH, new LogoutPage("Logout"), "My Account");
128             putPage("/secure", new TestSecure(), null);
129             putPage(Verify.PATH, new Verify(), null);
130             putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
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("My email addresses"), "Certificates");
136             putPage(DomainOverview.PATH + "*", new DomainOverview("Domains"), "Certificates");
137             putPage(MyPoints.PATH, new MyPoints("My Points"), "Web of Trust");
138             putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
139             putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
140             putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
141             putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
142             putPage(FindUserPage.PATH, new FindUserPage("Find User"), "System Admin");
143             putPage(FindDomainPage.PATH, new FindDomainPage("Find Domain"), "System Admin");
144             putPage(SupportEnterTicketPage.PATH, new SupportEnterTicketPage(), "System Admin");
145             putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage("Support: User Details"), null);
146             putPage(UserHistory.PATH, new UserHistory(false), "My Account");
147             putPage(UserHistory.SUPPORT_PATH, new UserHistory(true), null);
148             putPage(UserTrainings.PATH, new UserTrainings(false), "My Account");
149             putPage(UserTrainings.SUPPORT_PATH, new UserTrainings(true), null);
150             if (testing) {
151                 try {
152                     Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
153                     Page p = (Page) manager.getMethod("getInstance").invoke(null);
154                     String pa = (String) manager.getField("PATH").get(null);
155                     putPage(pa + "/*", p, "Gigi test server");
156                 } catch (ReflectiveOperationException e) {
157                     e.printStackTrace();
158                 }
159             }
160
161             try {
162                 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
163             } catch (UnsupportedEncodingException e) {
164                 throw new ServletException(e);
165             }
166             baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
167             rootMenu = new Menu("Main");
168             Menu about = new Menu("About CAcert.org");
169             categories.add(about);
170
171             about.addItem(new SimpleMenuItem("//blog.cacert.org/", "CAcert News"));
172             about.addItem(new SimpleMenuItem("//wiki.cacert.org/", "Wiki Documentation"));
173             putPage(PolicyIndex.DEFAULT_PATH, new PolicyIndex(), "About CAcert.org");
174             about.addItem(new SimpleMenuItem("//wiki.cacert.org/FAQ/Privileges", "Point System"));
175             about.addItem(new SimpleMenuItem("//bugs.cacert.org/", "Bug Database"));
176             about.addItem(new SimpleMenuItem("//wiki.cacert.org/Board", "CAcert Board"));
177             about.addItem(new SimpleMenuItem("//lists.cacert.org/wws", "Mailing Lists"));
178             about.addItem(new SimpleMenuItem("//blog.CAcert.org/feed", "RSS News Feed"));
179
180             Menu languages = new Menu("Translations");
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.addItem(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 Menu 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             Outputable content = new Outputable() {
360
361                 @Override
362                 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
363                     try {
364                         if (req.getMethod().equals("POST")) {
365                             if (req.getQueryString() != null && !(p instanceof HandlesMixedRequest)) {
366                                 return;
367                             }
368                             p.doPost(req, resp);
369                         } else {
370                             p.doGet(req, resp);
371                         }
372                     } catch (CSRFException err) {
373                         try {
374                             resp.sendError(500, "CSRF invalid");
375                         } catch (IOException e) {
376                             e.printStackTrace();
377                         }
378                     } catch (IOException e) {
379                         e.printStackTrace();
380                     }
381
382                 }
383             };
384             Language lang = Page.getLanguage(req);
385
386             vars.put(Menu.AUTH_VALUE, currentAuthContext);
387             vars.put("menu", rootMenu);
388             vars.put("title", lang.getTranslation(p.getTitle()));
389             vars.put("static", getStaticTemplateVar(isSecure));
390             vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
391             vars.put("content", content);
392             if (currentAuthContext != null) {
393                 // TODO maybe move this information into the AuthContext object
394                 vars.put("loginMethod", lang.getTranslation((String) req.getSession().getAttribute(LOGIN_METHOD)));
395                 vars.put("authContext", currentAuthContext);
396
397             }
398             resp.setContentType("text/html; charset=utf-8");
399             baseTemplate.output(resp.getWriter(), lang, vars);
400         } else {
401             resp.sendError(404, "Page not found.");
402         }
403
404     }
405
406     public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
407         hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
408         hsr.addHeader("Access-Control-Max-Age", "60");
409         if (doHttps) {
410             hsr.addHeader("Content-Security-Policy", httpsCSP);
411         } else {
412             hsr.addHeader("Content-Security-Policy", httpCSP);
413         }
414         hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
415
416     }
417
418     private static String httpsCSP = genHttpsCSP();
419
420     private static String httpCSP = genHttpCSP();
421
422     private static String genHttpsCSP() {
423         StringBuffer csp = new StringBuffer();
424         csp.append("default-src 'none'");
425         csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
426         csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
427         csp.append(";media-src 'none'; object-src 'none'");
428         csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
429         csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
430         csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
431         csp.append(";report-url https://api.cacert.org/security/csp/report");
432         return csp.toString();
433     }
434
435     private static String genHttpCSP() {
436         StringBuffer csp = new StringBuffer();
437         csp.append("default-src 'none'");
438         csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
439         csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
440         csp.append(";media-src 'none'; object-src 'none'");
441         csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
442         csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
443         csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
444         csp.append(";report-url http://api.cacert.org/security/csp/report");
445         return csp.toString();
446     }
447
448     /**
449      * Requests Pinging of domains.
450      * 
451      * @param toReping
452      *            if not null, the {@link DomainPingConfiguration} to test, if
453      *            null, just re-check if there is something to do.
454      */
455     public static void notifyPinger(DomainPingConfiguration toReping) {
456         if (toReping != null) {
457             instance.pinger.queue(toReping);
458         }
459         instance.pinger.interrupt();
460     }
461
462 }