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