ConnectorBootstrap.java 41.6 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29 30 31
 */

package sun.management.jmxremote;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
32
import java.io.InputStream;
33
import sun.misc.ObjectInputFilter;
34
import java.lang.management.ManagementFactory;
D
duke 已提交
35 36
import java.net.InetAddress;
import java.net.MalformedURLException;
37 38
import java.net.Socket;
import java.net.ServerSocket;
D
duke 已提交
39 40 41 42 43 44 45
import java.net.UnknownHostException;
import java.rmi.NoSuchObjectException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMIServerSocketFactory;
46
import java.rmi.server.RemoteObject;
D
duke 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
import java.rmi.server.UnicastRemoteObject;
import java.security.KeyStore;
import java.security.Principal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;

import javax.management.MBeanServer;
import javax.management.remote.JMXAuthenticator;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.rmi.RMIConnectorServer;
63 64
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
65 66
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
67
import javax.net.ssl.TrustManagerFactory;
D
duke 已提交
68 69 70 71
import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.rmi.ssl.SslRMIServerSocketFactory;
import javax.security.auth.Subject;

72 73 74
import com.sun.jmx.remote.internal.RMIExporter;
import com.sun.jmx.remote.security.JMXPluggableAuthenticator;
import com.sun.jmx.remote.util.ClassLogger;
S
sjiang 已提交
75
import com.sun.jmx.remote.util.EnvHelp;
D
duke 已提交
76 77 78 79

import sun.management.Agent;
import sun.management.AgentConfigurationError;
import static sun.management.AgentConfigurationError.*;
80
import sun.management.ConnectorAddressLink;
D
duke 已提交
81
import sun.management.FileSystem;
82 83 84
import sun.rmi.server.UnicastRef;
import sun.rmi.server.UnicastServerRef;
import sun.rmi.server.UnicastServerRef2;
85
import sun.rmi.transport.LiveRef;
D
duke 已提交
86 87 88 89 90 91 92 93 94 95 96

/**
 * This class initializes and starts the RMIConnectorServer for JSR 163
 * JMX Monitoring.
 **/
public final class ConnectorBootstrap {

    /**
     * Default values for JMX configuration properties.
     **/
    public static interface DefaultValues {
97 98 99 100

        public static final String PORT = "0";
        public static final String CONFIG_FILE_NAME = "management.properties";
        public static final String USE_SSL = "true";
101
        public static final String USE_LOCAL_ONLY = "true";
102 103 104 105 106
        public static final String USE_REGISTRY_SSL = "false";
        public static final String USE_AUTHENTICATION = "true";
        public static final String PASSWORD_FILE_NAME = "jmxremote.password";
        public static final String ACCESS_FILE_NAME = "jmxremote.access";
        public static final String SSL_NEED_CLIENT_AUTH = "false";
D
duke 已提交
107 108 109 110 111 112
    }

    /**
     * Names of JMX configuration properties.
     **/
    public static interface PropertyNames {
113

D
duke 已提交
114 115
        public static final String PORT =
                "com.sun.management.jmxremote.port";
116 117
        public static final String HOST =
                "com.sun.management.jmxremote.host";
118 119
        public static final String RMI_PORT =
                "com.sun.management.jmxremote.rmi.port";
D
duke 已提交
120 121
        public static final String CONFIG_FILE_NAME =
                "com.sun.management.config.file";
122 123
        public static final String USE_LOCAL_ONLY =
                "com.sun.management.jmxremote.local.only";
D
duke 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
        public static final String USE_SSL =
                "com.sun.management.jmxremote.ssl";
        public static final String USE_REGISTRY_SSL =
                "com.sun.management.jmxremote.registry.ssl";
        public static final String USE_AUTHENTICATION =
                "com.sun.management.jmxremote.authenticate";
        public static final String PASSWORD_FILE_NAME =
                "com.sun.management.jmxremote.password.file";
        public static final String ACCESS_FILE_NAME =
                "com.sun.management.jmxremote.access.file";
        public static final String LOGIN_CONFIG_NAME =
                "com.sun.management.jmxremote.login.config";
        public static final String SSL_ENABLED_CIPHER_SUITES =
                "com.sun.management.jmxremote.ssl.enabled.cipher.suites";
        public static final String SSL_ENABLED_PROTOCOLS =
                "com.sun.management.jmxremote.ssl.enabled.protocols";
        public static final String SSL_NEED_CLIENT_AUTH =
                "com.sun.management.jmxremote.ssl.need.client.auth";
        public static final String SSL_CONFIG_FILE_NAME =
                "com.sun.management.jmxremote.ssl.config.file";
144 145
        public static final String SERIAL_FILTER_PATTERN =
                "com.sun.management.jmxremote.serial.filter.pattern";
D
duke 已提交
146 147
    }

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    /**
     * JMXConnectorServer associated data.
     */
    private static class JMXConnectorServerData {

