]> WPIA git - gigi.git/blob - src/org/cacert/gigi/Launcher.java
Fix: enforce client auth on "secure"-subhost
[gigi.git] / src / org / cacert / gigi / Launcher.java
1 package org.cacert.gigi;
2
3 import java.io.IOException;
4 import java.security.GeneralSecurityException;
5 import java.security.Key;
6 import java.security.KeyStore;
7 import java.security.KeyStoreException;
8 import java.security.NoSuchAlgorithmException;
9 import java.security.UnrecoverableKeyException;
10 import java.security.cert.Certificate;
11 import java.util.List;
12 import java.util.Locale;
13 import java.util.Properties;
14 import java.util.TimeZone;
15
16 import javax.net.ssl.ExtendedSSLSession;
17 import javax.net.ssl.SNIHostName;
18 import javax.net.ssl.SNIServerName;
19 import javax.net.ssl.SSLEngine;
20 import javax.net.ssl.SSLParameters;
21 import javax.net.ssl.SSLSession;
22 import javax.servlet.http.HttpServletResponse;
23
24 import org.cacert.gigi.api.GigiAPI;
25 import org.cacert.gigi.email.EmailProvider;
26 import org.cacert.gigi.natives.SetUID;
27 import org.cacert.gigi.util.CipherInfo;
28 import org.cacert.gigi.util.ServerConstants;
29 import org.eclipse.jetty.http.HttpHeader;
30 import org.eclipse.jetty.http.HttpVersion;
31 import org.eclipse.jetty.server.Connector;
32 import org.eclipse.jetty.server.Handler;
33 import org.eclipse.jetty.server.HttpConfiguration;
34 import org.eclipse.jetty.server.HttpConnectionFactory;
35 import org.eclipse.jetty.server.SecureRequestCustomizer;
36 import org.eclipse.jetty.server.Server;
37 import org.eclipse.jetty.server.ServerConnector;
38 import org.eclipse.jetty.server.SessionManager;
39 import org.eclipse.jetty.server.SslConnectionFactory;
40 import org.eclipse.jetty.server.handler.ContextHandler;
41 import org.eclipse.jetty.server.handler.HandlerList;
42 import org.eclipse.jetty.server.handler.HandlerWrapper;
43 import org.eclipse.jetty.server.handler.ResourceHandler;
44 import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
45 import org.eclipse.jetty.servlet.ServletContextHandler;
46 import org.eclipse.jetty.servlet.ServletHolder;
47 import org.eclipse.jetty.util.log.Log;
48 import org.eclipse.jetty.util.resource.Resource;
49 import org.eclipse.jetty.util.ssl.SslContextFactory;
50
51 public class Launcher {
52
53     public static void main(String[] args) throws Exception {
54         System.setProperty("jdk.tls.ephemeralDHKeySize", "4096");
55         new Launcher().boot();
56     }
57
58     Server s;
59
60     GigiConfig conf;
61
62     public synchronized void boot() throws Exception {
63         Locale.setDefault(Locale.ENGLISH);
64         TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
65
66         conf = GigiConfig.parse(System.in);
67         ServerConstants.init(conf.getMainProps());
68         initEmails(conf);
69
70         s = new Server();
71
72         initConnectors();
73         initHandlers();
74
75         s.start();
76         if ((ServerConstants.getSecurePort() <= 1024 || ServerConstants.getPort() <= 1024) && !System.getProperty("os.name").toLowerCase().contains("win")) {
77             SetUID uid = new SetUID();
78             if ( !uid.setUid(65536 - 2, 65536 - 2).getSuccess()) {
79                 Log.getLogger(Launcher.class).warn("Couldn't set uid!");
80             }
81         }
82     }
83
84     private HttpConfiguration createHttpConfiguration() {
85         // SSL HTTP Configuration
86         HttpConfiguration httpsConfig = new HttpConfiguration();
87         httpsConfig.setSendServerVersion(false);
88         httpsConfig.setSendXPoweredBy(false);
89         return httpsConfig;
90     }
91
92     private void initConnectors() throws GeneralSecurityException, IOException {
93         HttpConfiguration httpsConfig = createHttpConfiguration();
94         // for client-cert auth
95         httpsConfig.addCustomizer(new SecureRequestCustomizer());
96         HttpConfiguration httpConfig = createHttpConfiguration();
97         s.setConnectors(new Connector[] {
98                 ConnectorsLauncher.createConnector(conf, s, httpsConfig, true), ConnectorsLauncher.createConnector(conf, s, httpConfig, false)
99         });
100     }
101
102     private void initEmails(GigiConfig conf) throws GeneralSecurityException, IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
103         KeyStore privateStore = conf.getPrivateStore();
104         Certificate mail = privateStore.getCertificate("mail");
105         Key k = privateStore.getKey("mail", conf.getPrivateStorePw().toCharArray());
106         EmailProvider.initSystem(conf.getMainProps(), mail, k);
107     }
108
109     private static class ConnectorsLauncher {
110
111         private ConnectorsLauncher() {}
112
113         protected static ServerConnector createConnector(GigiConfig conf, Server s, HttpConfiguration httpConfig, boolean doHttps) throws GeneralSecurityException, IOException {
114             ServerConnector connector;
115             if (doHttps) {
116                 connector = new ServerConnector(s, createConnectionFactory(conf), new HttpConnectionFactory(httpConfig));
117             } else {
118                 connector = new ServerConnector(s, new HttpConnectionFactory(httpConfig));
119             }
120             connector.setHost(conf.getMainProps().getProperty("host"));
121             if (doHttps) {
122                 connector.setPort(ServerConstants.getSecurePort());
123             } else {
124                 connector.setPort(ServerConstants.getPort());
125             }
126             connector.setAcceptQueueSize(100);
127             return connector;
128         }
129
130         private static SslConnectionFactory createConnectionFactory(GigiConfig conf) throws GeneralSecurityException, IOException {
131             final SslContextFactory sslContextFactory = generateSSLContextFactory(conf, "www");
132             final SslContextFactory secureContextFactory = generateSSLContextFactory(conf, "secure");
133             secureContextFactory.setWantClientAuth(true);
134             secureContextFactory.setNeedClientAuth(true);
135             final SslContextFactory staticContextFactory = generateSSLContextFactory(conf, "static");
136             final SslContextFactory apiContextFactory = generateSSLContextFactory(conf, "api");
137             apiContextFactory.setWantClientAuth(true);
138             try {
139                 secureContextFactory.start();
140                 staticContextFactory.start();
141                 apiContextFactory.start();
142             } catch (Exception e) {
143                 e.printStackTrace();
144             }
145             return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()) {
146
147                 @Override
148                 public boolean shouldRestartSSL() {
149                     return true;
150                 }
151
152                 @Override
153                 public SSLEngine restartSSL(SSLSession sslSession) {
154                     SSLEngine e2 = null;
155                     if (sslSession instanceof ExtendedSSLSession) {
156                         ExtendedSSLSession es = (ExtendedSSLSession) sslSession;
157                         List<SNIServerName> names = es.getRequestedServerNames();
158                         for (SNIServerName sniServerName : names) {
159                             if (sniServerName instanceof SNIHostName) {
160                                 SNIHostName host = (SNIHostName) sniServerName;
161                                 String hostname = host.getAsciiName();
162                                 if (hostname.equals(ServerConstants.getWwwHostName())) {
163                                     e2 = sslContextFactory.newSSLEngine();
164                                 } else if (hostname.equals(ServerConstants.getStaticHostName())) {
165                                     e2 = staticContextFactory.newSSLEngine();
166                                 } else if (hostname.equals(ServerConstants.getSecureHostName())) {
167                                     e2 = secureContextFactory.newSSLEngine();
168                                 } else if (hostname.equals(ServerConstants.getApiHostName())) {
169                                     e2 = apiContextFactory.newSSLEngine();
170                                 }
171                                 break;
172                             }
173                         }
174                     }
175                     if (e2 == null) {
176                         e2 = sslContextFactory.newSSLEngine(sslSession.getPeerHost(), sslSession.getPeerPort());
177                     }
178                     e2.setUseClientMode(false);
179                     return e2;
180                 }
181             };
182         }
183
184         private static SslContextFactory generateSSLContextFactory(GigiConfig conf, String alias) throws GeneralSecurityException, IOException {
185             SslContextFactory scf = new SslContextFactory() {
186
187                 String[] ciphers = null;
188
189                 @Override
190                 public void customize(SSLEngine sslEngine) {
191                     super.customize(sslEngine);
192
193                     SSLParameters ssl = sslEngine.getSSLParameters();
194                     ssl.setUseCipherSuitesOrder(true);
195                     if (ciphers == null) {
196                         ciphers = CipherInfo.filter(sslEngine.getSupportedCipherSuites());
197                     }
198
199                     ssl.setCipherSuites(ciphers);
200                     sslEngine.setSSLParameters(ssl);
201
202                 }
203
204             };
205             scf.setRenegotiationAllowed(false);
206
207             scf.setProtocol("TLS");
208             scf.setIncludeProtocols("TLSv1", "TLSv1.1", "TLSv1.2");
209             scf.setTrustStore(conf.getTrustStore());
210             KeyStore privateStore = conf.getPrivateStore();
211             scf.setKeyStorePassword(conf.getPrivateStorePw());
212             scf.setKeyStore(privateStore);
213             scf.setCertAlias(alias);
214             return scf;
215         }
216     }
217
218     private void initHandlers() throws GeneralSecurityException, IOException {
219         HandlerList hl = new HandlerList();
220         hl.setHandlers(new Handler[] {
221                 ContextLauncher.generateStaticContext(), ContextLauncher.generateGigiContexts(conf.getMainProps(), conf.getTrustStore()), ContextLauncher.generateAPIContext()
222         });
223         s.setHandler(hl);
224     }
225
226     private static class ContextLauncher {
227
228         private ContextLauncher() {}
229
230         protected static Handler generateGigiContexts(Properties conf, KeyStore trust) {
231             ServletHolder webAppServlet = new ServletHolder(new Gigi(conf, trust));
232
233             ContextHandler ch = generateGigiServletContext(webAppServlet);
234             ch.setVirtualHosts(new String[] {
235                 ServerConstants.getWwwHostName()
236             });
237             ContextHandler chSecure = generateGigiServletContext(webAppServlet);
238             chSecure.setVirtualHosts(new String[] {
239                 ServerConstants.getSecureHostName()
240             });
241
242             HandlerList hl = new HandlerList();
243             hl.setHandlers(new Handler[] {
244                     ch, chSecure
245             });
246             return hl;
247         }
248
249         private static ContextHandler generateGigiServletContext(ServletHolder webAppServlet) {
250             final ResourceHandler rh = generateResourceHandler();
251             rh.setResourceBase("static/www");
252
253             HandlerWrapper hw = new PolicyRedirector();
254             hw.setHandler(rh);
255
256             ServletContextHandler servlet = new ServletContextHandler(ServletContextHandler.SESSIONS);
257             servlet.setInitParameter(SessionManager.__SessionCookieProperty, "CACert-Session");
258             servlet.addServlet(webAppServlet, "/*");
259             ErrorPageErrorHandler epeh = new ErrorPageErrorHandler();
260             epeh.addErrorPage(404, "/error");
261             epeh.addErrorPage(403, "/denied");
262             servlet.setErrorHandler(epeh);
263
264             HandlerList hl = new HandlerList();
265             hl.setHandlers(new Handler[] {
266                     hw, servlet
267             });
268
269             ContextHandler ch = new ContextHandler();
270             ch.setHandler(hl);
271             return ch;
272         }
273
274         protected static Handler generateStaticContext() {
275             final ResourceHandler rh = generateResourceHandler();
276             rh.setResourceBase("static/static");
277
278             ContextHandler ch = new ContextHandler();
279             ch.setHandler(rh);
280             ch.setVirtualHosts(new String[] {
281                 ServerConstants.getStaticHostName()
282             });
283
284             return ch;
285         }
286
287         private static ResourceHandler generateResourceHandler() {
288             ResourceHandler rh = new ResourceHandler() {
289
290                 @Override
291                 protected void doResponseHeaders(HttpServletResponse response, Resource resource, String mimeType) {
292                     super.doResponseHeaders(response, resource, mimeType);
293                     response.setDateHeader(HttpHeader.EXPIRES.asString(), System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 7);
294                 }
295             };
296             rh.setEtags(true);
297             return rh;
298         }
299
300         protected static Handler generateAPIContext() {
301             ServletContextHandler sch = new ServletContextHandler();
302
303             sch.addVirtualHosts(new String[] {
304                 ServerConstants.getApiHostName()
305             });
306             sch.addServlet(new ServletHolder(new GigiAPI()), "/*");
307             return sch;
308         }
309
310     }
311
312 }