]> WPIA git - gigi.git/blob - src/club/wpia/gigi/Launcher.java
upd: remove 'browser install'
[gigi.git] / src / club / wpia / gigi / Launcher.java
1 package club.wpia.gigi;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.IOException;
7 import java.io.InputStream;
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;
24
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;
32
33 import org.eclipse.jetty.http.HttpFields;
34 import org.eclipse.jetty.http.HttpHeader;
35 import org.eclipse.jetty.http.HttpVersion;
36 import org.eclipse.jetty.server.Connector;
37 import org.eclipse.jetty.server.Handler;
38 import org.eclipse.jetty.server.HttpConfiguration;
39 import org.eclipse.jetty.server.HttpConfiguration.Customizer;
40 import org.eclipse.jetty.server.HttpConnectionFactory;
41 import org.eclipse.jetty.server.Request;
42 import org.eclipse.jetty.server.SecureRequestCustomizer;
43 import org.eclipse.jetty.server.Server;
44 import org.eclipse.jetty.server.ServerConnector;
45 import org.eclipse.jetty.server.SessionManager;
46 import org.eclipse.jetty.server.SslConnectionFactory;
47 import org.eclipse.jetty.server.handler.ContextHandler;
48 import org.eclipse.jetty.server.handler.HandlerList;
49 import org.eclipse.jetty.server.handler.HandlerWrapper;
50 import org.eclipse.jetty.server.handler.ResourceHandler;
51 import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
52 import org.eclipse.jetty.servlet.ServletContextHandler;
53 import org.eclipse.jetty.servlet.ServletHolder;
54 import org.eclipse.jetty.util.log.Log;
55 import org.eclipse.jetty.util.resource.Resource;
56 import org.eclipse.jetty.util.ssl.SslContextFactory;
57
58 import club.wpia.gigi.api.GigiAPI;
59 import club.wpia.gigi.email.EmailProvider;
60 import club.wpia.gigi.natives.SetUID;
61 import club.wpia.gigi.ocsp.OCSPResponder;
62 import club.wpia.gigi.util.CipherInfo;
63 import club.wpia.gigi.util.PEM;
64 import club.wpia.gigi.util.ServerConstants;
65 import club.wpia.gigi.util.ServerConstants.Host;
66
67 public class Launcher {
68
69     class ExtendedForwarded implements Customizer {
70
71         @Override
72         public void customize(Connector connector, HttpConfiguration config, Request request) {
73             HttpFields httpFields = request.getHttpFields();
74
75             String ip = httpFields.getStringField("X-Real-IP");
76             String proto = httpFields.getStringField("X-Real-Proto");
77             String cert = httpFields.getStringField("X-Client-Cert");
78             request.setSecure("https".equals(proto));
79             request.setScheme(proto);
80             if ( !"https".equals(proto)) {
81                 cert = null;
82
83             }
84             if (cert != null) {
85                 X509Certificate[] certs = new X509Certificate[1];
86                 try {
87                     certs[0] = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(new ByteArrayInputStream(PEM.decode("CERTIFICATE", cert)));
88                     request.setAttribute("javax.servlet.request.X509Certificate", certs);
89                 } catch (CertificateException e) {
90                     e.printStackTrace();
91                 }
92             }
93             if (ip != null) {
94                 String[] parts = ip.split(":");
95                 if (parts.length == 2) {
96                     request.setRemoteAddr(InetSocketAddress.createUnresolved(parts[0], Integer.parseInt(parts[1])));
97                 }
98             }
99
100         }
101     }
102
103     public static void main(String[] args) throws Exception {
104         System.setProperty("jdk.tls.ephemeralDHKeySize", "4096");
105         InputStream in;
106         if (args.length >= 1) {
107             in = new FileInputStream(new File(args[0]));
108         } else {
109             in = System.in;
110         }
111         new Launcher().boot(in);
112     }
113
114     Server s;
115
116     GigiConfig conf;
117
118     private boolean isSystemPort(int port) {
119         return 1 <= port && port <= 1024;
120     }
121
122     public synchronized void boot(InputStream in) throws Exception {
123         Locale.setDefault(Locale.ENGLISH);
124         TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
125         HttpURLConnection.setFollowRedirects(false);
126
127         conf = GigiConfig.parse(in);
128         ServerConstants.init(conf.getMainProps());
129         initEmails(conf);
130
131         s = new Server();
132
133         initConnectors();
134         initHandlers();
135
136         s.start();
137         if ((isSystemPort(ServerConstants.getSecurePort()) || isSystemPort(ServerConstants.getPort())) && !System.getProperty("os.name").toLowerCase().contains("win")) {
138             String uid_s = conf.getMainProps().getProperty("gigi.uid", Integer.toString(65536 - 2));
139             String gid_s = conf.getMainProps().getProperty("gigi.gid", Integer.toString(65536 - 2));
140             try {
141                 int uid = Integer.parseInt(uid_s);
142                 int gid = Integer.parseInt(gid_s);
143                 if (uid == -1 && gid == -1) {
144                     // skip setuid step
145                 } else if (uid > 0 && gid > 0 && uid < 65536 && gid < 65536) {
146                     SetUID.Status status = new SetUID().setUid(uid, gid);
147                     if ( !status.getSuccess()) {
148                         Log.getLogger(Launcher.class).warn(status.getMessage());
149                     }
150                 } else {
151                     Log.getLogger(Launcher.class).warn("Invalid uid or gid (must satisfy 0 < id < 65536)");
152                 }
153             } catch (NumberFormatException e) {
154                 Log.getLogger(Launcher.class).warn("Invalid gigi.uid or gigi.gid", e);
155             }
156         }
157     }
158
159     private HttpConfiguration createHttpConfiguration() {
160         // SSL HTTP Configuration
161         HttpConfiguration httpsConfig = new HttpConfiguration();
162         httpsConfig.setSendServerVersion(false);
163         httpsConfig.setSendXPoweredBy(false);
164         return httpsConfig;
165     }
166
167     private void initConnectors() throws GeneralSecurityException, IOException {
168         HttpConfiguration httpConfig = createHttpConfiguration();
169         if (conf.getMainProps().getProperty("proxy", "false").equals("true")) {
170             httpConfig.addCustomizer(new ExtendedForwarded());
171             s.setConnectors(new Connector[] {
172                     ConnectorsLauncher.createConnector(conf, s, httpConfig, false)
173             });
174         } else {
175             HttpConfiguration httpsConfig = createHttpConfiguration();
176             // for client-cert auth
177             httpsConfig.addCustomizer(new SecureRequestCustomizer());
178             s.setConnectors(new Connector[] {
179                     ConnectorsLauncher.createConnector(conf, s, httpsConfig, true), ConnectorsLauncher.createConnector(conf, s, httpConfig, false)
180             });
181         }
182     }
183
184     private void initEmails(GigiConfig conf) throws GeneralSecurityException, IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
185         KeyStore privateStore = conf.getPrivateStore();
186         Certificate mail = null;
187         Key k = null;
188         if (privateStore != null && privateStore.containsAlias("mail")) {
189             mail = privateStore.getCertificate("mail");
190             k = privateStore.getKey("mail", conf.getPrivateStorePw().toCharArray());
191         }
192         EmailProvider.initSystem(conf.getMainProps(), mail, k);
193     }
194
195     private static class ConnectorsLauncher {
196
197         private ConnectorsLauncher() {}
198
199         protected static ServerConnector createConnector(GigiConfig conf, Server s, HttpConfiguration httpConfig, boolean doHttps) throws GeneralSecurityException, IOException {
200             ServerConnector connector;
201             int port;
202             if (doHttps) {
203                 connector = new ServerConnector(s, createConnectionFactory(conf), new HttpConnectionFactory(httpConfig));
204                 port = ServerConstants.getSecurePort();
205             } else {
206                 connector = new ServerConnector(s, new HttpConnectionFactory(httpConfig));
207                 port = ServerConstants.getPort();
208             }
209             if (port == -1) {
210                 connector.setInheritChannel(true);
211             } else {
212                 connector.setHost(conf.getMainProps().getProperty("host"));
213                 connector.setPort(port);
214             }
215             connector.setAcceptQueueSize(100);
216             return connector;
217         }
218
219         private static SslConnectionFactory createConnectionFactory(GigiConfig conf) throws GeneralSecurityException, IOException {
220             final SslContextFactory sslContextFactory = generateSSLContextFactory(conf, "www");
221             final SslContextFactory secureContextFactory = generateSSLContextFactory(conf, "secure");
222             secureContextFactory.setWantClientAuth(true);
223             secureContextFactory.setNeedClientAuth(true);
224             final SslContextFactory staticContextFactory = generateSSLContextFactory(conf, "static");
225             final SslContextFactory apiContextFactory = generateSSLContextFactory(conf, "api");
226             apiContextFactory.setWantClientAuth(true);
227             try {
228                 secureContextFactory.start();
229                 staticContextFactory.start();
230                 apiContextFactory.start();
231             } catch (Exception e) {
232                 e.printStackTrace();
233             }
234             return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()) {
235
236                 @Override
237                 public boolean shouldRestartSSL() {
238                     return true;
239                 }
240
241                 @Override
242                 public SSLEngine restartSSL(SSLSession sslSession) {
243                     SSLEngine e2 = null;
244                     if (sslSession instanceof ExtendedSSLSession) {
245                         ExtendedSSLSession es = (ExtendedSSLSession) sslSession;
246                         List<SNIServerName> names = es.getRequestedServerNames();
247                         for (SNIServerName sniServerName : names) {
248                             if (sniServerName instanceof SNIHostName) {
249                                 SNIHostName host = (SNIHostName) sniServerName;
250                                 String hostname = host.getAsciiName();
251                                 if (hostname.equals(ServerConstants.getHostName(Host.WWW))) {
252                                     e2 = sslContextFactory.newSSLEngine();
253                                 } else if (hostname.equals(ServerConstants.getHostName(Host.STATIC))) {
254                                     e2 = staticContextFactory.newSSLEngine();
255                                 } else if (hostname.equals(ServerConstants.getHostName(Host.SECURE))) {
256                                     e2 = secureContextFactory.newSSLEngine();
257                                 } else if (hostname.equals(ServerConstants.getHostName(Host.API))) {
258                                     e2 = apiContextFactory.newSSLEngine();
259                                 }
260                                 break;
261                             }
262                         }
263                     }
264                     if (e2 == null) {
265                         e2 = sslContextFactory.newSSLEngine(sslSession.getPeerHost(), sslSession.getPeerPort());
266                     }
267                     e2.setUseClientMode(false);
268                     return e2;
269                 }
270             };
271         }
272
273         private static SslContextFactory generateSSLContextFactory(GigiConfig conf, String alias) throws GeneralSecurityException, IOException {
274             SslContextFactory scf = new SslContextFactory() {
275
276                 String[] ciphers = null;
277
278                 @Override
279                 public void customize(SSLEngine sslEngine) {
280                     super.customize(sslEngine);
281
282                     SSLParameters ssl = sslEngine.getSSLParameters();
283                     ssl.setUseCipherSuitesOrder(true);
284                     if (ciphers == null) {
285                         ciphers = CipherInfo.filter(sslEngine.getSupportedCipherSuites());
286                     }
287
288                     ssl.setCipherSuites(ciphers);
289                     sslEngine.setSSLParameters(ssl);
290
291                 }
292
293             };
294             scf.setRenegotiationAllowed(false);
295
296             scf.setProtocol("TLS");
297             scf.setIncludeProtocols("TLSv1", "TLSv1.1", "TLSv1.2");
298             scf.setTrustStore(conf.getTrustStore());
299             KeyStore privateStore = conf.getPrivateStore();
300             scf.setKeyStorePassword(conf.getPrivateStorePw());
301             scf.setKeyStore(privateStore);
302             scf.setCertAlias(alias);
303             return scf;
304         }
305     }
306
307     private void initHandlers() throws GeneralSecurityException, IOException {
308         HandlerList hl = new HandlerList();
309         hl.setHandlers(new Handler[] {
310                 ContextLauncher.generateStaticContext(), ContextLauncher.generateGigiContexts(conf.getMainProps(), conf.getTrustStore()), ContextLauncher.generateAPIContext(), ContextLauncher.generateOCSPContext()
311         });
312         s.setHandler(hl);
313     }
314
315     private static class ContextLauncher {
316
317         private ContextLauncher() {}
318
319         protected static Handler generateGigiContexts(Properties conf, KeyStore trust) {
320             ServletHolder webAppServlet = new ServletHolder(new Gigi(conf, trust));
321
322             ContextHandler ch = generateGigiServletContext(webAppServlet);
323             ch.setVirtualHosts(new String[] {
324                     ServerConstants.getHostName(Host.WWW)
325             });
326             ContextHandler chSecure = generateGigiServletContext(webAppServlet);
327             chSecure.setVirtualHosts(new String[] {
328                     ServerConstants.getHostName(Host.SECURE)
329             });
330
331             HandlerList hl = new HandlerList();
332             hl.setHandlers(new Handler[] {
333                     ch, chSecure
334             });
335             return hl;
336         }
337
338         private static ContextHandler generateGigiServletContext(ServletHolder webAppServlet) {
339             final ResourceHandler rh = generateResourceHandler();
340             rh.setResourceBase("static/www");
341
342             HandlerWrapper hw = new HandlerWrapper();
343             hw.setHandler(rh);
344
345             ServletContextHandler servlet = new ServletContextHandler(ServletContextHandler.SESSIONS);
346             servlet.setInitParameter(SessionManager.__SessionCookieProperty, ServerConstants.getAppName() + "-Session");
347             servlet.addServlet(webAppServlet, "/*");
348             ErrorPageErrorHandler epeh = new ErrorPageErrorHandler();
349             epeh.addErrorPage(404, "/error");
350             epeh.addErrorPage(403, "/denied");
351             servlet.setErrorHandler(epeh);
352
353             HandlerList hl = new HandlerList();
354             hl.setHandlers(new Handler[] {
355                     hw, servlet
356             });
357
358             ContextHandler ch = new ContextHandler();
359             ch.setHandler(hl);
360             return ch;
361         }
362
363         protected static Handler generateStaticContext() {
364             final ResourceHandler rh = generateResourceHandler();
365             rh.setResourceBase("static/static");
366
367             ContextHandler ch = new ContextHandler();
368             ch.setHandler(rh);
369             ch.setVirtualHosts(new String[] {
370                     ServerConstants.getHostName(Host.STATIC)
371             });
372
373             return ch;
374         }
375
376         private static ResourceHandler generateResourceHandler() {
377             ResourceHandler rh = new ResourceHandler() {
378
379                 @Override
380                 protected void doResponseHeaders(HttpServletResponse response, Resource resource, String mimeType) {
381                     super.doResponseHeaders(response, resource, mimeType);
382                     response.setDateHeader(HttpHeader.EXPIRES.asString(), System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 7);
383                 }
384             };
385             rh.setEtags(true);
386             return rh;
387         }
388
389         protected static Handler generateAPIContext() {
390             ServletContextHandler sch = new ServletContextHandler();
391
392             sch.addVirtualHosts(new String[] {
393                     ServerConstants.getHostName(Host.API)
394             });
395             sch.addServlet(new ServletHolder(new GigiAPI()), "/*");
396             return sch;
397         }
398
399         protected static Handler generateOCSPContext() {
400             ServletContextHandler sch = new ServletContextHandler();
401
402             sch.addVirtualHosts(new String[] {
403                     ServerConstants.getHostName(Host.OCSP_RESPONDER)
404             });
405             sch.addServlet(new ServletHolder(new OCSPResponder()), "/*");
406             return sch;
407         }
408     }
409
410 }