        public JMXConnectorServerData(
                JMXConnectorServer jmxConnectorServer,
                JMXServiceURL jmxRemoteURL) {
            this.jmxConnectorServer = jmxConnectorServer;
            this.jmxRemoteURL = jmxRemoteURL;
        }
        JMXConnectorServer jmxConnectorServer;
        JMXServiceURL jmxRemoteURL;
    }

D
duke 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    /**
     * <p>Prevents our RMI server objects from keeping the JVM alive.</p>
     *
     * <p>We use a private interface in Sun's JMX Remote API implementation
     * that allows us to specify how to export RMI objects.  We do so using
     * UnicastServerRef, a class in Sun's RMI implementation.  This is all
     * non-portable, of course, so this is only valid because we are inside
     * Sun's JRE.</p>
     *
     * <p>Objects are exported using {@link
     * UnicastServerRef#exportObject(Remote, Object, boolean)}.  The
     * boolean parameter is called <code>permanent</code> and means
     * both that the object is not eligible for Distributed Garbage
     * Collection, and that its continued existence will not prevent
     * the JVM from exiting.  It is the latter semantics we want (we
     * already have the former because of the way the JMX Remote API
     * works).  Hence the somewhat misleading name of this class.</p>
     */
    private static class PermanentExporter implements RMIExporter {
182

D
duke 已提交
183 184 185
        public Remote exportObject(Remote obj,
                int port,
                RMIClientSocketFactory csf,
186 187
                RMIServerSocketFactory ssf,
                ObjectInputFilter filter)
D
duke 已提交
188 189 190
                throws RemoteException {

            synchronized (this) {
191
                if (firstExported == null) {
D
duke 已提交
192
                    firstExported = obj;
193
                }
D
duke 已提交
194 195 196
            }

            final UnicastServerRef ref;
197
            if (csf == null && ssf == null) {
198
                ref = new UnicastServerRef(new LiveRef(port), filter);
199
            } else {
200
                ref = new UnicastServerRef2(port, csf, ssf, filter);
201
            }
D
duke 已提交
202 203 204 205 206
            return ref.exportObject(obj, null, true);
        }

        // Nothing special to be done for this case
        public boolean unexportObject(Remote obj, boolean force)
207
                throws NoSuchObjectException {
D
duke 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
            return UnicastRemoteObject.unexportObject(obj, force);
        }
        Remote firstExported;
    }

    /**
     * This JMXAuthenticator wraps the JMXPluggableAuthenticator and verifies
     * that at least one of the principal names contained in the authenticated
     * Subject is present in the access file.
     */
    private static class AccessFileCheckerAuthenticator
            implements JMXAuthenticator {

        public AccessFileCheckerAuthenticator(Map<String, Object> env) throws IOException {
            environment = env;
            accessFile = (String) env.get("jmx.remote.x.access.file");
            properties = propertiesFromFile(accessFile);
        }

        public Subject authenticate(Object credentials) {
            final JMXAuthenticator authenticator =
                    new JMXPluggableAuthenticator(environment);
            final Subject subject = authenticator.authenticate(credentials);
            checkAccessFileEntries(subject);
            return subject;
        }

        private void checkAccessFileEntries(Subject subject) {
236
            if (subject == null) {
D
duke 已提交
237 238 239 240
                throw new SecurityException(
                        "Access denied! No matching entries found in " +
                        "the access file [" + accessFile + "] as the " +
                        "authenticated Subject is null");
241
            }
242
            final Set<Principal> principals = subject.getPrincipals();
243 244
            for (Principal p1: principals) {
                if (properties.containsKey(p1.getName())) {
D
duke 已提交
245
                    return;
246
                }
D
duke 已提交
247
            }
248 249 250 251

            final Set<String> principalsStr = new HashSet<>();
            for (Principal p2: principals) {
                principalsStr.add(p2.getName());
D
duke 已提交
252 253 254 255 256 257 258 259
            }
            throw new SecurityException(
                    "Access denied! No entries found in the access file [" +
                    accessFile + "] for any of the authenticated identities " +
                    principalsStr);
        }

        private static Properties propertiesFromFile(String fname)
260
                throws IOException {
D
duke 已提交
261
            Properties p = new Properties();
262
            if (fname == null) {
D
duke 已提交
263
                return p;
264
            }
265 266 267
            try (FileInputStream fin = new FileInputStream(fname)) {
                p.load(fin);
            }
D
duke 已提交
268 269 270 271 272 273 274
            return p;
        }
        private final Map<String, Object> environment;
        private final Properties properties;
        private final String accessFile;
    }

275 276 277 278
    // The variable below is here to support stop functionality
    // It would be overriten if you call startRemoteCommectionServer second
    // time. It's OK for now as logic in Agent.java forbids mutiple agents
    private static Registry registry = null;
D
duke 已提交
279

280 281 282 283 284 285 286 287 288 289 290
    public static void unexportRegistry() {
        // Remove the entry from registry
        try {
            if (registry != null) {
                UnicastRemoteObject.unexportObject(registry, true);
                registry = null;
            }
        } catch(NoSuchObjectException ex) {
            // This exception can appears only if we attempt
            // to unexportRegistry second time. So it's safe
            // to ignore it without additional messages.
291
        }
292
    }
D
duke 已提交
293

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
     /**
      * Initializes and starts the JMX Connector Server.
      * If the com.sun.management.jmxremote.port property is not defined,
      * simply return. Otherwise, attempts to load the config file, and
      * then calls {@link #startRemoteConnectorServer
      *                            (java.lang.String, java.util.Properties)}.
      *
      * This method is used by some jtreg tests.
      **/
      public static synchronized JMXConnectorServer initialize() {

         // Load a new management properties
         final Properties props = Agent.loadManagementProperties();
         if (props == null) {
              return null;
         }

         final String portStr = props.getProperty(PropertyNames.PORT);
         return startRemoteConnectorServer(portStr, props);
     }
D
duke 已提交
314

315 316 317 318 319 320 321 322
    /**
     * This method is used by some jtreg tests.
     *
     * @see #startRemoteConnectorServer
     *             (String portStr, Properties props)
     */
    public static synchronized JMXConnectorServer initialize(String portStr, Properties props)  {
         return startRemoteConnectorServer(portStr, props);
D
duke 已提交
323 324 325 326 327 328
    }

