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.AccessDenied;
46 import org.cacert.gigi.pages.error.PageNotFound;
47 import org.cacert.gigi.pages.main.RegisterPage;
48 import org.cacert.gigi.pages.orga.CreateOrgPage;
49 import org.cacert.gigi.pages.orga.ViewOrgPage;
50 import org.cacert.gigi.pages.wot.AssurePage;
51 import org.cacert.gigi.pages.wot.MyPoints;
52 import org.cacert.gigi.pages.wot.RequestTTPPage;
53 import org.cacert.gigi.ping.PingerDaemon;
54 import org.cacert.gigi.util.ServerConstants;
56 public class Gigi extends HttpServlet {
58 private boolean firstInstanceInited = false;
60 public static final String LOGGEDIN = "loggedin";
62 public static final String USER = "user";
64 private static final long serialVersionUID = -6386785421902852904L;
66 private Template baseTemplate;
68 private LinkedList<Menu> categories = new LinkedList<Menu>();
70 private HashMap<String, Page> pages = new HashMap<String, Page>();
72 private HashMap<Page, String> reveresePages = new HashMap<Page, String>();
74 private Menu rootMenu;
76 private static Gigi instance;
78 private PingerDaemon pinger;
80 private KeyStore truststore;
82 private boolean testing;
84 public Gigi(Properties conf, KeyStore truststore) {
85 if (instance != null) {
86 throw new IllegalStateException("Multiple Gigi instances!");
88 testing = conf.getProperty("testing") != null;
90 DatabaseConnection.init(conf);
91 this.truststore = truststore;
92 pinger = new PingerDaemon(truststore);
97 public void init() throws ServletException {
98 if ( !firstInstanceInited) {
99 putPage("/denied", new AccessDenied(), null);
100 putPage("/error", new PageNotFound(), null);
101 putPage("/login", new LoginPage("Password Login"), "CAcert.org");
102 getMenu("CAcert.org").addItem(new SimpleMenuItem("https://" + ServerConstants.getSecureHostNamePort() + "/login", "Certificate Login") {
105 public boolean isPermitted(User u) {
109 putPage("/", new MainPage("CAcert - Home"), null);
110 putPage("/roots", new RootCertPage(truststore), "CAcert.org");
111 putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
112 putPage(LogoutPage.PATH, new LogoutPage("Logout"), "My Account");
113 putPage("/secure", new TestSecure(), null);
114 putPage(Verify.PATH, new Verify(), null);
115 putPage(AssurePage.PATH + "/*", new AssurePage(), "CAcert Web of Trust");
116 putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
117 putPage(MyDetails.PATH, new MyDetails(), "My Account");
118 putPage(RegisterPage.PATH, new RegisterPage(), "CAcert.org");
119 putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
120 putPage(MailOverview.DEFAULT_PATH, new MailOverview("My email addresses"), "Certificates");
121 putPage(DomainOverview.PATH + "*", new DomainOverview("Domains"), "Certificates");
122 putPage(MyPoints.PATH, new MyPoints("My Points"), "CAcert Web of Trust");
123 putPage(RequestTTPPage.PATH, new RequestTTPPage(), "CAcert Web of Trust");
124 putPage(TTPAdminPage.PATH + "/*", new TTPAdminPage(), "Admin");
125 putPage(CreateOrgPage.DEFAULT_PATH, new CreateOrgPage(), "Organisation Admin");
126 putPage(ViewOrgPage.DEFAULT_PATH + "/*", new ViewOrgPage(), "Organisation Admin");
129 Class<?> manager = Class.forName("org.cacert.gigi.pages.Manager");
130 Page p = (Page) manager.getMethod("getInstance").invoke(null);
131 String pa = (String) manager.getField("PATH").get(null);
132 putPage(pa + "/*", p, "Gigi test server");
133 } catch (ReflectiveOperationException e) {
138 putPage("/wot/rules", new StaticPage("CAcert Web of Trust Rules", AssurePage.class.getResourceAsStream("Rules.templ")), "CAcert Web of Trust");
139 baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
140 rootMenu = new Menu("Main");
141 Menu about = new Menu("About CAcert.org");
142 categories.add(about);
144 about.addItem(new SimpleMenuItem("//blog.cacert.org/", "CAcert News"));
145 about.addItem(new SimpleMenuItem("//wiki.cacert.org/", "Wiki Documentation"));
146 putPage(PolicyIndex.DEFAULT_PATH, new PolicyIndex(), "About CAcert.org");
147 about.addItem(new SimpleMenuItem("//wiki.cacert.org/FAQ/Privileges", "Point System"));
148 about.addItem(new SimpleMenuItem("//bugs.cacert.org/", "Bug Database"));
149 about.addItem(new SimpleMenuItem("//wiki.cacert.org/Board", "CAcert Board"));
150 about.addItem(new SimpleMenuItem("//lists.cacert.org/wws", "Mailing Lists"));
151 about.addItem(new SimpleMenuItem("//blog.CAcert.org/feed", "RSS News Feed"));
153 Menu languages = new Menu("Translations");
154 for (Locale l : Language.getSupportedLocales()) {
155 languages.addItem(new SimpleMenuItem("?lang=" + l.toString(), l.getDisplayName(l)));
157 categories.add(languages);
158 for (Menu menu : categories) {
160 rootMenu.addItem(menu);
164 firstInstanceInited = true;
169 private void putPage(String path, Page p, String category) {
171 reveresePages.put(p, path);
172 if (category == null) {
175 Menu m = getMenu(category);
176 m.addItem(new PageMenuItem(p));
180 private Menu getMenu(String category) {
182 for (Menu menu : categories) {
183 if (menu.getMenuName().equals(category)) {
189 m = new Menu(category);
195 private static String staticTemplateVarHttp;
197 private static String staticTemplateVarHttps;
199 private static String getStaticTemplateVar(boolean https) {
201 if (staticTemplateVarHttps == null) {
202 staticTemplateVarHttps = "https://" + ServerConstants.getStaticHostNamePortSecure();
204 return staticTemplateVarHttps;
206 if (staticTemplateVarHttp == null) {
207 staticTemplateVarHttp = "http://" + ServerConstants.getStaticHostNamePort();
209 return staticTemplateVarHttp;
214 protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
215 boolean isSecure = req.getServerPort() == ServerConstants.getSecurePort();
216 addXSSHeaders(resp, isSecure);
217 // Firefox only sends this, if it's a cross domain access; safari sends
219 String originHeader = req.getHeader("Origin");
220 if (originHeader != null //
222 !(originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getWwwHostNamePortSecure()) + "(/.*|)") || //
223 originHeader.matches("^" + Pattern.quote("http://" + ServerConstants.getWwwHostNamePort()) + "(/.*|)") || //
224 originHeader.matches("^" + Pattern.quote("https://" + ServerConstants.getSecureHostNamePort()) + "(/.*|)"))) {
225 resp.setContentType("text/html; charset=utf-8");
226 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>");
229 HttpSession hs = req.getSession();
230 if (req.getParameter("lang") != null) {
231 Locale l = Language.getLocaleFromString(req.getParameter("lang"));
232 Language lu = Language.getInstance(l);
233 req.getSession().setAttribute(Language.SESSION_ATTRIB_NAME, lu.getLocale());
235 final Page p = getPage(req.getPathInfo());
238 if ( !isSecure && (p.needsLogin() || p instanceof LoginPage || p instanceof RegisterPage)) {
239 resp.sendRedirect("https://" + ServerConstants.getWwwHostNamePortSecure() + req.getPathInfo());
242 User currentPageUser = LoginPage.getUser(req);
243 if ( !p.isPermitted(currentPageUser)) {
244 if (hs.getAttribute("loggedin") == null) {
245 String request = req.getPathInfo();
246 request = request.split("\\?")[0];
247 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
248 resp.sendRedirect("/login");
254 if (p.beforeTemplate(req, resp)) {
257 HashMap<String, Object> vars = new HashMap<String, Object>();
258 Outputable content = new Outputable() {
261 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
263 if (req.getMethod().equals("POST")) {
264 if (req.getQueryString() != null) {
271 } catch (CSRFException err) {
273 resp.sendError(500, "CSRF invalid");
274 } catch (IOException e) {
277 } catch (IOException e) {
283 vars.put(Menu.USER_VALUE, currentPageUser);
284 vars.put("menu", rootMenu);
285 vars.put("title", Page.getLanguage(req).getTranslation(p.getTitle()));
286 vars.put("static", getStaticTemplateVar(isSecure));
287 vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
288 vars.put("content", content);
289 if (currentPageUser != null) {
290 vars.put("loggedInAs", currentPageUser.getName().toString());
292 resp.setContentType("text/html; charset=utf-8");
293 baseTemplate.output(resp.getWriter(), Page.getLanguage(req), vars);
295 resp.sendError(404, "Page not found.");
300 private Page getPage(String pathInfo) {
301 if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
302 pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
304 Page page = pages.get(pathInfo);
308 page = pages.get(pathInfo + "/*");
312 int idx = pathInfo.lastIndexOf('/');
313 pathInfo = pathInfo.substring(0, idx);
315 page = pages.get(pathInfo + "/*");
323 public static void addXSSHeaders(HttpServletResponse hsr, boolean doHttps) {
324 hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePortSecure() + " https://" + ServerConstants.getSecureHostNamePort());
325 hsr.addHeader("Access-Control-Max-Age", "60");
327 hsr.addHeader("Content-Security-Policy", getHttpsCSP());
329 hsr.addHeader("Content-Security-Policy", getHttpCSP());
331 hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
335 private static String httpsCSP = null;
337 private static String httpCSP = null;
339 private static String getHttpsCSP() {
340 if (httpsCSP == null) {
341 StringBuffer csp = new StringBuffer();
342 csp.append("default-src 'none'");
343 csp.append(";font-src https://" + ServerConstants.getStaticHostNamePortSecure());
344 csp.append(";img-src https://" + ServerConstants.getStaticHostNamePortSecure());
345 csp.append(";media-src 'none'; object-src 'none'");
346 csp.append(";script-src https://" + ServerConstants.getStaticHostNamePortSecure());
347 csp.append(";style-src https://" + ServerConstants.getStaticHostNamePortSecure());
348 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePortSecure());
349 csp.append(";report-url https://api.cacert.org/security/csp/report");
350 httpsCSP = csp.toString();
355 private static String getHttpCSP() {
356 if (httpCSP == null) {
357 StringBuffer csp = new StringBuffer();
358 csp.append("default-src 'none'");
359 csp.append(";font-src http://" + ServerConstants.getStaticHostNamePort());
360 csp.append(";img-src http://" + ServerConstants.getStaticHostNamePort());
361 csp.append(";media-src 'none'; object-src 'none'");
362 csp.append(";script-src http://" + ServerConstants.getStaticHostNamePort());
363 csp.append(";style-src http://" + ServerConstants.getStaticHostNamePort());
364 csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
365 csp.append(";report-url http://api.cacert.org/security/csp/report");
366 httpCSP = csp.toString();
371 public static String getPathByPage(Page p) {
372 return instance.reveresePages.get(p).replaceFirst("/?\\*$", "");
375 public static void notifyPinger() {
376 instance.pinger.interrupt();