1 package org.cacert.gigi;
3 import java.io.ByteArrayInputStream;
5 import java.io.FileInputStream;
6 import java.io.InputStream;
7 import java.io.IOException;
8 import java.net.HttpURLConnection;
9 import java.net.InetSocketAddress;
10 import java.security.GeneralSecurityException;
11 import java.security.Key;
12 import java.security.KeyStore;
13 import java.security.KeyStoreException;
14 import java.security.NoSuchAlgorithmException;
15 import java.security.UnrecoverableKeyException;
16 import java.security.cert.Certificate;
17 import java.security.cert.CertificateException;
18 import java.security.cert.CertificateFactory;
19 import java.security.cert.X509Certificate;
20 import java.util.List;
21 import java.util.Locale;
22 import java.util.Properties;
23 import java.util.TimeZone;
25 import javax.net.ssl.ExtendedSSLSession;
26 import javax.net.ssl.SNIHostName;
27 import javax.net.ssl.SNIServerName;
28 import javax.net.ssl.SSLEngine;
29 import javax.net.ssl.SSLParameters;
30 import javax.net.ssl.SSLSession;
31 import javax.servlet.http.HttpServletResponse;
33 import org.cacert.gigi.api.GigiAPI;
34 import org.cacert.gigi.email.EmailProvider;
35 import org.cacert.gigi.natives.SetUID;
36 import org.cacert.gigi.util.CipherInfo;
37 import org.cacert.gigi.util.PEM;
38 import org.cacert.gigi.util.ServerConstants;
39 import org.eclipse.jetty.http.HttpFields;
40 import org.eclipse.jetty.http.HttpHeader;
41 import org.eclipse.jetty.http.HttpVersion;
42 import org.eclipse.jetty.server.Connector;
43 import org.eclipse.jetty.server.Handler;
44 import org.eclipse.jetty.server.HttpConfiguration;
45 import org.eclipse.jetty.server.HttpConfiguration.Customizer;
46 import org.eclipse.jetty.server.HttpConnectionFactory;
47 import org.eclipse.jetty.server.Request;
48 import org.eclipse.jetty.server.SecureRequestCustomizer;
49 import org.eclipse.jetty.server.Server;
50 import org.eclipse.jetty.server.ServerConnector;
51 import org.eclipse.jetty.server.SessionManager;
52 import org.eclipse.jetty.server.SslConnectionFactory;
53 import org.eclipse.jetty.server.handler.ContextHandler;
54 import org.eclipse.jetty.server.handler.HandlerList;
55 import org.eclipse.jetty.server.handler.HandlerWrapper;
56 import org.eclipse.jetty.server.handler.ResourceHandler;
57 import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
58 import org.eclipse.jetty.servlet.ServletContextHandler;
59 import org.eclipse.jetty.servlet.ServletHolder;
60 import org.eclipse.jetty.util.log.Log;
61 import org.eclipse.jetty.util.resource.Resource;
62 import org.eclipse.jetty.util.ssl.SslContextFactory;
64 public class Launcher {
66 class ExtendedForwarded implements Customizer {
69 public void customize(Connector connector, HttpConfiguration config, Request request) {
70 HttpFields httpFields = request.getHttpFields();
72 String ip = httpFields.getStringField("X-Real-IP");
73 String proto = httpFields.getStringField("X-Real-Proto");
74 String cert = httpFields.getStringField("X-Client-Cert");
75 request.setSecure("https".equals(proto));
76 request.setScheme(proto);
77 if ( !"https".equals(proto)) {
82 X509Certificate[] certs = new X509Certificate[1];
84 certs[0] = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(PEM.decode("CERTIFICATE", cert)));
85 request.setAttribute("javax.servlet.request.X509Certificate", certs);
86 } catch (CertificateException e) {
91 String[] parts = ip.split(":");
92 if (parts.length == 2) {
93 request.setRemoteAddr(InetSocketAddress.createUnresolved(parts[0], Integer.parseInt(parts[1])));
100 public static void main(String[] args) throws Exception {
101 System.setProperty("jdk.tls.ephemeralDHKeySize", "4096");
103 if (args.length >= 1) {
104 in = new FileInputStream(new File(args[0]));
108 new Launcher().boot(in);
115 public synchronized void boot(InputStream in) throws Exception {
116 Locale.setDefault(Locale.ENGLISH);
117 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
118 HttpURLConnection.setFollowRedirects(false);
120 conf = GigiConfig.parse(in);
121 ServerConstants.init(conf.getMainProps());
130 if ((ServerConstants.getSecurePort() <= 1024 || ServerConstants.getPort() <= 1024) && !System.getProperty("os.name").toLowerCase().contains("win")) {
131 SetUID uid = new SetUID();
132 if ( !uid.setUid(65536 - 2, 65536 - 2).getSuccess()) {
133 Log.getLogger(Launcher.class).warn("Couldn't set uid!");
138 private HttpConfiguration createHttpConfiguration() {
139 // SSL HTTP Configuration
140 HttpConfiguration httpsConfig = new HttpConfiguration();
141 httpsConfig.setSendServerVersion(false);
142 httpsConfig.setSendXPoweredBy(false);
146 private void initConnectors() throws GeneralSecurityException, IOException {
147 HttpConfiguration httpConfig = createHttpConfiguration();
148 if (conf.getMainProps().getProperty("proxy", "false").equals("true")) {
149 httpConfig.addCustomizer(new ExtendedForwarded());
150 s.setConnectors(new Connector[] {
151 ConnectorsLauncher.createConnector(conf, s, httpConfig, false)
154 HttpConfiguration httpsConfig = createHttpConfiguration();
155 // for client-cert auth
156 httpsConfig.addCustomizer(new SecureRequestCustomizer());
157 s.setConnectors(new Connector[] {
158 ConnectorsLauncher.createConnector(conf, s, httpsConfig, true), ConnectorsLauncher.createConnector(conf, s, httpConfig, false)
163 private void initEmails(GigiConfig conf) throws GeneralSecurityException, IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
164 KeyStore privateStore = conf.getPrivateStore();
165 Certificate mail = null;
167 if (privateStore != null && privateStore.containsAlias("mail")) {
168 mail = privateStore.getCertificate("mail");
169 k = privateStore.getKey("mail", conf.getPrivateStorePw().toCharArray());
171 EmailProvider.initSystem(conf.getMainProps(), mail, k);
174 private static class ConnectorsLauncher {
176 private ConnectorsLauncher() {}
178 protected static ServerConnector createConnector(GigiConfig conf, Server s, HttpConfiguration httpConfig, boolean doHttps) throws GeneralSecurityException, IOException {
179 ServerConnector connector;
181 connector = new ServerConnector(s, createConnectionFactory(conf), new HttpConnectionFactory(httpConfig));
183 connector = new ServerConnector(s, new HttpConnectionFactory(httpConfig));
185 connector.setHost(conf.getMainProps().getProperty("host"));
187 connector.setPort(ServerConstants.getSecurePort());
189 connector.setPort(ServerConstants.getPort());
191 connector.setAcceptQueueSize(100);
195 private static SslConnectionFactory createConnectionFactory(GigiConfig conf) throws GeneralSecurityException, IOException {
196 final SslContextFactory sslContextFactory = generateSSLContextFactory(conf, "www");
197 final SslContextFactory secureContextFactory = generateSSLContextFactory(conf, "secure");
198 secureContextFactory.setWantClientAuth(true);
199 secureContextFactory.setNeedClientAuth(true);
200 final SslContextFactory staticContextFactory = generateSSLContextFactory(conf, "static");
201 final SslContextFactory apiContextFactory = generateSSLContextFactory(conf, "api");
202 apiContextFactory.setWantClientAuth(true);
204 secureContextFactory.start();
205 staticContextFactory.start();
206 apiContextFactory.start();
207 } catch (Exception e) {
210 return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()) {
213 public boolean shouldRestartSSL() {
218 public SSLEngine restartSSL(SSLSession sslSession) {
220 if (sslSession instanceof ExtendedSSLSession) {
221 ExtendedSSLSession es = (ExtendedSSLSession) sslSession;
222 List<SNIServerName> names = es.getRequestedServerNames();
223 for (SNIServerName sniServerName : names) {
224 if (sniServerName instanceof SNIHostName) {
225 SNIHostName host = (SNIHostName) sniServerName;
226 String hostname = host.getAsciiName();
227 if (hostname.equals(ServerConstants.getWwwHostName())) {
228 e2 = sslContextFactory.newSSLEngine();
229 } else if (hostname.equals(ServerConstants.getStaticHostName())) {
230 e2 = staticContextFactory.newSSLEngine();
231 } else if (hostname.equals(ServerConstants.getSecureHostName())) {
232 e2 = secureContextFactory.newSSLEngine();
233 } else if (hostname.equals(ServerConstants.getApiHostName())) {
234 e2 = apiContextFactory.newSSLEngine();
241 e2 = sslContextFactory.newSSLEngine(sslSession.getPeerHost(), sslSession.getPeerPort());
243 e2.setUseClientMode(false);
249 private static SslContextFactory generateSSLContextFactory(GigiConfig conf, String alias) throws GeneralSecurityException, IOException {
250 SslContextFactory scf = new SslContextFactory() {
252 String[] ciphers = null;
255 public void customize(SSLEngine sslEngine) {
256 super.customize(sslEngine);
258 SSLParameters ssl = sslEngine.getSSLParameters();
259 ssl.setUseCipherSuitesOrder(true);
260 if (ciphers == null) {
261 ciphers = CipherInfo.filter(sslEngine.getSupportedCipherSuites());
264 ssl.setCipherSuites(ciphers);
265 sslEngine.setSSLParameters(ssl);
270 scf.setRenegotiationAllowed(false);
272 scf.setProtocol("TLS");
273 scf.setIncludeProtocols("TLSv1", "TLSv1.1", "TLSv1.2");
274 scf.setTrustStore(conf.getTrustStore());
275 KeyStore privateStore = conf.getPrivateStore();
276 scf.setKeyStorePassword(conf.getPrivateStorePw());
277 scf.setKeyStore(privateStore);
278 scf.setCertAlias(alias);
283 private void initHandlers() throws GeneralSecurityException, IOException {
284 HandlerList hl = new HandlerList();
285 hl.setHandlers(new Handler[] {
286 ContextLauncher.generateStaticContext(), ContextLauncher.generateGigiContexts(conf.getMainProps(), conf.getTrustStore()), ContextLauncher.generateAPIContext()
291 private static class ContextLauncher {
293 private ContextLauncher() {}
295 protected static Handler generateGigiContexts(Properties conf, KeyStore trust) {
296 ServletHolder webAppServlet = new ServletHolder(new Gigi(conf, trust));
298 ContextHandler ch = generateGigiServletContext(webAppServlet);
299 ch.setVirtualHosts(new String[] {
300 ServerConstants.getWwwHostName()
302 ContextHandler chSecure = generateGigiServletContext(webAppServlet);
303 chSecure.setVirtualHosts(new String[] {
304 ServerConstants.getSecureHostName()
307 HandlerList hl = new HandlerList();
308 hl.setHandlers(new Handler[] {
314 private static ContextHandler generateGigiServletContext(ServletHolder webAppServlet) {
315 final ResourceHandler rh = generateResourceHandler();
316 rh.setResourceBase("static/www");
318 HandlerWrapper hw = new PolicyRedirector();
321 ServletContextHandler servlet = new ServletContextHandler(ServletContextHandler.SESSIONS);
322 servlet.setInitParameter(SessionManager.__SessionCookieProperty, "SomeCA-Session");
323 servlet.addServlet(webAppServlet, "/*");
324 ErrorPageErrorHandler epeh = new ErrorPageErrorHandler();
325 epeh.addErrorPage(404, "/error");
326 epeh.addErrorPage(403, "/denied");
327 servlet.setErrorHandler(epeh);
329 HandlerList hl = new HandlerList();
330 hl.setHandlers(new Handler[] {
334 ContextHandler ch = new ContextHandler();
339 protected static Handler generateStaticContext() {
340 final ResourceHandler rh = generateResourceHandler();
341 rh.setResourceBase("static/static");
343 ContextHandler ch = new ContextHandler();
345 ch.setVirtualHosts(new String[] {
346 ServerConstants.getStaticHostName()
352 private static ResourceHandler generateResourceHandler() {
353 ResourceHandler rh = new ResourceHandler() {
356 protected void doResponseHeaders(HttpServletResponse response, Resource resource, String mimeType) {
357 super.doResponseHeaders(response, resource, mimeType);
358 response.setDateHeader(HttpHeader.EXPIRES.asString(), System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 7);
365 protected static Handler generateAPIContext() {
366 ServletContextHandler sch = new ServletContextHandler();
368 sch.addVirtualHosts(new String[] {
369 ServerConstants.getApiHostName()
371 sch.addServlet(new ServletHolder(new GigiAPI()), "/*");