    /**
     * Initializes and starts a JMX Connector Server for remote
     * monitoring and management.
     **/
329
    public static synchronized JMXConnectorServer startRemoteConnectorServer(String portStr, Properties props) {
D
duke 已提交
330 331 332 333 334 335 336 337 338 339 340 341

        // Get port number
        final int port;
        try {
            port = Integer.parseInt(portStr);
        } catch (NumberFormatException x) {
            throw new AgentConfigurationError(INVALID_JMXREMOTE_PORT, x, portStr);
        }
        if (port < 0) {
            throw new AgentConfigurationError(INVALID_JMXREMOTE_PORT, portStr);
        }

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
        // User can specify a port to be used to export rmi object,
        // in order to simplify firewall rules
        // if port is not specified random one will be allocated.
        int rmiPort = 0;
        String rmiPortStr = props.getProperty(PropertyNames.RMI_PORT);
        try {
            if (rmiPortStr != null) {
               rmiPort = Integer.parseInt(rmiPortStr);
            }
        } catch (NumberFormatException x) {
            throw new AgentConfigurationError(INVALID_JMXREMOTE_RMI_PORT, x, rmiPortStr);
        }
        if (rmiPort < 0) {
            throw new AgentConfigurationError(INVALID_JMXREMOTE_RMI_PORT, rmiPortStr);
        }

D
duke 已提交
358
        // Do we use authentication?
359
        final String useAuthenticationStr =
D
duke 已提交
360 361 362 363 364 365
                props.getProperty(PropertyNames.USE_AUTHENTICATION,
                DefaultValues.USE_AUTHENTICATION);
        final boolean useAuthentication =
                Boolean.valueOf(useAuthenticationStr).booleanValue();

        // Do we use SSL?
366
        final String useSslStr =
D
duke 已提交
367 368 369 370 371 372
                props.getProperty(PropertyNames.USE_SSL,
                DefaultValues.USE_SSL);
        final boolean useSsl =
                Boolean.valueOf(useSslStr).booleanValue();

        // Do we use RMI Registry SSL?
373
        final String useRegistrySslStr =
D
duke 已提交
374 375 376 377 378 379 380 381 382 383 384 385
                props.getProperty(PropertyNames.USE_REGISTRY_SSL,
                DefaultValues.USE_REGISTRY_SSL);
        final boolean useRegistrySsl =
                Boolean.valueOf(useRegistrySslStr).booleanValue();

        final String enabledCipherSuites =
                props.getProperty(PropertyNames.SSL_ENABLED_CIPHER_SUITES);
        String enabledCipherSuitesList[] = null;
        if (enabledCipherSuites != null) {
            StringTokenizer st = new StringTokenizer(enabledCipherSuites, ",");
            int tokens = st.countTokens();
            enabledCipherSuitesList = new String[tokens];
386
            for (int i = 0; i < tokens; i++) {
D
duke 已提交
387 388 389 390 391 392 393 394 395 396 397
                enabledCipherSuitesList[i] = st.nextToken();
            }
        }

        final String enabledProtocols =
                props.getProperty(PropertyNames.SSL_ENABLED_PROTOCOLS);
        String enabledProtocolsList[] = null;
        if (enabledProtocols != null) {
            StringTokenizer st = new StringTokenizer(enabledProtocols, ",");
            int tokens = st.countTokens();
            enabledProtocolsList = new String[tokens];
398
            for (int i = 0; i < tokens; i++) {
D
duke 已提交
399 400 401 402
                enabledProtocolsList[i] = st.nextToken();
            }
        }

403
        final String sslNeedClientAuthStr =
D
duke 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
                props.getProperty(PropertyNames.SSL_NEED_CLIENT_AUTH,
                DefaultValues.SSL_NEED_CLIENT_AUTH);
        final boolean sslNeedClientAuth =
                Boolean.valueOf(sslNeedClientAuthStr).booleanValue();

        // Read SSL config file name
        final String sslConfigFileName =
                props.getProperty(PropertyNames.SSL_CONFIG_FILE_NAME);

        String loginConfigName = null;
        String passwordFileName = null;
        String accessFileName = null;

        // Initialize settings when authentication is active
        if (useAuthentication) {

            // Get non-default login configuration
            loginConfigName =
                    props.getProperty(PropertyNames.LOGIN_CONFIG_NAME);

            if (loginConfigName == null) {
                // Get password file
                passwordFileName =
                        props.getProperty(PropertyNames.PASSWORD_FILE_NAME,
                        getDefaultFileName(DefaultValues.PASSWORD_FILE_NAME));
                checkPasswordFile(passwordFileName);
            }

            // Get access file
            accessFileName = props.getProperty(PropertyNames.ACCESS_FILE_NAME,
                    getDefaultFileName(DefaultValues.ACCESS_FILE_NAME));
            checkAccessFile(accessFileName);
        }

438 439
        final String bindAddress =
                props.getProperty(PropertyNames.HOST);
440
        final String jmxRmiFilter = props.getProperty(PropertyNames.SERIAL_FILTER_PATTERN);
441

442
        if (log.debugOn()) {
443 444
            log.debug("startRemoteConnectorServer",
                    Agent.getText("jmxremote.ConnectorBootstrap.starting") +
D
duke 已提交
445
                    "\n\t" + PropertyNames.PORT + "=" + port +
446
                    (bindAddress == null ? "" : "\n\t" + PropertyNames.HOST + "=" + bindAddress) +
447
                    "\n\t" + PropertyNames.RMI_PORT + "=" + rmiPort +
D
duke 已提交
448 449 450 451 452 453 454 455 456 457 458
                    "\n\t" + PropertyNames.USE_SSL + "=" + useSsl +
                    "\n\t" + PropertyNames.USE_REGISTRY_SSL + "=" + useRegistrySsl +
                    "\n\t" + PropertyNames.SSL_CONFIG_FILE_NAME + "=" + sslConfigFileName +
                    "\n\t" + PropertyNames.SSL_ENABLED_CIPHER_SUITES + "=" +
                    enabledCipherSuites +
                    "\n\t" + PropertyNames.SSL_ENABLED_PROTOCOLS + "=" +
                    enabledProtocols +
                    "\n\t" + PropertyNames.SSL_NEED_CLIENT_AUTH + "=" +
                    sslNeedClientAuth +
                    "\n\t" + PropertyNames.USE_AUTHENTICATION + "=" +
                    useAuthentication +
459 460
                    (useAuthentication ? (loginConfigName == null ? ("\n\t" + PropertyNames.PASSWORD_FILE_NAME + "=" +
                    passwordFileName) : ("\n\t" + PropertyNames.LOGIN_CONFIG_NAME + "=" +
D
duke 已提交
461
                    loginConfigName)) : "\n\t" +
462
                    Agent.getText("jmxremote.ConnectorBootstrap.noAuthentication")) +
463
                    (useAuthentication ? ("\n\t" + PropertyNames.ACCESS_FILE_NAME + "=" +
D
duke 已提交
464 465 466 467 468 469
                    accessFileName) : "") +
                    "");
        }

        final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        JMXConnectorServer cs = null;
470
        JMXServiceURL url = null;
D
duke 已提交
471
        try {
472
            final JMXConnectorServerData data = exportMBeanServer(
473
                    mbs, port, rmiPort, useSsl, useRegistrySsl,
D
duke 已提交
474 475 476
                    sslConfigFileName, enabledCipherSuitesList,
                    enabledProtocolsList, sslNeedClientAuth,
                    useAuthentication, loginConfigName,
477
                    passwordFileName, accessFileName, bindAddress, jmxRmiFilter);
478 479
            cs = data.jmxConnectorServer;
            url = data.jmxRemoteURL;
480 481
            log.config("startRemoteConnectorServer",
                    Agent.getText("jmxremote.ConnectorBootstrap.ready",
482
                    url.toString()));
D
duke 已提交
483 484 485
        } catch (Exception e) {
            throw new AgentConfigurationError(AGENT_EXCEPTION, e, e.toString());
        }
486 487 488
        try {
            // Export remote connector address and associated configuration
            // properties to the instrumentation buffer.
489
            Map<String, String> properties = new HashMap<>();
490 491 492 493 494 495 496 497 498 499
            properties.put("remoteAddress", url.toString());
            properties.put("authenticate", useAuthenticationStr);
            properties.put("ssl", useSslStr);
            properties.put("sslRegistry", useRegistrySslStr);
            properties.put("sslNeedClientAuth", sslNeedClientAuthStr);
            ConnectorAddressLink.exportRemote(properties);
        } catch (Exception e) {
            // Remote connector server started but unable to export remote
            // connector address and associated configuration properties to
            // the instrumentation buffer - non-fatal error.
500
            log.debug("startRemoteConnectorServer", e);
501
        }
D
duke 已提交
502 503 504 505 506 507 508 509 510 511 512 513 514
        return cs;
    }

