1 package club.wpia.gigi;
3 import java.io.ByteArrayInputStream;
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;
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.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;
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;
67 public class Launcher {
69 class ExtendedForwarded implements Customizer {
72 public void customize(Connector connector, HttpConfiguration config, Request request) {
73 HttpFields httpFields = request.getHttpFields();
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)) {
85 X509Certificate[] certs = new X509Certificate[1];
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) {
94 String[] parts = ip.split(":");
95 if (parts.length == 2) {
96 request.setRemoteAddr(InetSocketAddress.createUnresolved(parts[0], Integer.parseInt(parts[1])));
103 public static void main(String[] args) throws Exception {
104 System.setProperty("jdk.tls.ephemeralDHKeySize", "4096");
106 if (args.length >= 1) {
107 in = new FileInputStream(new File(args[0]));
111 new Launcher().boot(in);
118 private boolean isSystemPort(int port) {
119 return 1 <= port && port <= 1024;
122 public synchronized void boot(InputStream in) throws Exception {
123 Locale.setDefault(Locale.ENGLISH);
124 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
125 HttpURLConnection.setFollowRedirects(false);
127 conf = GigiConfig.parse(in);
128 ServerConstants.init(conf.getMainProps());
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));
141 int uid = Integer.parseInt(uid_s);
142 int gid = Integer.parseInt(gid_s);
143 if (uid == -1 && gid == -1) {
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());
151 Log.getLogger(Launcher.class).warn("Invalid uid or gid (must satisfy 0 < id < 65536)");
153 } catch (NumberFormatException e) {
154 Log.getLogger(Launcher.class).warn("Invalid gigi.uid or gigi.gid", e);
159 private HttpConfiguration createHttpConfiguration() {
160 // SSL HTTP Configuration
161 HttpConfiguration httpsConfig = new HttpConfiguration();
162 httpsConfig.setSendServerVersion(false);
163 httpsConfig.setSendXPoweredBy(false);
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)
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)
184 private void initEmails(GigiConfig conf) throws GeneralSecurityException, IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
185 KeyStore privateStore = conf.getPrivateStore();
186 Certificate mail = null;
188 if (privateStore != null && privateStore.containsAlias("mail")) {
189 mail = privateStore.getCertificate("mail");
190 k = privateStore.getKey("mail", conf.getPrivateStorePw().toCharArray());
192 EmailProvider.initSystem(conf.getMainProps(), mail, k);
195 private static class ConnectorsLauncher {
197 private ConnectorsLauncher() {}
199 protected static ServerConnector createConnector(GigiConfig conf, Server s, HttpConfiguration httpConfig, boolean doHttps) throws GeneralSecurityException, IOException {
200 ServerConnector connector;
203 connector = new ServerConnector(s, createConnectionFactory(conf), new HttpConnectionFactory(httpConfig));
204 port = ServerConstants.getSecurePort();
206 connector = new ServerConnector(s, new HttpConnectionFactory(httpConfig));
207 port = ServerConstants.getPort();
210 connector.setInheritChannel(true);
212 connector.setHost(conf.getMainProps().getProperty("host"));
213 connector.setPort(port);
215 connector.setAcceptQueueSize(100);
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);
228 secureContextFactory.start();
229 staticContextFactory.start();
230 apiContextFactory.start();
231 } catch (Exception e) {
234 return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()) {
237 public boolean shouldRestartSSL() {
242 public SSLEngine restartSSL(SSLSession sslSession) {
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();
265 e2 = sslContextFactory.newSSLEngine(sslSession.getPeerHost(), sslSession.getPeerPort());
267 e2.setUseClientMode(false);
273 private static SslContextFactory generateSSLContextFactory(GigiConfig conf, String alias) throws GeneralSecurityException, IOException {
274 SslContextFactory scf = new SslContextFactory() {
276 String[] ciphers = null;
279 public void customize(SSLEngine sslEngine) {
280 super.customize(sslEngine);
282 SSLParameters ssl = sslEngine.getSSLParameters();
283 ssl.setUseCipherSuitesOrder(true);
284 if (ciphers == null) {
285 ciphers = CipherInfo.filter(sslEngine.getSupportedCipherSuites());
288 ssl.setCipherSuites(ciphers);
289 sslEngine.setSSLParameters(ssl);
294 scf.setRenegotiationAllowed(false);
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);
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()
315 private static class ContextLauncher {
317 private ContextLauncher() {}
319 protected static Handler generateGigiContexts(Properties conf, KeyStore trust) {
320 ServletHolder webAppServlet = new ServletHolder(new Gigi(conf, trust));
322 ContextHandler ch = generateGigiServletContext(webAppServlet);
323 ch.setVirtualHosts(new String[] {
324 ServerConstants.getHostName(Host.WWW)
326 ContextHandler chSecure = generateGigiServletContext(webAppServlet);
327 chSecure.setVirtualHosts(new String[] {
328 ServerConstants.getHostName(Host.SECURE)
331 HandlerList hl = new HandlerList();
332 hl.setHandlers(new Handler[] {
338 private static ContextHandler generateGigiServletContext(ServletHolder webAppServlet) {
339 final ResourceHandler rh = generateResourceHandler();
340 rh.setResourceBase("static/www");
342 HandlerWrapper hw = new HandlerWrapper();
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);
353 HandlerList hl = new HandlerList();
354 hl.setHandlers(new Handler[] {
358 ContextHandler ch = new ContextHandler();
363 protected static Handler generateStaticContext() {
364 final ResourceHandler rh = generateResourceHandler();
365 rh.setResourceBase("static/static");
367 ContextHandler ch = new ContextHandler();
369 ch.setVirtualHosts(new String[] {
370 ServerConstants.getHostName(Host.STATIC)
376 private static ResourceHandler generateResourceHandler() {
377 ResourceHandler rh = new ResourceHandler() {
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);
389 protected static Handler generateAPIContext() {
390 ServletContextHandler sch = new ServletContextHandler();
392 sch.addVirtualHosts(new String[] {
393 ServerConstants.getHostName(Host.API)
395 sch.addServlet(new ServletHolder(new GigiAPI()), "/*");
399 protected static Handler generateOCSPContext() {
400 ServletContextHandler sch = new ServletContextHandler();
402 sch.addVirtualHosts(new String[] {
403 ServerConstants.getHostName(Host.OCSP_RESPONDER)
405 sch.addServlet(new ServletHolder(new OCSPResponder()), "/*");