source: josm/trunk/src/org/openstreetmap/josm/io/remotecontrol/RemoteControlHttpsServer.java@ 8377

Last change on this file since 8377 was 8377, checked in by Don-vip, 9 years ago

performance - remove useless boxing of boolean constants

  • Property svn:eol-style set to native
File size: 18.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io.remotecontrol;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
5
6import java.io.IOException;
7import java.io.InputStream;
8import java.math.BigInteger;
9import java.net.ServerSocket;
10import java.net.Socket;
11import java.net.SocketException;
12import java.nio.file.Files;
13import java.nio.file.Path;
14import java.nio.file.Paths;
15import java.nio.file.StandardOpenOption;
16import java.security.GeneralSecurityException;
17import java.security.KeyPair;
18import java.security.KeyPairGenerator;
19import java.security.KeyStore;
20import java.security.KeyStoreException;
21import java.security.NoSuchAlgorithmException;
22import java.security.PrivateKey;
23import java.security.SecureRandom;
24import java.security.cert.Certificate;
25import java.security.cert.CertificateException;
26import java.security.cert.X509Certificate;
27import java.util.Arrays;
28import java.util.Date;
29import java.util.Enumeration;
30import java.util.Vector;
31
32import javax.net.ssl.KeyManagerFactory;
33import javax.net.ssl.SSLContext;
34import javax.net.ssl.SSLServerSocket;
35import javax.net.ssl.SSLServerSocketFactory;
36import javax.net.ssl.SSLSocket;
37import javax.net.ssl.TrustManagerFactory;
38
39import org.openstreetmap.josm.Main;
40import org.openstreetmap.josm.data.preferences.StringProperty;
41
42import sun.security.util.ObjectIdentifier;
43import sun.security.x509.AlgorithmId;
44import sun.security.x509.BasicConstraintsExtension;
45import sun.security.x509.CertificateAlgorithmId;
46import sun.security.x509.CertificateExtensions;
47import sun.security.x509.CertificateIssuerName;
48import sun.security.x509.CertificateSerialNumber;
49import sun.security.x509.CertificateSubjectName;
50import sun.security.x509.CertificateValidity;
51import sun.security.x509.CertificateVersion;
52import sun.security.x509.CertificateX509Key;
53import sun.security.x509.ExtendedKeyUsageExtension;
54import sun.security.x509.GeneralName;
55import sun.security.x509.GeneralNameInterface;
56import sun.security.x509.GeneralNames;
57import sun.security.x509.IPAddressName;
58import sun.security.x509.OIDName;
59import sun.security.x509.SubjectAlternativeNameExtension;
60import sun.security.x509.URIName;
61import sun.security.x509.X500Name;
62import sun.security.x509.X509CertImpl;
63import sun.security.x509.X509CertInfo;
64
65/**
66 * Simple HTTPS server that spawns a {@link RequestProcessor} for every secure connection.
67 *
68 * @since 6941
69 */
70public class RemoteControlHttpsServer extends Thread {
71
72 /** The server socket */
73 private ServerSocket server = null;
74
75 /** The server instance for IPv4 */
76 private static volatile RemoteControlHttpsServer instance4 = null;
77 /** The server instance for IPv6 */
78 private static volatile RemoteControlHttpsServer instance6 = null;
79
80 /** SSL context information for connections */
81 private SSLContext sslContext;
82
83 /* the default port for HTTPS remote control */
84 private static final int HTTPS_PORT = 8112;
85
86 /**
87 * JOSM keystore file name.
88 * @since 7337
89 */
90 public static final String KEYSTORE_FILENAME = "josm.keystore";
91
92 /**
93 * Preference for keystore password (automatically generated by JOSM).
94 * @since 7335
95 */
96 public static final StringProperty KEYSTORE_PASSWORD = new StringProperty("remotecontrol.https.keystore.password", "");
97
98 /**
99 * Preference for certificate password (automatically generated by JOSM).
100 * @since 7335
101 */
102 public static final StringProperty KEYENTRY_PASSWORD = new StringProperty("remotecontrol.https.keyentry.password", "");
103
104 /**
105 * Unique alias used to store JOSM localhost entry, both in JOSM keystore and system/browser keystores.
106 * @since 7343
107 */
108 public static final String ENTRY_ALIAS = "josm_localhost";
109
110 /**
111 * Creates a GeneralName object from known types.
112 * @param t one of 4 known types
113 * @param v value
114 * @return which one
115 * @throws IOException
116 */
117 private static GeneralName createGeneralName(String t, String v) throws IOException {
118 GeneralNameInterface gn;
119 switch (t.toLowerCase()) {
120 case "uri": gn = new URIName(v); break;
121 case "dns": gn = new DNSName(v); break;
122 case "ip": gn = new IPAddressName(v); break;
123 default: gn = new OIDName(v);
124 }
125 return new GeneralName(gn);
126 }
127
128 /**
129 * Create a self-signed X.509 Certificate.
130 * @param dn the X.509 Distinguished Name, eg "CN=localhost, OU=JOSM, O=OpenStreetMap"
131 * @param pair the KeyPair
132 * @param days how many days from now the Certificate is valid for
133 * @param algorithm the signing algorithm, eg "SHA256withRSA"
134 * @param san SubjectAlternativeName extension (optional)
135 */
136 private static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm, String san)
137 throws GeneralSecurityException, IOException {
138 PrivateKey privkey = pair.getPrivate();
139 X509CertInfo info = new X509CertInfo();
140 Date from = new Date();
141 Date to = new Date(from.getTime() + days * 86400000L);
142 CertificateValidity interval = new CertificateValidity(from, to);
143 BigInteger sn = new BigInteger(64, new SecureRandom());
144 X500Name owner = new X500Name(dn);
145
146 info.set(X509CertInfo.VALIDITY, interval);
147 info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
148
149 // Change of behaviour in JDK8:
150 // https://bugs.openjdk.java.net/browse/JDK-8040820
151 // https://bugs.openjdk.java.net/browse/JDK-7198416
152 if (!Main.isJava8orLater()) {
153 // Java 7 code. To remove with Java 8 migration
154 info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
155 info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
156 } else {
157 // Java 8 and later code
158 info.set(X509CertInfo.SUBJECT, owner);
159 info.set(X509CertInfo.ISSUER, owner);
160 }
161
162 info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
163 info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
164 AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
165 info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
166
167 CertificateExtensions ext = new CertificateExtensions();
168 // Critical: Not CA, max path len 0
169 ext.set(BasicConstraintsExtension.NAME, new BasicConstraintsExtension(Boolean.TRUE, false, 0));
170 // Critical: only allow TLS ("serverAuth" = 1.3.6.1.5.5.7.3.1)
171 ext.set(ExtendedKeyUsageExtension.NAME, new ExtendedKeyUsageExtension(Boolean.TRUE,
172 new Vector<ObjectIdentifier>(Arrays.asList(new ObjectIdentifier("1.3.6.1.5.5.7.3.1")))));
173
174 if (san != null) {
175 int colonpos;
176 String[] ps = san.split(",");
177 GeneralNames gnames = new GeneralNames();
178 for(String item: ps) {
179 colonpos = item.indexOf(':');
180 if (colonpos < 0) {
181 throw new IllegalArgumentException("Illegal item " + item + " in " + san);
182 }
183 String t = item.substring(0, colonpos);
184 String v = item.substring(colonpos+1);
185 gnames.add(createGeneralName(t, v));
186 }
187 // Non critical
188 ext.set(SubjectAlternativeNameExtension.NAME, new SubjectAlternativeNameExtension(Boolean.FALSE, gnames));
189 }
190
191 info.set(X509CertInfo.EXTENSIONS, ext);
192
193 // Sign the cert to identify the algorithm that's used.
194 X509CertImpl cert = new X509CertImpl(info);
195 cert.sign(privkey, algorithm);
196
197 // Update the algorithm, and resign.
198 algo = (AlgorithmId)cert.get(X509CertImpl.SIG_ALG);
199 info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
200 cert = new X509CertImpl(info);
201 cert.sign(privkey, algorithm);
202 return cert;
203 }
204
205 /**
206 * Setup the JOSM internal keystore, used to store HTTPS certificate and private key.
207 * @return Path to the (initialized) JOSM keystore
208 * @throws IOException if an I/O error occurs
209 * @throws GeneralSecurityException if a security error occurs
210 * @since 7343
211 */
212 public static Path setupJosmKeystore() throws IOException, GeneralSecurityException {
213
214 char[] storePassword = KEYSTORE_PASSWORD.get().toCharArray();
215 char[] entryPassword = KEYENTRY_PASSWORD.get().toCharArray();
216
217 Path dir = Paths.get(RemoteControl.getRemoteControlDir());
218 Path path = dir.resolve(KEYSTORE_FILENAME);
219 Files.createDirectories(dir);
220
221 if (!Files.exists(path)) {
222 Main.debug("No keystore found, creating a new one");
223
224 // Create new keystore like previous one generated with JDK keytool as follows:
225 // keytool -genkeypair -storepass josm_ssl -keypass josm_ssl -alias josm_localhost -dname "CN=localhost, OU=JOSM, O=OpenStreetMap"
226 // -ext san=ip:127.0.0.1 -keyalg RSA -validity 1825
227
228 KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
229 generator.initialize(2048);
230 KeyPair pair = generator.generateKeyPair();
231
232 X509Certificate cert = generateCertificate("CN=localhost, OU=JOSM, O=OpenStreetMap", pair, 1825, "SHA256withRSA",
233 // see #10033#comment:20: All browsers respect "ip" in SAN, except IE which only understands DNS entries:
234 // https://connect.microsoft.com/IE/feedback/details/814744/the-ie-doesnt-trust-a-san-certificate-when-connecting-to-ip-address
235 "dns:localhost,ip:127.0.0.1,dns:127.0.0.1,ip:::1,uri:https://127.0.0.1:"+HTTPS_PORT+",uri:https://::1:"+HTTPS_PORT);
236
237 KeyStore ks = KeyStore.getInstance("JKS");
238 ks.load(null, null);
239
240 // Generate new passwords. See https://stackoverflow.com/a/41156/2257172
241 SecureRandom random = new SecureRandom();
242 KEYSTORE_PASSWORD.put(new BigInteger(130, random).toString(32));
243 KEYENTRY_PASSWORD.put(new BigInteger(130, random).toString(32));
244
245 storePassword = KEYSTORE_PASSWORD.get().toCharArray();
246 entryPassword = KEYENTRY_PASSWORD.get().toCharArray();
247
248 ks.setKeyEntry(ENTRY_ALIAS, pair.getPrivate(), entryPassword, new Certificate[]{cert});
249 ks.store(Files.newOutputStream(path, StandardOpenOption.CREATE), storePassword);
250 }
251 return path;
252 }
253
254 /**
255 * Loads the JOSM keystore.
256 * @return the (initialized) JOSM keystore
257 * @throws IOException if an I/O error occurs
258 * @throws GeneralSecurityException if a security error occurs
259 * @since 7343
260 */
261 public static KeyStore loadJosmKeystore() throws IOException, GeneralSecurityException {
262 try (InputStream in = Files.newInputStream(setupJosmKeystore())) {
263 KeyStore ks = KeyStore.getInstance("JKS");
264 ks.load(in, KEYSTORE_PASSWORD.get().toCharArray());
265
266 if (Main.isDebugEnabled()) {
267 for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements();) {
268 Main.debug("Alias in JOSM keystore: "+aliases.nextElement());
269 }
270 }
271 return ks;
272 }
273 }
274
275 /**
276 * Initializes the TLS basics.
277 * @throws IOException if an I/O error occurs
278 * @throws GeneralSecurityException if a security error occurs
279 */
280 private void initialize() throws IOException, GeneralSecurityException {
281 KeyStore ks = loadJosmKeystore();
282
283 KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
284 kmf.init(ks, KEYENTRY_PASSWORD.get().toCharArray());
285
286 TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
287 tmf.init(ks);
288
289 sslContext = SSLContext.getInstance("TLS");
290 sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
291
292 if (Main.isTraceEnabled()) {
293 Main.trace("SSL Context protocol: " + sslContext.getProtocol());
294 Main.trace("SSL Context provider: " + sslContext.getProvider());
295 }
296
297 setupPlatform(ks);
298 }
299
300 /**
301 * Setup the platform-dependant certificate stuff.
302 * @param josmKs The JOSM keystore, containing localhost certificate and private key.
303 * @return {@code true} if something has changed as a result of the call (certificate installation, etc.)
304 * @throws KeyStoreException if the keystore has not been initialized (loaded)
305 * @throws NoSuchAlgorithmException in case of error
306 * @throws CertificateException in case of error
307 * @throws IOException in case of error
308 * @since 7343
309 */
310 public static boolean setupPlatform(KeyStore josmKs) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
311 Enumeration<String> aliases = josmKs.aliases();
312 if (aliases.hasMoreElements()) {
313 return Main.platform.setupHttpsCertificate(ENTRY_ALIAS,
314 new KeyStore.TrustedCertificateEntry(josmKs.getCertificate(aliases.nextElement())));
315 }
316 return false;
317 }
318
319 /**
320 * Starts or restarts the HTTPS server
321 */
322 public static void restartRemoteControlHttpsServer() {
323 stopRemoteControlHttpsServer();
324 if (RemoteControl.PROP_REMOTECONTROL_HTTPS_ENABLED.get()) {
325 int port = Main.pref.getInteger("remote.control.https.port", HTTPS_PORT);
326 try {
327 instance4 = new RemoteControlHttpsServer(port, false);
328 instance4.start();
329 } catch (Exception ex) {
330 Main.warn(marktr("Cannot start IPv4 remotecontrol https server on port {0}: {1}"),
331 Integer.toString(port), ex.getLocalizedMessage());
332 }
333 try {
334 instance6 = new RemoteControlHttpsServer(port, true);
335 instance6.start();
336 } catch (Exception ex) {
337 /* only show error when we also have no IPv4 */
338 if(instance4 == null) {
339 Main.warn(marktr("Cannot start IPv6 remotecontrol https server on port {0}: {1}"),
340 Integer.toString(port), ex.getLocalizedMessage());
341 }
342 }
343 }
344 }
345
346 /**
347 * Stops the HTTPS server
348 */
349 public static void stopRemoteControlHttpsServer() {
350 if (instance4 != null) {
351 try {
352 instance4.stopServer();
353 } catch (IOException ioe) {
354 Main.error(ioe);
355 }
356 instance4 = null;
357 }
358 if (instance6 != null) {
359 try {
360 instance6.stopServer();
361 } catch (IOException ioe) {
362 Main.error(ioe);
363 }
364 instance6 = null;
365 }
366 }
367
368 /**
369 * Constructs a new {@code RemoteControlHttpsServer}.
370 * @param port The port this server will listen on
371 * @param ipv6 Whether IPv6 or IPv4 server should be started
372 * @throws IOException when connection errors
373 * @throws NoSuchAlgorithmException if the JVM does not support TLS (can not happen)
374 * @throws GeneralSecurityException in case of SSL setup errors
375 * @since 8339
376 */
377 public RemoteControlHttpsServer(int port, boolean ipv6) throws IOException, NoSuchAlgorithmException, GeneralSecurityException {
378 super("RemoteControl HTTPS Server");
379 this.setDaemon(true);
380
381 initialize();
382
383 // Create SSL Server factory
384 SSLServerSocketFactory factory = sslContext.getServerSocketFactory();
385 if (Main.isTraceEnabled()) {
386 Main.trace("SSL factory - Supported Cipher suites: "+Arrays.toString(factory.getSupportedCipherSuites()));
387 }
388
389 this.server = factory.createServerSocket(port, 1, ipv6 ?
390 RemoteControl.getInet6Address() : RemoteControl.getInet4Address());
391
392 if (Main.isTraceEnabled()) {
393 if(server instanceof SSLServerSocket) {
394 SSLServerSocket sslServer = (SSLServerSocket) server;
395 Main.trace("SSL server - Enabled Cipher suites: "+Arrays.toString(sslServer.getEnabledCipherSuites()));
396 Main.trace("SSL server - Enabled Protocols: "+Arrays.toString(sslServer.getEnabledProtocols()));
397 Main.trace("SSL server - Enable Session Creation: "+sslServer.getEnableSessionCreation());
398 Main.trace("SSL server - Need Client Auth: "+sslServer.getNeedClientAuth());
399 Main.trace("SSL server - Want Client Auth: "+sslServer.getWantClientAuth());
400 Main.trace("SSL server - Use Client Mode: "+sslServer.getUseClientMode());
401 }
402 }
403 }
404
405 /**
406 * The main loop, spawns a {@link RequestProcessor} for each connection.
407 */
408 @Override
409 public void run() {
410 Main.info(marktr("RemoteControl::Accepting secure remote connections on {0}:{1}"),
411 server.getInetAddress(), Integer.toString(server.getLocalPort()));
412 while (true) {
413 try {
414 @SuppressWarnings("resource")
415 Socket request = server.accept();
416 if (Main.isTraceEnabled() && request instanceof SSLSocket) {
417 SSLSocket sslSocket = (SSLSocket) request;
418 Main.trace("SSL socket - Enabled Cipher suites: "+Arrays.toString(sslSocket.getEnabledCipherSuites()));
419 Main.trace("SSL socket - Enabled Protocols: "+Arrays.toString(sslSocket.getEnabledProtocols()));
420 Main.trace("SSL socket - Enable Session Creation: "+sslSocket.getEnableSessionCreation());
421 Main.trace("SSL socket - Need Client Auth: "+sslSocket.getNeedClientAuth());
422 Main.trace("SSL socket - Want Client Auth: "+sslSocket.getWantClientAuth());
423 Main.trace("SSL socket - Use Client Mode: "+sslSocket.getUseClientMode());
424 Main.trace("SSL socket - Session: "+sslSocket.getSession());
425 }
426 RequestProcessor.processRequest(request);
427 } catch (SocketException se) {
428 if (!server.isClosed()) {
429 Main.error(se);
430 }
431 } catch (IOException ioe) {
432 Main.error(ioe);
433 }
434 }
435 }
436
437 /**
438 * Stops the HTTPS server.
439 *
440 * @throws IOException if any I/O error occurs
441 */
442 public void stopServer() throws IOException {
443 Main.info(marktr("RemoteControl::Server {0}:{1} stopped."),
444 server.getInetAddress(), Integer.toString(server.getLocalPort()));
445 server.close();
446 }
447}
Note: See TracBrowser for help on using the repository browser.