    /*
     * Creates and starts a RMI Connector Server for "local" monitoring
     * and management.
     */
    public static JMXConnectorServer startLocalConnectorServer() {
        // Ensure cryptographically strong random number generater used
        // to choose the object number - see java.rmi.server.ObjID
        System.setProperty("java.rmi.server.randomIDs", "true");

        // This RMI server should not keep the VM alive
515
        Map<String, Object> env = new HashMap<>();
D
duke 已提交
516
        env.put(RMIExporter.EXPORTER_ATTRIBUTE, new PermanentExporter());
517
        env.put(EnvHelp.CREDENTIALS_FILTER_PATTERN, String.class.getName() + ";!*");
D
duke 已提交
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537

        // The local connector server need only be available via the
        // loopback connection.
        String localhost = "localhost";
        InetAddress lh = null;
        try {
            lh = InetAddress.getByName(localhost);
            localhost = lh.getHostAddress();
        } catch (UnknownHostException x) {
        }

        // localhost unknown or (somehow) didn't resolve to
        // a loopback address.
        if (lh == null || !lh.isLoopbackAddress()) {
            localhost = "127.0.0.1";
        }

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        try {
            JMXServiceURL url = new JMXServiceURL("rmi", localhost, 0);
538 539 540 541 542 543 544 545 546 547 548 549
            // Do we accept connections from local interfaces only?
            Properties props = Agent.getManagementProperties();
            if (props ==  null) {
                props = new Properties();
            }
            String useLocalOnlyStr = props.getProperty(
                    PropertyNames.USE_LOCAL_ONLY, DefaultValues.USE_LOCAL_ONLY);
            boolean useLocalOnly = Boolean.valueOf(useLocalOnlyStr).booleanValue();
            if (useLocalOnly) {
                env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE,
                        new LocalRMIServerSocketFactory());
            }
D
duke 已提交
550 551 552 553 554 555 556 557 558 559
            JMXConnectorServer server =
                    JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
            server.start();
            return server;
        } catch (Exception e) {
            throw new AgentConfigurationError(AGENT_EXCEPTION, e, e.toString());
        }
    }

    private static void checkPasswordFile(String passwordFileName) {
560
        if (passwordFileName == null || passwordFileName.length() == 0) {
D
duke 已提交
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
            throw new AgentConfigurationError(PASSWORD_FILE_NOT_SET);
        }
        File file = new File(passwordFileName);
        if (!file.exists()) {
            throw new AgentConfigurationError(PASSWORD_FILE_NOT_FOUND, passwordFileName);
        }

        if (!file.canRead()) {
            throw new AgentConfigurationError(PASSWORD_FILE_NOT_READABLE, passwordFileName);
        }

        FileSystem fs = FileSystem.open();
        try {
            if (fs.supportsFileSecurity(file)) {
                if (!fs.isAccessUserOnly(file)) {
576
                    final String msg = Agent.getText("jmxremote.ConnectorBootstrap.password.readonly",
D
duke 已提交
577
                            passwordFileName);
578
                    log.config("startRemoteConnectorServer", msg);
D
duke 已提交
579 580 581 582 583 584 585 586 587 588 589
                    throw new AgentConfigurationError(PASSWORD_FILE_ACCESS_NOT_RESTRICTED,
                            passwordFileName);
                }
            }
        } catch (IOException e) {
            throw new AgentConfigurationError(PASSWORD_FILE_READ_FAILED,
                    e, passwordFileName);
        }
    }

    private static void checkAccessFile(String accessFileName) {
590
        if (accessFileName == null || accessFileName.length() == 0) {
D
duke 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
            throw new AgentConfigurationError(ACCESS_FILE_NOT_SET);
        }
        File file = new File(accessFileName);
        if (!file.exists()) {
            throw new AgentConfigurationError(ACCESS_FILE_NOT_FOUND, accessFileName);
        }

        if (!file.canRead()) {
            throw new AgentConfigurationError(ACCESS_FILE_NOT_READABLE, accessFileName);
        }
    }

    private static void checkRestrictedFile(String restrictedFileName) {
        if (restrictedFileName == null || restrictedFileName.length() == 0) {
            throw new AgentConfigurationError(FILE_NOT_SET);
        }
        File file = new File(restrictedFileName);
        if (!file.exists()) {
            throw new AgentConfigurationError(FILE_NOT_FOUND, restrictedFileName);
        }
        if (!file.canRead()) {
            throw new AgentConfigurationError(FILE_NOT_READABLE, restrictedFileName);
        }
        FileSystem fs = FileSystem.open();
        try {
            if (fs.supportsFileSecurity(file)) {
                if (!fs.isAccessUserOnly(file)) {
                    final String msg = Agent.getText(
619
                            "jmxremote.ConnectorBootstrap.file.readonly",
D
duke 已提交
620
                            restrictedFileName);
621
                    log.config("startRemoteConnectorServer", msg);
D
duke 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
                    throw new AgentConfigurationError(
                            FILE_ACCESS_NOT_RESTRICTED, restrictedFileName);
                }
            }
        } catch (IOException e) {
            throw new AgentConfigurationError(
                    FILE_READ_FAILED, e, restrictedFileName);
        }
    }

    /**
     * Compute the full path name for a default file.
     * @param basename basename (with extension) of the default file.
     * @return ${JRE}/lib/management/${basename}
     **/
    private static String getDefaultFileName(String basename) {
        final String fileSeparator = File.separator;
        return System.getProperty("java.home") + fileSeparator + "lib" +
                fileSeparator + "management" + fileSeparator +
                basename;
    }

    private static SslRMIServerSocketFactory createSslRMIServerSocketFactory(
            String sslConfigFileName,
            String[] enabledCipherSuites,
            String[] enabledProtocols,
648 649
            boolean sslNeedClientAuth,
            String bindAddress) {
D
duke 已提交
650
        if (sslConfigFileName == null) {
651
            return new HostAwareSslSocketFactory(
D
duke 已提交
652 653
                    enabledCipherSuites,
                    enabledProtocols,
654
                    sslNeedClientAuth, bindAddress);
D
duke 已提交
655 656 657 658 659
        } else {
            checkRestrictedFile(sslConfigFileName);
            try {
                // Load the SSL keystore properties from the config file
                Properties p = new Properties();
660
                try (InputStream in = new FileInputStream(sslConfigFileName)) {
D
duke 已提交
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
                    BufferedInputStream bin = new BufferedInputStream(in);
                    p.load(bin);
                }
                String keyStore =
                        p.getProperty("javax.net.ssl.keyStore");
                String keyStorePassword =
                        p.getProperty("javax.net.ssl.keyStorePassword", "");
                String trustStore =
                        p.getProperty("javax.net.ssl.trustStore");
                String trustStorePassword =
                        p.getProperty("javax.net.ssl.trustStorePassword", "");

                char[] keyStorePasswd = null;
                if (keyStorePassword.length() != 0) {
                    keyStorePasswd = keyStorePassword.toCharArray();
                }

                char[] trustStorePasswd = null;
                if (trustStorePassword.length() != 0) {
                    trustStorePasswd = trustStorePassword.toCharArray();
                }

                KeyStore ks = null;
                if (keyStore != null) {
                    ks = KeyStore.getInstance(KeyStore.getDefaultType());
686
                    try (FileInputStream ksfis = new FileInputStream(keyStore)) {
D
duke 已提交
687 688 689 690 691 692 693 694 695 696
                        ks.load(ksfis, keyStorePasswd);
                    }
                }
                KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                        KeyManagerFactory.getDefaultAlgorithm());
                kmf.init(ks, keyStorePasswd);

                KeyStore ts = null;
                if (trustStore != null) {
                    ts = KeyStore.getInstance(KeyStore.getDefaultType());
697
                    try (FileInputStream tsfis = new FileInputStream(trustStore)) {
D
duke 已提交
698 699 700 701 702
                        ts.load(tsfis, trustStorePasswd);
                    }
                }
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                        TrustManagerFactory.getDefaultAlgorithm());
703
                tmf.init(ts);
D
duke 已提交
704 705 706 707

                SSLContext ctx = SSLContext.getInstance("SSL");
                ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

708
                return new HostAwareSslSocketFactory(
D
duke 已提交
709 710 711
                        ctx,
                        enabledCipherSuites,
                        enabledProtocols,
712
                        sslNeedClientAuth, bindAddress);
D
duke 已提交
713 714 715 716 717 718
            } catch (Exception e) {
                throw new AgentConfigurationError(AGENT_EXCEPTION, e, e.toString());
            }
        }
    }

