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.util.CipherInfo;
62 import club.wpia.gigi.util.PEM;
63 import club.wpia.gigi.util.ServerConstants;
64 import club.wpia.gigi.util.ServerConstants.Host;
66 public class Launcher {
68 class ExtendedForwarded implements Customizer {
71 public void customize(Connector connector, HttpConfiguration config, Request request) {
72 HttpFields httpFields = request.getHttpFields();
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)) {
84 X509Certificate[] certs = new X509Certificate[1];
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) {
93 String[] parts = ip.split(":");
94 if (parts.length == 2) {
95 request.setRemoteAddr(InetSocketAddress.createUnresolved(parts[0], Integer.parseInt(parts[1])));
102 public static void main(String[] args) throws Exception {
103 System.setProperty("jdk.tls.ephemeralDHKeySize", "4096");
105 if (args.length >= 1) {
106 in = new FileInputStream(new File(args[0]));
110 new Launcher().boot(in);
117 private boolean isSystemPort(int port) {
118 return 1 <= port && port <= 1024;
121 public synchronized void boot(InputStream in) throws Exception {
122 Locale.setDefault(Locale.ENGLISH);
123 TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
124 HttpURLConnection.setFollowRedirects(false);
126 conf = GigiConfig.parse(in);
127 ServerConstants.init(conf.getMainProps());
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));
140 int uid = Integer.parseInt(uid_s);
141 int gid = Integer.parseInt(gid_s);
142 if (uid == -1 && gid == -1) {
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());
150 Log.getLogger(Launcher.class).warn("Invalid uid or gid (must satisfy 0 < id < 65536)");
152 } catch (NumberFormatException e) {
153 Log.getLogger(Launcher.class).warn("Invalid gigi.uid or gigi.gid", e);
158 private HttpConfiguration createHttpConfiguration() {
159 // SSL HTTP Configuration
160 HttpConfiguration httpsConfig = new HttpConfiguration();
161 httpsConfig.setSendServerVersion(false);
162 httpsConfig.setSendXPoweredBy(false);
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)
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)
183 private void initEmails(GigiConfig conf) throws GeneralSecurityException, IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
184 KeyStore privateStore = conf.getPrivateStore();
185 Certificate mail = null;
187 if (privateStore != null && privateStore.containsAlias("mail")) {
188 mail = privateStore.getCertificate("mail");
189 k = privateStore.getKey("mail", conf.getPrivateStorePw().toCharArray());
191 EmailProvider.initSystem(conf.getMainProps(), mail, k);
194 private static class ConnectorsLauncher {
196 private ConnectorsLauncher() {}
198 protected static ServerConnector createConnector(GigiConfig conf, Server s, HttpConfiguration httpConfig, boolean doHttps) throws GeneralSecurityException, IOException {
199 ServerConnector connector;
202 connector = new ServerConnector(s, createConnectionFactory(conf), new HttpConnectionFactory(httpConfig));
203 port = ServerConstants.getSecurePort();
205 connector = new ServerConnector(s, new HttpConnectionFactory(httpConfig));
206 port = ServerConstants.getPort();
209 connector.setInheritChannel(true);
211 connector.setHost(conf.getMainProps().getProperty("host"));
212 connector.setPort(port);
214 connector.setAcceptQueueSize(100);
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);
227 secureContextFactory.start();
228 staticContextFactory.start();
229 apiContextFactory.start();
230 } catch (Exception e) {
233 return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()) {
236 public boolean shouldRestartSSL() {
241 public SSLEngine restartSSL(SSLSession sslSession) {
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();
264 e2 = sslContextFactory.newSSLEngine(sslSession.getPeerHost(), sslSession.getPeerPort());
266 e2.setUseClientMode(false);
272 private static SslContextFactory generateSSLContextFactory(GigiConfig conf, String alias) throws GeneralSecurityException, IOException {
273 SslContextFactory scf = new SslContextFactory() {
275 String[] ciphers = null;
278 public void customize(SSLEngine sslEngine) {
279 super.customize(sslEngine);
281 SSLParameters ssl = sslEngine.getSSLParameters();
282 ssl.setUseCipherSuitesOrder(true);
283 if (ciphers == null) {
284 ciphers = CipherInfo.filter(sslEngine.getSupportedCipherSuites());
287 ssl.setCipherSuites(ciphers);
288 sslEngine.setSSLParameters(ssl);
293 scf.setRenegotiationAllowed(false);
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);
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()
314 private static class ContextLauncher {
316 private ContextLauncher() {}
318 protected static Handler generateGigiContexts(Properties conf, KeyStore trust) {
319 ServletHolder webAppServlet = new ServletHolder(new Gigi(conf, trust));
321 ContextHandler ch = generateGigiServletContext(webAppServlet);
322 ch.setVirtualHosts(new String[] {
323 ServerConstants.getHostName(Host.WWW)
325 ContextHandler chSecure = generateGigiServletContext(webAppServlet);
326 chSecure.setVirtualHosts(new String[] {
327 ServerConstants.getHostName(Host.SECURE)
330 HandlerList hl = new HandlerList();
331 hl.setHandlers(new Handler[] {
337 private static ContextHandler generateGigiServletContext(ServletHolder webAppServlet) {
338 final ResourceHandler rh = generateResourceHandler();
339 rh.setResourceBase("static/www");
341 HandlerWrapper hw = new HandlerWrapper();
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);
352 HandlerList hl = new HandlerList();
353 hl.setHandlers(new Handler[] {
357 ContextHandler ch = new ContextHandler();
362 protected static Handler generateStaticContext() {
363 final ResourceHandler rh = generateResourceHandler();
364 rh.setResourceBase("static/static");
366 ContextHandler ch = new ContextHandler();
368 ch.setVirtualHosts(new String[] {
369 ServerConstants.getHostName(Host.STATIC)
375 private static ResourceHandler generateResourceHandler() {
376 ResourceHandler rh = new ResourceHandler() {
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);
388 protected static Handler generateAPIContext() {
389 ServletContextHandler sch = new ServletContextHandler();
391 sch.addVirtualHosts(new String[] {
392 ServerConstants.getHostName(Host.API)
394 sch.addServlet(new ServletHolder(new GigiAPI()), "/*");