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

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

see #10230, see #10033 - add "Install/uninstall certificate" buttons in remote control preferences (Windows only)

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