719
    private static JMXConnectorServerData exportMBeanServer(
D
duke 已提交
720 721
            MBeanServer mbs,
            int port,
722
            int rmiPort,
D
duke 已提交
723 724 725 726 727 728 729 730 731
            boolean useSsl,
            boolean useRegistrySsl,
            String sslConfigFileName,
            String[] enabledCipherSuites,
            String[] enabledProtocols,
            boolean sslNeedClientAuth,
            boolean useAuthentication,
            String loginConfigName,
            String passwordFileName,
732
            String accessFileName,
733 734
            String bindAddress,
            String jmxRmiFilter)
D
duke 已提交
735 736 737 738 739 740 741
            throws IOException, MalformedURLException {

        /* Make sure we use non-guessable RMI object IDs.  Otherwise
         * attackers could hijack open connections by guessing their
         * IDs.  */
        System.setProperty("java.rmi.server.randomIDs", "true");

742
        JMXServiceURL url = new JMXServiceURL("rmi", bindAddress, rmiPort);
D
duke 已提交
743

744
        Map<String, Object> env = new HashMap<>();
D
duke 已提交
745 746 747 748

        PermanentExporter exporter = new PermanentExporter();

        env.put(RMIExporter.EXPORTER_ATTRIBUTE, exporter);
749 750 751 752 753
        env.put(EnvHelp.CREDENTIALS_FILTER_PATTERN, String.class.getName() + ";!*");

        if(jmxRmiFilter != null && !jmxRmiFilter.isEmpty()) {
            env.put(EnvHelp.SERIAL_FILTER_PATTERN, jmxRmiFilter);
        }
D
duke 已提交
754

755 756
        boolean useSocketFactory = bindAddress != null && !useSsl;

D
duke 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
        if (useAuthentication) {
            if (loginConfigName != null) {
                env.put("jmx.remote.x.login.config", loginConfigName);
            }
            if (passwordFileName != null) {
                env.put("jmx.remote.x.password.file", passwordFileName);
            }

            env.put("jmx.remote.x.access.file", accessFileName);

            if (env.get("jmx.remote.x.password.file") != null ||
                    env.get("jmx.remote.x.login.config") != null) {
                env.put(JMXConnectorServer.AUTHENTICATOR,
                        new AccessFileCheckerAuthenticator(env));
            }
        }

        RMIClientSocketFactory csf = null;
        RMIServerSocketFactory ssf = null;

        if (useSsl || useRegistrySsl) {
            csf = new SslRMIClientSocketFactory();
            ssf = createSslRMIServerSocketFactory(
                    sslConfigFileName, enabledCipherSuites,
781
                    enabledProtocols, sslNeedClientAuth, bindAddress);
D
duke 已提交
782 783 784 785 786 787 788 789 790
        }

        if (useSsl) {
            env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE,
                    csf);
            env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE,
                    ssf);
        }

