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