1 package org.cacert.gigi;
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.security.KeyStore;
6 import java.security.cert.X509Certificate;
7 import java.util.Calendar;
8 import java.util.HashMap;
9 import java.util.LinkedList;
10 import java.util.Locale;
12 import java.util.Properties;
13 import java.util.regex.Pattern;
15 import javax.servlet.ServletException;
16 import javax.servlet.http.HttpServlet;
17 import javax.servlet.http.HttpServletRequest;
18 import javax.servlet.http.HttpServletResponse;
19 import javax.servlet.http.HttpSession;
21 import org.cacert.gigi.database.DatabaseConnection;
22 import org.cacert.gigi.dbObjects.User;
23 import org.cacert.gigi.localisation.Language;
24 import org.cacert.gigi.output.Menu;
25 import org.cacert.gigi.output.PageMenuItem;
26 import org.cacert.gigi.output.SimpleMenuItem;
27 import org.cacert.gigi.output.template.Form.CSRFException;
28 import org.cacert.gigi.output.template.Outputable;
29 import org.cacert.gigi.output.template.Template;
30 import org.cacert.gigi.pages.LoginPage;
31 import org.cacert.gigi.pages.LogoutPage;
32 import org.cacert.gigi.pages.MainPage;
33 import org.cacert.gigi.pages.Page;
34 import org.cacert.gigi.pages.PolicyIndex;
35 import org.cacert.gigi.pages.RootCertPage;
36 import org.cacert.gigi.pages.StaticPage;
37 import org.cacert.gigi.pages.TestSecure;
38 import org.cacert.gigi.pages.Verify;
39 import org.cacert.gigi.pages.account.ChangePasswordPage;
40 import org.cacert.gigi.pages.account.MyDetails;
41 import org.cacert.gigi.pages.account.certs.CertificateAdd;
42 import org.cacert.gigi.pages.account.certs.Certificates;
43 import org.cacert.gigi.pages.account.domain.DomainOverview;
44 import org.cacert.gigi.pages.account.mail.MailOverview;
45 import org.cacert.gigi.pages.admin.TTPAdminPage;
46 import org.cacert.gigi.pages.admin.support.FindDomainPage;
47 import org.cacert.gigi.pages.admin.support.FindUserPage;
48 import org.cacert.gigi.pages.admin.support.SupportUserDetailsPage;
49 import org.cacert.gigi.pages.error.AccessDenied;
50 import org.cacert.gigi.pages.error.PageNotFound;
51 import org.cacert.gigi.pages.main.RegisterPage;
52 import org.cacert.gigi.pages.orga.CreateOrgPage;
53 import org.cacert.gigi.pages.orga.ViewOrgPage;
54 import org.cacert.gigi.pages.wot.AssurePage;
55 import org.cacert.gigi.pages.wot.MyPoints;
56 import org.cacert.gigi.pages.wot.RequestTTPPage;
57 import org.cacert.gigi.ping.PingerDaemon;
58 import org.cacert.gigi.util.ServerConstants;
60 public class Gigi extends HttpServlet {
62 private boolean firstInstanceInited = false;
64 public static final String LOGGEDIN = "loggedin";
66 public static final String CERT_SERIAL = "org.cacert.gigi.serial";
68 public static final String CERT_ISSUER = "org.cacert.gigi.issuer";
70 public static final String USER = "user";
72 public static final String LOGIN_METHOD = "org.cacert.gigi.loginMethod";
74 private static final long serialVersionUID = -6386785421902852904L;
76 private Template baseTemplate;
78 private LinkedList<Menu> categories = new LinkedList<Menu>();
80 private HashMap<String, Page> pages = new HashMap<String, Page>();
82 private HashMap<Page, String> reveresePages = new HashMap<Page, String>();
84 private Menu rootMenu;
86 private static Gigi instance;
88 private PingerDaemon pinger;
90 private KeyStore truststore;
92 private boolean testing;
94 public Gigi(Properties conf, KeyStore truststore) {
95 if (instance != null) {
96 throw new IllegalStateException("Multiple Gigi instances!");
98 testing = conf.getProperty("testing") != null;
100 DatabaseConnection.init(conf);
101 this.truststore = truststore;
102 pinger = new PingerDaemon(truststore);
107 public void init() throws ServletException {
108 if ( !firstInstanceInited) {
109 putPage("/denied", new AccessDenied(), null);
110 putPage("/error", new PageNotFound(), null);
111 putPage("/login", new LoginPage("Password Login"), "CAcert.org");
112 getMenu("CAcert.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
115 public boolean isPermitted(User u) {
119 putPage("/", new MainPage("CAcert - Home"), null);
120 putPage("/roots", new RootCertPage(truststore), "CAcert.org");
121 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
122 putPage(LogoutPage.PATH, new LogoutPage("Logout"), "My Account");
123 putPage("/secure", new TestSecure(), null);
124 putPage(Verify.PATH, new Verify(), null);
125 putPage(AssurePage.PATH + "/*", new AssurePage(), "Web of Trust");
126 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
127 putPage(MyDetails.PATH, new MyDetails(), "My Account");
128 putPage(RegisterPage.PATH, new RegisterPage(), "CAcert.org");
129 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
130 putPage(MailOverview.DEFAULT_PATH, new MailOverview("My email addresses"), "Certificates");
131 putPage(DomainOverview.PATH + "*", new DomainOverview("Domains"), "Certificates");
132 putPage(MyPoints.PATH, new MyPoints("My Points"), "Web of Trust");
133 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "Web of Trust");
134 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
135 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
136 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
137 putPage(FindDomainPage.PATH, new FindDomainPage("Find Domain"), "System Admin");
138 putPage(FindUserPage.PATH, new FindUserPage("Find User"), "System Admin");
139 putPage(SupportUserDetailsPage.PATH + "*", new SupportUserDetailsPage("Support: User Details"), null);
142 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
143 Page p = (Page) manager.getMethod("getInstance").invoke(null);
144 String pa = (String) manager.getField("PATH").get(null);
145 putPage(pa + "/*", p, "Gigi test server");
146 } catch (ReflectiveOperationException e) {
151 putPage("/wot/rules", new StaticPage("Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "Web of Trust");
152 baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
153 rootMenu = new Menu("Main");
154 Menu about = new Menu("About CAcert.org");
155 categories.add(about);
157 about.addItem(new SimpleMenuItem("//blog.cacert.org/", "CAcert News"));
158 about.addItem(new SimpleMenuItem("//wiki.cacert.org/", "Wiki Documentation"));
159 putPage(PolicyIndex.DEFAULT_PATH, new PolicyIndex(), "About CAcert.org");
160 about.addItem(new SimpleMenuItem("//wiki.cacert.org/FAQ/Privileges", "Point System"));
161 about.addItem(new SimpleMenuItem("//bugs.cacert.org/", "Bug Database"));
162 about.addItem(new SimpleMenuItem("//wiki.cacert.org/Board", "CAcert Board"));
163 about.addItem(new SimpleMenuItem("//lists.cacert.org/wws", "Mailing Lists"));
164 about.addItem(new SimpleMenuItem("//blog.CAcert.org/feed", "RSS News Feed"));
166 Menu languages = new Menu("Translations");
167 for (Locale l : Language.getSupportedLocales()) {
168 languages.addItem(new SimpleMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
170 categories.add(languages);
171 for (Menu menu : categories) {
173 rootMenu.addItem(menu);
177 firstInstanceInited = true;
182 private void putPage(String path, Page p, String category) {
184 reveresePages.put(p, path);
185 if (category == null) {
188 Menu m = getMenu(category);
189 m.addItem(new PageMenuItem(p));
193 private Menu getMenu(String category) {
195 for (Menu menu : categories) {
196 if (menu.getMenuName().equals(category)) {
202 m = new Menu(category);
208 private static String staticTemplateVarHttp;
210 private static String staticTemplateVarHttps;
212 private static String getStaticTemplateVar(boolean https) {
214 if (staticTemplateVarHttps == null) {
215 staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
217 return staticTemplateVarHttps;
219 if (staticTemplateVarHttp == null) {
220 staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
222 return staticTemplateVarHttp;
227 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
228 boolean isSecure = req.getServerPort() == ServerConstants.getSecurePort();
229 addXSSHeaders(resp, isSecure);
230 // Firefox only sends this, if it's a cross domain access; safari sends
232 String originHeader = req.getHeader("Origin");
233 if (originHeader != null //
235 !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
236 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
237 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
238 resp.setContentType("text/html; charset=utf-8");
239 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>");
242 HttpSession hs = req.getSession();
243 String clientSerial = (String) hs.getAttribute(CERT_SERIAL);
244 if (clientSerial != null) {
245 X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate");
246 if (cert == null || cert[0] == null//
247 || !cert[0].getSerialNumber().toString(16).toUpperCase().equals(clientSerial) //
248 || !cert[0].getIssuerDN().equals(hs.getAttribute(CERT_ISSUER))) {
250 resp.sendError(403, "Certificate mismatch.");
255 if (req.getParameter("lang") != null) {
256 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
257 Language lu = Language.getInstance(l);
258 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
260 final Page p = getPage(req.getPathInfo());
263 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
264 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
267 User currentPageUser = LoginPage.getUser(req);
268 if ( !p.isPermitted(currentPageUser)) {
269 if (hs.getAttribute("loggedin") == null) {
270 String request = req.getPathInfo();
271 request = request.split("\\?")[0];
272 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
273 resp.sendRedirect("/login");
279 if (p.beforeTemplate(req, resp)) {
282 HashMap<String, Object> vars = new HashMap<String, Object>();
283 Outputable content = new Outputable() {
286 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
288 if (req.getMethod().equals("POST")) {
289 if (req.getQueryString() != null) {
296 } catch (CSRFException err) {
298 resp.sendError(500, "CSRF invalid");
299 } catch (IOException e) {
302 } catch (IOException e) {
308 Language lang = Page.getLanguage(req);
310 vars.put(Menu.USER_VALUE, currentPageUser);
311 vars.put("menu", rootMenu);
312 vars.put("title", lang.getTranslation(p.getTitle()));
313 vars.put("static", getStaticTemplateVar(isSecure));
314 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
315 vars.put("content", content);
316 if (currentPageUser != null) {
317 vars.put("loggedInAs", currentPageUser.getName().toString());
318 vars.put("loginMethod", lang.getTranslation((String) req.getSession().getAttribute(LOGIN_METHOD)));
320 resp.setContentType("text/html; charset=utf-8");
321 baseTemplate.output(resp.getWriter(), lang, vars);
323 resp.sendError(404, "Page not found.");
328 private Page getPage(String pathInfo) {
329 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
330 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
332 Page page = pages.get(pathInfo);
336 page = pages.get(pathInfo + "/*");
340 int idx = pathInfo.lastIndexOf('/');
341 pathInfo = pathInfo.substring(0, idx);
343 page = pages.get(pathInfo + "/*");
351 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
352 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
353 hsr.addHeader("Access-Control-Max-Age", "60");
355 hsr.addHeader("Content-Security-Policy", getHttpsCSP());
357 hsr.addHeader("Content-Security-Policy", getHttpCSP());
359 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
363 private static String httpsCSP = null;
365 private static String httpCSP = null;
367 private static String getHttpsCSP() {
368 if (httpsCSP == null) {
369 StringBuffer csp = new StringBuffer();
370 csp.append("default-src 'none'");
371 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
372 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
373 csp.append(";media-src 'none'; object-src 'none'");
374 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
375 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
376 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
377 csp.append(";report-url https://api.cacert.org/security/csp/report");
378 httpsCSP = csp.toString();
383 private static String getHttpCSP() {
384 if (httpCSP == null) {
385 StringBuffer csp = new StringBuffer();
386 csp.append("default-src 'none'");
387 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
388 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
389 csp.append(";media-src 'none'; object-src 'none'");
390 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
391 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
392 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
393 csp.append(";report-url http://api.cacert.org/security/csp/report");
394 httpCSP = csp.toString();
399 public static String getPathByPage(Page p) {
400 return instance.reveresePages.get(p).replaceFirst("/?\\*$", "");
403 public static void notifyPinger() {
404 instance.pinger.interrupt();