791 792 793 794 795 796
        if (useSocketFactory) {
            ssf = new HostAwareSocketFactory(bindAddress);
            env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE,
                    ssf);
        }

D
duke 已提交
797 798 799 800 801 802
        JMXConnectorServer connServer = null;
        try {
            connServer =
                    JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
            connServer.start();
        } catch (IOException e) {
803
            if (connServer == null || connServer.getAddress() == null) {
D
duke 已提交
804 805 806 807 808 809 810 811
                throw new AgentConfigurationError(CONNECTOR_SERVER_IO_ERROR,
                        e, url.toString());
            } else {
                throw new AgentConfigurationError(CONNECTOR_SERVER_IO_ERROR,
                        e, connServer.getAddress().toString());
            }
        }

812
        if (useRegistrySsl) {
D
duke 已提交
813 814 815
            registry =
                    new SingleEntryRegistry(port, csf, ssf,
                    "jmxrmi", exporter.firstExported);
816 817 818 819
        } else if (useSocketFactory) {
            registry =
                    new SingleEntryRegistry(port, csf, ssf,
                    "jmxrmi", exporter.firstExported);
820
        } else {
D
duke 已提交
821 822 823
            registry =
                    new SingleEntryRegistry(port,
                    "jmxrmi", exporter.firstExported);
824 825
        }

