1 package org.cacert.gigi;
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.security.KeyStore;
6 import java.util.Calendar;
7 import java.util.HashMap;
8 import java.util.LinkedList;
9 import java.util.Locale;
11 import java.util.Properties;
12 import java.util.regex.Pattern;
14 import javax.servlet.ServletException;
15 import javax.servlet.http.HttpServlet;
16 import javax.servlet.http.HttpServletRequest;
17 import javax.servlet.http.HttpServletResponse;
18 import javax.servlet.http.HttpSession;
20 import org.cacert.gigi.database.DatabaseConnection;
21 import org.cacert.gigi.dbObjects.User;
22 import org.cacert.gigi.localisation.Language;
23 import org.cacert.gigi.output.Form.CSRFException;
24 import org.cacert.gigi.output.Menu;
25 import org.cacert.gigi.output.Outputable;
26 import org.cacert.gigi.output.PageMenuItem;
27 import org.cacert.gigi.output.SimpleMenuItem;
28 import org.cacert.gigi.output.template.Template;
29 import org.cacert.gigi.pages.LoginPage;
30 import org.cacert.gigi.pages.LogoutPage;
31 import org.cacert.gigi.pages.MainPage;
32 import org.cacert.gigi.pages.Page;
33 import org.cacert.gigi.pages.PolicyIndex;
34 import org.cacert.gigi.pages.RootCertPage;
35 import org.cacert.gigi.pages.StaticPage;
36 import org.cacert.gigi.pages.TestSecure;
37 import org.cacert.gigi.pages.Verify;
38 import org.cacert.gigi.pages.account.ChangePasswordPage;
39 import org.cacert.gigi.pages.account.MyDetails;
40 import org.cacert.gigi.pages.account.certs.CertificateAdd;
41 import org.cacert.gigi.pages.account.certs.Certificates;
42 import org.cacert.gigi.pages.account.domain.DomainOverview;
43 import org.cacert.gigi.pages.account.mail.MailOverview;
44 import org.cacert.gigi.pages.admin.TTPAdminPage;
45 import org.cacert.gigi.pages.error.PageNotFound;
46 import org.cacert.gigi.pages.main.RegisterPage;
47 import org.cacert.gigi.pages.orga.CreateOrgPage;
48 import org.cacert.gigi.pages.orga.ViewOrgPage;
49 import org.cacert.gigi.pages.wot.AssurePage;
50 import org.cacert.gigi.pages.wot.MyPoints;
51 import org.cacert.gigi.pages.wot.RequestTTPPage;
52 import org.cacert.gigi.ping.PingerDaemon;
53 import org.cacert.gigi.util.ServerConstants;
55 public class Gigi extends HttpServlet {
57 private boolean firstInstanceInited = false;
59 public static final String LOGGEDIN = "loggedin";
61 public static final String USER = "user";
63 private static final long serialVersionUID = -6386785421902852904L;
65 private Template baseTemplate;
67 private LinkedList<Menu> categories = new LinkedList<Menu>();
69 private HashMap<String, Page> pages = new HashMap<String, Page>();
71 private HashMap<Page, String> reveresePages = new HashMap<Page, String>();
73 private Menu rootMenu;
75 private static Gigi instance;
77 private PingerDaemon pinger;
79 private KeyStore truststore;
81 private boolean testing;
83 public Gigi(Properties conf, KeyStore truststore) {
84 if (instance != null) {
85 throw new IllegalStateException("Multiple Gigi instances!");
87 testing = conf.getProperty("testing") != null;
89 DatabaseConnection.init(conf);
90 this.truststore = truststore;
91 pinger = new PingerDaemon(truststore);
96 public void init() throws ServletException {
97 if ( !firstInstanceInited) {
98 putPage("/error", new PageNotFound(), null);
99 putPage("/login", new LoginPage("CAcert - Login"), "CAcert.org");
100 putPage("/", new MainPage("CAcert - Home"), null);
101 putPage("/roots", new RootCertPage(truststore), "CAcert.org");
102 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
103 putPage(LogoutPage.PATH, new LogoutPage("Logout"), "My Account");
104 putPage("/secure", new TestSecure(), null);
105 putPage(Verify.PATH, new Verify(), null);
106 putPage(AssurePage.PATH + "/*", new AssurePage(), "CAcert Web of Trust");
107 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
108 putPage(MyDetails.PATH, new MyDetails(), "My Account");
109 putPage(RegisterPage.PATH, new RegisterPage(), "CAcert.org");
110 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
111 putPage(MailOverview.DEFAULT_PATH, new MailOverview("My email addresses"), "Certificates");
112 putPage(DomainOverview.PATH + "*", new DomainOverview("Domains"), "Certificates");
113 putPage(MyPoints.PATH, new MyPoints("My Points"), "CAcert Web of Trust");
114 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "CAcert Web of Trust");
115 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
116 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Admin");
117 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Admin");
120 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
121 Page p = (Page) manager.getMethod("getInstance").invoke(null);
122 String pa = (String) manager.getField("PATH").get(null);
123 putPage(pa + "/*", p, "Admin");
124 } catch (ReflectiveOperationException e) {
129 putPage("/wot/rules", new StaticPage("CAcert Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "CAcert Web of Trust");
130 baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
131 rootMenu = new Menu("Main");
132 Menu about = new Menu("About CAcert.org");
133 categories.add(about);
135 about.addItem(new SimpleMenuItem("//blog.cacert.org/", "CAcert News"));
136 about.addItem(new SimpleMenuItem("//wiki.cacert.org/", "Wiki Documentation"));
137 putPage(PolicyIndex.DEFAULT_PATH, new PolicyIndex(), "About CAcert.org");
138 about.addItem(new SimpleMenuItem("//wiki.cacert.org/FAQ/Privileges", "Point System"));
139 about.addItem(new SimpleMenuItem("//bugs.cacert.org/", "Bug Database"));
140 about.addItem(new SimpleMenuItem("//wiki.cacert.org/Board", "CAcert Board"));
141 about.addItem(new SimpleMenuItem("//lists.cacert.org/wws", "Mailing Lists"));
142 about.addItem(new SimpleMenuItem("//blog.CAcert.org/feed", "RSS News Feed"));
144 Menu languages = new Menu("Translations");
145 for (Locale l : Language.getSupportedLocales()) {
146 languages.addItem(new SimpleMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
148 categories.add(languages);
149 for (Menu menu : categories) {
151 rootMenu.addItem(menu);
155 firstInstanceInited = true;
160 private void putPage(String path, Page p, String category) {
162 reveresePages.put(p, path);
163 if (category == null) {
167 for (Menu menu : categories) {
168 if (menu.getMenuName().equals(category)) {
174 m = new Menu(category);
177 m.addItem(new PageMenuItem(p));
181 private static String staticTemplateVarHttp;
183 private static String staticTemplateVarHttps;
185 private static String getStaticTemplateVar(boolean https) {
187 if (staticTemplateVarHttps == null) {
188 staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
190 return staticTemplateVarHttps;
192 if (staticTemplateVarHttp == null) {
193 staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
195 return staticTemplateVarHttp;
200 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
201 boolean isSecure = req.getServerPort() == ServerConstants.getSecurePort();
202 addXSSHeaders(resp, isSecure);
203 // Firefox only sends this, if it's a cross domain access; safari sends
205 String originHeader = req.getHeader("Origin");
206 if (originHeader != null //
208 !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
209 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
210 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
211 resp.setContentType("text/html; charset=utf-8");
212 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>");
215 HttpSession hs = req.getSession();
216 if (req.getParameter("lang") != null) {
217 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
218 Language lu = Language.getInstance(l);
219 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
221 final Page p = getPage(req.getPathInfo());
224 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
225 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
228 User currentPageUser = LoginPage.getUser(req);
229 if ( !p.isPermitted(currentPageUser)) {
230 if (hs.getAttribute("loggedin") == null) {
231 String request = req.getPathInfo();
232 request = request.split("\\?")[0];
233 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
234 resp.sendRedirect("/login");
240 if (p.beforeTemplate(req, resp)) {
243 HashMap<String, Object> vars = new HashMap<String, Object>();
244 Outputable content = new Outputable() {
247 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
249 if (req.getMethod().equals("POST")) {
250 if (req.getQueryString() != null) {
257 } catch (CSRFException err) {
259 resp.sendError(500, "CSRF invalid");
260 } catch (IOException e) {
263 } catch (IOException e) {
269 vars.put(Menu.USER_VALUE, currentPageUser);
270 vars.put("menu", rootMenu);
271 vars.put("title", Page.getLanguage(req).getTranslation(p.getTitle()));
272 vars.put("static", getStaticTemplateVar(isSecure));
273 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
274 vars.put("content", content);
275 resp.setContentType("text/html; charset=utf-8");
276 baseTemplate.output(resp.getWriter(), Page.getLanguage(req), vars);
278 resp.sendError(404, "Page not found.");
283 private Page getPage(String pathInfo) {
284 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
285 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
287 Page page = pages.get(pathInfo);
291 page = pages.get(pathInfo + "/*");
295 int idx = pathInfo.lastIndexOf('/');
296 pathInfo = pathInfo.substring(0, idx);
298 page = pages.get(pathInfo + "/*");
306 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
307 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
308 hsr.addHeader("Access-Control-Max-Age", "60");
310 hsr.addHeader("Content-Security-Policy", getHttpsCSP());
312 hsr.addHeader("Content-Security-Policy", getHttpCSP());
314 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
318 private static String httpsCSP = null;
320 private static String httpCSP = null;
322 private static String getHttpsCSP() {
323 if (httpsCSP == null) {
324 StringBuffer csp = new StringBuffer();
325 csp.append("default-src 'none'");
326 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
327 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
328 csp.append(";media-src 'none'; object-src 'none'");
329 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
330 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
331 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
332 csp.append(";report-url https://api.cacert.org/security/csp/report");
333 httpsCSP = csp.toString();
338 private static String getHttpCSP() {
339 if (httpCSP == null) {
340 StringBuffer csp = new StringBuffer();
341 csp.append("default-src 'none'");
342 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
343 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
344 csp.append(";media-src 'none'; object-src 'none'");
345 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
346 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
347 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
348 csp.append(";report-url http://api.cacert.org/security/csp/report");
349 httpCSP = csp.toString();
354 public static String getPathByPage(Page p) {
355 return instance.reveresePages.get(p).replaceFirst("/?\\*$", "");
358 public static void notifyPinger() {
359 instance.pinger.interrupt();