1 package org.cacert.gigi;
3 import java.io.ByteArrayInputStream;
4 import java.io.IOException;
5 import java.net.HttpURLConnection;
6 import java.net.InetSocketAddress;
7 import java.security.GeneralSecurityException;
8 import java.security.Key;
9 import java.security.KeyStore;
10 import java.security.KeyStoreException;
11 import java.security.NoSuchAlgorithmException;
12 import java.security.UnrecoverableKeyException;
13 import java.security.cert.Certificate;
14 import java.security.cert.CertificateException;
15 import java.security.cert.CertificateFactory;
16 import java.security.cert.X509Certificate;
17 import java.util.List;
18 import java.util.Locale;
19 import java.util.Properties;
20 import java.util.TimeZone;
22 import javax.net.ssl.ExtendedSSLSession;
23 import javax.net.ssl.SNIHostName;
24 import javax.net.ssl.SNIServerName;
25 import javax.net.ssl.SSLEngine;
26 import javax.net.ssl.SSLParameters;
27 import javax.net.ssl.SSLSession;
28 import javax.servlet.http.HttpServletResponse;
30 import org.cacert.gigi.api.GigiAPI;
31 import org.cacert.gigi.email.EmailProvider;
32 import org.cacert.gigi.natives.SetUID;
33 import org.cacert.gigi.util.CipherInfo;
34 import org.cacert.gigi.util.PEM;
35 import org.cacert.gigi.util.ServerConstants;
36 import org.eclipse.jetty.http.HttpFields;
37 import org.eclipse.jetty.http.HttpHeader;
38 import org.eclipse.jetty.http.HttpVersion;
39 import org.eclipse.jetty.server.Connector;
40 import org.eclipse.jetty.server.Handler;
41 import org.eclipse.jetty.server.HttpConfiguration;
42 import org.eclipse.jetty.server.HttpConfiguration.Customizer;
43 import org.eclipse.jetty.server.HttpConnectionFactory;
44 import org.eclipse.jetty.server.Request;
45 import org.eclipse.jetty.server.SecureRequestCustomizer;
46 import org.eclipse.jetty.server.Server;
47 import org.eclipse.jetty.server.ServerConnector;
48 import org.eclipse.jetty.server.SessionManager;
49 import org.eclipse.jetty.server.SslConnectionFactory;
50 import org.eclipse.jetty.server.handler.ContextHandler;
51 import org.eclipse.jetty.server.handler.HandlerList;
52 import org.eclipse.jetty.server.handler.HandlerWrapper;
53 import org.eclipse.jetty.server.handler.ResourceHandler;
54 import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
55 import org.eclipse.jetty.servlet.ServletContextHandler;
56 import org.eclipse.jetty.servlet.ServletHolder;
57 import org.eclipse.jetty.util.log.Log;
58 import org.eclipse.jetty.util.resource.Resource;
59 import org.eclipse.jetty.util.ssl.SslContextFactory;
61 public class Launcher {
63 class ExtendedForwarded implements Customizer {
66 public void customize(Connector connector, HttpConfiguration config, Request request) {
67 HttpFields httpFields = request.getHttpFields();
69 String ip = httpFields.getStringField("X-Real-IP");
70 String proto = httpFields.getStringField("X-Real-Proto");
71 String cert = httpFields.getStringField("X-Client-Cert");
72 request.setSecure("https".equals(proto));
73 request.setScheme(proto);
74 if ( !"https".equals(proto)) {
79 X509Certificate[] certs = new X509Certificate[1];
81 certs[0] = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(PEM.decode("CERTIFICATE", cert)));
82 request.setAttribute("javax.servlet.request.X509Certificate", certs);
83 } catch (CertificateException e) {
88 String[] parts = ip.split(":");
89 if (parts.length == 2) {
90 request.setRemoteAddr(InetSocketAddress.createUnresolved(parts[0], Integer.parseInt(parts[1])));
97 public static void main(String[] args) throws Exception {
98 System.setProperty("jdk.tls.ephemeralDHKeySize", "4096");
99 new Launcher().boot();
106 public synchronized void boot() throws Exception {
107 Locale.setDefault(Locale.ENGLISH);
108 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
109 HttpURLConnection.setFollowRedirects(false);
111 conf = GigiConfig.parse(System.in);
112 ServerConstants.init(conf.getMainProps());
121 if ((ServerConstants.getSecurePort() <= 1024 || ServerConstants.getPort() <= 1024) && !System.getProperty("os.name").toLowerCase().contains("win")) {
122 SetUID uid = new SetUID();
123 if ( !uid.setUid(65536 - 2, 65536 - 2).getSuccess()) {
124 Log.getLogger(Launcher.class).warn("Couldn't set uid!");
129 private HttpConfiguration createHttpConfiguration() {
130 // SSL HTTP Configuration
131 HttpConfiguration httpsConfig = new HttpConfiguration();
132 httpsConfig.setSendServerVersion(false);
133 httpsConfig.setSendXPoweredBy(false);
137 private void initConnectors() throws GeneralSecurityException, IOException {
138 HttpConfiguration httpConfig = createHttpConfiguration();
139 if (conf.getMainProps().getProperty("proxy", "false").equals("true")) {
140 httpConfig.addCustomizer(new ExtendedForwarded());
141 s.setConnectors(new Connector[] {
142 ConnectorsLauncher.createConnector(conf, s, httpConfig, false)
145 HttpConfiguration httpsConfig = createHttpConfiguration();
146 // for client-cert auth
147 httpsConfig.addCustomizer(new SecureRequestCustomizer());
148 s.setConnectors(new Connector[] {
149 ConnectorsLauncher.createConnector(conf, s, httpsConfig, true), ConnectorsLauncher.createConnector(conf, s, httpConfig, false)
154 private void initEmails(GigiConfig conf) throws GeneralSecurityException, IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
155 KeyStore privateStore = conf.getPrivateStore();
156 Certificate mail = null;
158 if (privateStore != null && privateStore.containsAlias("mail")) {
159 mail = privateStore.getCertificate("mail");
160 k = privateStore.getKey("mail", conf.getPrivateStorePw().toCharArray());
162 EmailProvider.initSystem(conf.getMainProps(), mail, k);
165 private static class ConnectorsLauncher {
167 private ConnectorsLauncher() {}
169 protected static ServerConnector createConnector(GigiConfig conf, Server s, HttpConfiguration httpConfig, boolean doHttps) throws GeneralSecurityException, IOException {
170 ServerConnector connector;
172 connector = new ServerConnector(s, createConnectionFactory(conf), new HttpConnectionFactory(httpConfig));
174 connector = new ServerConnector(s, new HttpConnectionFactory(httpConfig));
176 connector.setHost(conf.getMainProps().getProperty("host"));
178 connector.setPort(ServerConstants.getSecurePort());
180 connector.setPort(ServerConstants.getPort());
182 connector.setAcceptQueueSize(100);
186 private static SslConnectionFactory createConnectionFactory(GigiConfig conf) throws GeneralSecurityException, IOException {
187 final SslContextFactory sslContextFactory = generateSSLContextFactory(conf, "www");
188 final SslContextFactory secureContextFactory = generateSSLContextFactory(conf, "secure");
189 secureContextFactory.setWantClientAuth(true);
190 secureContextFactory.setNeedClientAuth(true);
191 final SslContextFactory staticContextFactory = generateSSLContextFactory(conf, "static");
192 final SslContextFactory apiContextFactory = generateSSLContextFactory(conf, "api");
193 apiContextFactory.setWantClientAuth(true);
195 secureContextFactory.start();
196 staticContextFactory.start();
197 apiContextFactory.start();
198 } catch (Exception e) {
201 return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()) {
204 public boolean shouldRestartSSL() {
209 public SSLEngine restartSSL(SSLSession sslSession) {
211 if (sslSession instanceof ExtendedSSLSession) {
212 ExtendedSSLSession es = (ExtendedSSLSession) sslSession;
213 List<SNIServerName> names = es.getRequestedServerNames();
214 for (SNIServerName sniServerName : names) {
215 if (sniServerName instanceof SNIHostName) {
216 SNIHostName host = (SNIHostName) sniServerName;
217 String hostname = host.getAsciiName();
218 if (hostname.equals(ServerConstants.getWwwHostName())) {
219 e2 = sslContextFactory.newSSLEngine();
220 } else if (hostname.equals(ServerConstants.getStaticHostName())) {
221 e2 = staticContextFactory.newSSLEngine();
222 } else if (hostname.equals(ServerConstants.getSecureHostName())) {
223 e2 = secureContextFactory.newSSLEngine();
224 } else if (hostname.equals(ServerConstants.getApiHostName())) {
225 e2 = apiContextFactory.newSSLEngine();
232 e2 = sslContextFactory.newSSLEngine(sslSession.getPeerHost(), sslSession.getPeerPort());
234 e2.setUseClientMode(false);
240 private static SslContextFactory generateSSLContextFactory(GigiConfig conf, String alias) throws GeneralSecurityException, IOException {
241 SslContextFactory scf = new SslContextFactory() {
243 String[] ciphers = null;
246 public void customize(SSLEngine sslEngine) {
247 super.customize(sslEngine);
249 SSLParameters ssl = sslEngine.getSSLParameters();
250 ssl.setUseCipherSuitesOrder(true);
251 if (ciphers == null) {
252 ciphers = CipherInfo.filter(sslEngine.getSupportedCipherSuites());
255 ssl.setCipherSuites(ciphers);
256 sslEngine.setSSLParameters(ssl);
261 scf.setRenegotiationAllowed(false);
263 scf.setProtocol("TLS");
264 scf.setIncludeProtocols("TLSv1", "TLSv1.1", "TLSv1.2");
265 scf.setTrustStore(conf.getTrustStore());
266 KeyStore privateStore = conf.getPrivateStore();
267 scf.setKeyStorePassword(conf.getPrivateStorePw());
268 scf.setKeyStore(privateStore);
269 scf.setCertAlias(alias);
274 private void initHandlers() throws GeneralSecurityException, IOException {
275 HandlerList hl = new HandlerList();
276 hl.setHandlers(new Handler[] {
277 ContextLauncher.generateStaticContext(), ContextLauncher.generateGigiContexts(conf.getMainProps(), conf.getTrustStore()), ContextLauncher.generateAPIContext()
282 private static class ContextLauncher {
284 private ContextLauncher() {}
286 protected static Handler generateGigiContexts(Properties conf, KeyStore trust) {
287 ServletHolder webAppServlet = new ServletHolder(new Gigi(conf, trust));
289 ContextHandler ch = generateGigiServletContext(webAppServlet);
290 ch.setVirtualHosts(new String[] {
291 ServerConstants.getWwwHostName()
293 ContextHandler chSecure = generateGigiServletContext(webAppServlet);
294 chSecure.setVirtualHosts(new String[] {
295 ServerConstants.getSecureHostName()
298 HandlerList hl = new HandlerList();
299 hl.setHandlers(new Handler[] {
305 private static ContextHandler generateGigiServletContext(ServletHolder webAppServlet) {
306 final ResourceHandler rh = generateResourceHandler();
307 rh.setResourceBase("static/www");
309 HandlerWrapper hw = new PolicyRedirector();
312 ServletContextHandler servlet = new ServletContextHandler(ServletContextHandler.SESSIONS);
313 servlet.setInitParameter(SessionManager.__SessionCookieProperty, "SomeCA-Session");
314 servlet.addServlet(webAppServlet, "/*");
315 ErrorPageErrorHandler epeh = new ErrorPageErrorHandler();
316 epeh.addErrorPage(404, "/error");
317 epeh.addErrorPage(403, "/denied");
318 servlet.setErrorHandler(epeh);
320 HandlerList hl = new HandlerList();
321 hl.setHandlers(new Handler[] {
325 ContextHandler ch = new ContextHandler();
330 protected static Handler generateStaticContext() {
331 final ResourceHandler rh = generateResourceHandler();
332 rh.setResourceBase("static/static");
334 ContextHandler ch = new ContextHandler();
336 ch.setVirtualHosts(new String[] {
337 ServerConstants.getStaticHostName()
343 private static ResourceHandler generateResourceHandler() {
344 ResourceHandler rh = new ResourceHandler() {
347 protected void doResponseHeaders(HttpServletResponse response, Resource resource, String mimeType) {
348 super.doResponseHeaders(response, resource, mimeType);
349 response.setDateHeader(HttpHeader.EXPIRES.asString(), System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 7);
356 protected static Handler generateAPIContext() {
357 ServletContextHandler sch = new ServletContextHandler();
359 sch.addVirtualHosts(new String[] {
360 ServerConstants.getApiHostName()
362 sch.addServlet(new ServletHolder(new GigiAPI()), "/*");