826 827 828 829 830 831

        int registryPort =
            ((UnicastRef) ((RemoteObject) registry).getRef()).getLiveRef().getPort();
        String jmxUrlStr =  String.format("service:jmx:rmi:///jndi/rmi://%s:%d/jmxrmi",
                                           url.getHost(), registryPort);
        JMXServiceURL remoteURL = new JMXServiceURL(jmxUrlStr);
D
duke 已提交
832 833

        /* Our exporter remembers the first object it was asked to
834 835 836 837 838 839 840 841
        export, which will be an RMIServerImpl appropriate for
        publication in our special registry.  We could
        alternatively have constructed the RMIServerImpl explicitly
        and then constructed an RMIConnectorServer passing it as a
        parameter, but that's quite a bit more verbose and pulls in
        lots of knowledge of the RMI connector.  */

        return new JMXConnectorServerData(connServer, remoteURL);
D
duke 已提交
842 843 844 845 846 847 848 849
    }

    /**
     * This class cannot be instantiated.
     **/
    private ConnectorBootstrap() {
    }

850 851 852
    private static final ClassLogger log =
        new ClassLogger(ConnectorBootstrap.class.getPackage().getName(),
                        "ConnectorBootstrap");
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020

    private static class HostAwareSocketFactory implements RMIServerSocketFactory {

        private final String bindAddress;

        private HostAwareSocketFactory(String bindAddress) {
             this.bindAddress = bindAddress;
        }

        @Override
        public ServerSocket createServerSocket(int port) throws IOException {
            if (bindAddress == null) {
                return new ServerSocket(port);
            } else {
                try {
                    InetAddress addr = InetAddress.getByName(bindAddress);
                    return new ServerSocket(port, 0, addr);
                } catch (UnknownHostException e) {
                    return new ServerSocket(port);
                }
            }
        }
    }

    private static class HostAwareSslSocketFactory extends SslRMIServerSocketFactory {

        private final String bindAddress;
        private final String[] enabledCipherSuites;
        private final String[] enabledProtocols;
        private final boolean needClientAuth;
        private final SSLContext context;

        private HostAwareSslSocketFactory(String[] enabledCipherSuites,
                                          String[] enabledProtocols,
                                          boolean sslNeedClientAuth,
                                          String bindAddress) throws IllegalArgumentException {
            this(null, enabledCipherSuites, enabledProtocols, sslNeedClientAuth, bindAddress);
        }

        private HostAwareSslSocketFactory(SSLContext ctx,
                                          String[] enabledCipherSuites,
                                          String[] enabledProtocols,
                                          boolean sslNeedClientAuth,
                                          String bindAddress) throws IllegalArgumentException {
            this.context = ctx;
            this.bindAddress = bindAddress;
            this.enabledProtocols = enabledProtocols;
            this.enabledCipherSuites = enabledCipherSuites;
            this.needClientAuth = sslNeedClientAuth;
            checkValues(ctx, enabledCipherSuites, enabledProtocols);
        }

        @Override
        public ServerSocket createServerSocket(int port) throws IOException {
            if (bindAddress != null) {
                try {
                    InetAddress addr = InetAddress.getByName(bindAddress);
                    return new SslServerSocket(port, 0, addr, context,
                                               enabledCipherSuites, enabledProtocols, needClientAuth);
                } catch (UnknownHostException e) {
                    return new SslServerSocket(port, context,
                                               enabledCipherSuites, enabledProtocols, needClientAuth);
                }
            } else {
                return new SslServerSocket(port, context,
                                           enabledCipherSuites, enabledProtocols, needClientAuth);
            }
        }

        private static void checkValues(SSLContext context,
                                        String[] enabledCipherSuites,
                                        String[] enabledProtocols) throws IllegalArgumentException {
            // Force the initialization of the default at construction time,
            // rather than delaying it to the first time createServerSocket()
            // is called.
            //
            final SSLSocketFactory sslSocketFactory =
                    context == null ?
                        (SSLSocketFactory)SSLSocketFactory.getDefault() : context.getSocketFactory();
            SSLSocket sslSocket = null;
            if (enabledCipherSuites != null || enabledProtocols != null) {
                try {
                    sslSocket = (SSLSocket) sslSocketFactory.createSocket();
                } catch (Exception e) {
                    final String msg = "Unable to check if the cipher suites " +
                            "and protocols to enable are supported";
                    throw (IllegalArgumentException)
                    new IllegalArgumentException(msg).initCause(e);
                }
            }

            // Check if all the cipher suites and protocol versions to enable
            // are supported by the underlying SSL/TLS implementation and if
            // true create lists from arrays.
            //
            if (enabledCipherSuites != null) {
                sslSocket.setEnabledCipherSuites(enabledCipherSuites);
            }
            if (enabledProtocols != null) {
                sslSocket.setEnabledProtocols(enabledProtocols);
            }
        }
    }

    private static class SslServerSocket extends ServerSocket {

        private static SSLSocketFactory defaultSSLSocketFactory;
        private final String[] enabledCipherSuites;
        private final String[] enabledProtocols;
        private final boolean needClientAuth;
        private final SSLContext context;

        private SslServerSocket(int port,
                                SSLContext ctx,
                                String[] enabledCipherSuites,
                                String[] enabledProtocols,
                                boolean needClientAuth) throws IOException {
            super(port);
            this.enabledProtocols = enabledProtocols;
            this.enabledCipherSuites = enabledCipherSuites;
            this.needClientAuth = needClientAuth;
            this.context = ctx;
        }

        private SslServerSocket(int port,
                                int backlog,
                                InetAddress bindAddr,
                                SSLContext ctx,
                                String[] enabledCipherSuites,
                                String[] enabledProtocols,
                                boolean needClientAuth) throws IOException {
            super(port, backlog, bindAddr);
            this.enabledProtocols = enabledProtocols;
            this.enabledCipherSuites = enabledCipherSuites;
            this.needClientAuth = needClientAuth;
            this.context = ctx;
        }

        @Override
        public Socket accept() throws IOException {
            final SSLSocketFactory sslSocketFactory =
                    context == null ?
                        getDefaultSSLSocketFactory() : context.getSocketFactory();
            Socket socket = super.accept();
            SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
                    socket, socket.getInetAddress().getHostName(),
                    socket.getPort(), true);
            sslSocket.setUseClientMode(false);
            if (enabledCipherSuites != null) {
                sslSocket.setEnabledCipherSuites(enabledCipherSuites);
            }
            if (enabledProtocols != null) {
                sslSocket.setEnabledProtocols(enabledProtocols);
            }
            sslSocket.setNeedClientAuth(needClientAuth);
            return sslSocket;
        }

        private static synchronized SSLSocketFactory getDefaultSSLSocketFactory() {
            if (defaultSSLSocketFactory == null) {
                defaultSSLSocketFactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
                return defaultSSLSocketFactory;
            } else {
                return defaultSSLSocketFactory;
            }
        }

    }
D
duke 已提交
1021
}