Example usage for javax.rmi.ssl SslRMIServerSocketFactory SslRMIServerSocketFactory

List of usage examples for javax.rmi.ssl SslRMIServerSocketFactory SslRMIServerSocketFactory

Introduction

In this page you can find the example usage for javax.rmi.ssl SslRMIServerSocketFactory SslRMIServerSocketFactory.

Prototype

public SslRMIServerSocketFactory() 

Source Link

Document

Creates a new SslRMIServerSocketFactory with the default SSL socket configuration.

SSL connections accepted by server sockets created by this factory have the default cipher suites and protocol versions enabled and do not require client authentication.

Usage

From source file:gridool.util.remoting.RemoteBase.java

protected void bind() throws RemoteException, NamingException {
    //if(System.getSecurityManager() == null) {// create and install a security manager
    //    System.setSecurityManager(new RMISecurityManager());
    //}//from   w  ww. ja va2  s  . c om
    final Remote stub;
    if (rmiProtocol.equals(RMI_PROTOCOL_JRMP_SSL)) {
        stub = UnicastRemoteObject.exportObject(this, exportPort, new SslRMIClientSocketFactory(),
                new SslRMIServerSocketFactory());
    } else {
        assert (rmiProtocol.equals(RMI_PROTOCOL_JRMP));
        stub = UnicastRemoteObject.exportObject(this, exportPort,
                TimeoutSocketProdiver.createClientSocketFactory(), null);
    }
    try {// bind the remote object's stub in the registry
        Naming.rebind(endpointUrl, stub);
    } catch (MalformedURLException e) {
        LOG.error("failed to bind: " + endpointUrl, e);
        throw new IllegalStateException("Illegal regist url: " + endpointUrl, e);
    }
    LOG.info("Remote object is bounded at " + endpointUrl + " for " + ObjectUtils.identityToString(this));
}

From source file:com.tc.management.JMXConnectorProxy.java

private void determineConnector() throws Exception {
    JMXServiceURL url = new JMXServiceURL(getSecureJMXConnectorURL(m_host, m_port));

    if (m_secured) {
        RMIClientSocketFactory csf;
        if (Boolean.getBoolean("tc.ssl.trustAllCerts")) {
            csf = new TSASSLSocketFactory();
        } else {/*from  ww w.  j  a  v a2  s . c o m*/
            csf = new SslRMIClientSocketFactory();
        }
        SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory();
        m_env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
        m_env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);

        // Needed to avoid "non-JRMP server at remote endpoint" error
        m_env.put("com.sun.jndi.rmi.factory.socket", csf);

        m_serviceURL = new JMXServiceURL("service:jmx:rmi://" + m_host + ":" + m_port + "/jndi/rmi://" + m_host
                + ":" + m_port + "/jmxrmi");
        m_connector = JMXConnectorFactory.connect(url, m_env);
    } else {
        try {
            m_connector = JMXConnectorFactory.connect(url, m_env);
            m_serviceURL = url;
        } catch (IOException ioe) {
            if (isConnectException(ioe)) {
                throw ioe;
            }
            if (isAuthenticationException(ioe)) {
                throw new SecurityException("Invalid login name or credentials");
            }
            url = new JMXServiceURL(getJMXConnectorURL(m_host, m_port));
            m_connector = JMXConnectorFactory.connect(url, m_env);
            m_serviceURL = url;
        }
    }
}

From source file:org.apache.hadoop.hbase.JMXListener.java

public void startConnectorServer(int rmiRegistryPort, int rmiConnectorPort) throws IOException {
    boolean rmiSSL = false;
    boolean authenticate = true;
    String passwordFile = null;/*from  w  w  w. ja va2s. c  om*/
    String accessFile = null;

    System.setProperty("java.rmi.server.randomIDs", "true");

    String rmiSSLValue = System.getProperty("com.sun.management.jmxremote.ssl", "false");
    rmiSSL = Boolean.parseBoolean(rmiSSLValue);

    String authenticateValue = System.getProperty("com.sun.management.jmxremote.authenticate", "false");
    authenticate = Boolean.parseBoolean(authenticateValue);

    passwordFile = System.getProperty("com.sun.management.jmxremote.password.file");
    accessFile = System.getProperty("com.sun.management.jmxremote.access.file");

    LOG.info("rmiSSL:" + rmiSSLValue + ",authenticate:" + authenticateValue + ",passwordFile:" + passwordFile
            + ",accessFile:" + accessFile);

    // Environment map
    HashMap<String, Object> jmxEnv = new HashMap<String, Object>();

    RMIClientSocketFactory csf = null;
    RMIServerSocketFactory ssf = null;

    if (rmiSSL) {
        if (rmiRegistryPort == rmiConnectorPort) {
            throw new IOException(
                    "SSL is enabled. " + "rmiConnectorPort cannot share with the rmiRegistryPort!");
        }
        csf = new SslRMIClientSocketFactory();
        ssf = new SslRMIServerSocketFactory();
    }

    if (csf != null) {
        jmxEnv.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
    }
    if (ssf != null) {
        jmxEnv.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);
    }

    // Configure authentication
    if (authenticate) {
        jmxEnv.put("jmx.remote.x.password.file", passwordFile);
        jmxEnv.put("jmx.remote.x.access.file", accessFile);
    }

    // Create the RMI registry
    LocateRegistry.createRegistry(rmiRegistryPort);
    // Retrieve the PlatformMBeanServer.
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();

    // Build jmxURL
    JMXServiceURL serviceUrl = buildJMXServiceURL(rmiRegistryPort, rmiConnectorPort);

    try {
        // Start the JMXListener with the connection string
        jmxCS = JMXConnectorServerFactory.newJMXConnectorServer(serviceUrl, jmxEnv, mbs);
        jmxCS.start();
        LOG.info("ConnectorServer started!");
    } catch (IOException e) {
        LOG.error("fail to start connector server!", e);
    }

}

From source file:org.apache.synapse.JmxAdapter.java

/**
 * Creates an environment context map containing the configuration used to start the
 * server connector.//  w  ww.  j a  v  a 2  s. co m
 * 
 * @return an environment context map containing the configuration used to start the server 
 *         connector
 */
private Map<String, Object> createContextMap() {
    Map<String, Object> env = new HashMap<String, Object>();

    if (jmxInformation.isAuthenticate()) {

        if (jmxInformation.getRemotePasswordFile() != null) {
            env.put("jmx.remote.x.password.file", jmxInformation.getRemotePasswordFile());
        } else {
            SecretInformation secretInformation = jmxInformation.getSecretInformation();
            // Get the global secret resolver
            //TODO This should be properly implemented if JMX adapter is going to use out side synapse
            PasswordManager pwManager = PasswordManager.getInstance();
            if (pwManager.isInitialized()) {
                secretInformation.setGlobalSecretResolver(pwManager.getSecretResolver());
            }
            env.put(JMXConnectorServer.AUTHENTICATOR,
                    new JmxSecretAuthenticator(jmxInformation.getSecretInformation()));
        }

        if (jmxInformation.getRemoteAccessFile() != null) {
            env.put("jmx.remote.x.access.file", jmxInformation.getRemoteAccessFile());
        }
    } else {
        log.warn("Using unsecured JMX remote access!");
    }

    if (jmxInformation.isRemoteSSL()) {
        log.info("Activated SSL communication");
        env.put("jmx.remote.rmi.client.socket.factory", new SslRMIClientSocketFactory());
        env.put("jmx.remote.rmi.server.socket.factory", new SslRMIServerSocketFactory());
    }

    return env;
}

From source file:org.apereo.portal.jmx.JavaManagementServerBean.java

/**
 * Generates the environment Map for the JMX server based on system properties
 * @return A non-null Map of environment settings for the JMX server.
 *//* w  w  w  .  j  av a2s.c  om*/
protected Map<String, Object> getJmxServerEnvironment() {
    final Map<String, Object> jmxEnv = new HashMap<String, Object>();

    //SSL Options
    final String enableSSL = System.getProperty(JMX_SSL_PROPERTY);
    if (Boolean.getBoolean(enableSSL)) {
        SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
        jmxEnv.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);

        SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory();
        jmxEnv.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);
    }

    //Password file options
    final String passwordFile = System.getProperty(JMX_PASSWORD_FILE_PROPERTY);
    if (passwordFile != null) {
        jmxEnv.put(JMX_REMOTE_X_PASSWORD_FILE, passwordFile);
    }

    //Access file options
    final String accessFile = System.getProperty(JMX_ACCESS_FILE_PROPERTY);
    if (accessFile != null) {
        jmxEnv.put(JMX_REMOTE_X_ACCESS_FILE, accessFile);
    }

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Configured JMX Server Environment = '" + jmxEnv + "'");
    }

    return jmxEnv;
}

From source file:org.red5.server.jmx.JMXAgent.java

public void init() {
    //environmental var holder
    HashMap env = null;/*from  ww  w .  ja  va2 s . c om*/
    if (enableHtmlAdapter) {
        // setup the adapter
        try {
            //instance an html adaptor
            int port = htmlAdapterPort == null ? 8082 : Integer.valueOf(htmlAdapterPort);
            html = new HtmlAdaptorServer(port);
            ObjectName htmlName = new ObjectName(
                    JMXFactory.getDefaultDomain() + ":type=HtmlAdaptorServer,port=" + port);
            log.debug("Created HTML adaptor on port: " + port);
            //add the adaptor to the server
            mbs.registerMBean(html, htmlName);
            //start the adaptor
            html.start();
            log.info("JMX HTML connector server successfully started");

        } catch (Exception e) {
            log.error("Error in setup of JMX subsystem (HTML adapter)", e);
        }
    } else {
        log.info("JMX HTML adapter was not enabled");
    }
    if (enableRmiAdapter) {
        // Create an RMI connector server
        log.debug("Create an RMI connector server");
        try {

            Registry r = null;
            try {
                //lookup the registry
                r = LocateRegistry.getRegistry(Integer.valueOf(rmiAdapterPort));
                //ensure we are not already registered with the registry
                for (String regName : r.list()) {
                    if (regName.equals("red5")) {
                        //unbind connector from rmi registry
                        r.unbind("red5");
                    }
                }
            } catch (RemoteException re) {
                log.info("RMI Registry server was not found on port " + rmiAdapterPort);
                //if we didnt find the registry and the user wants it created
                if (startRegistry) {
                    log.info("Starting an internal RMI registry");
                    // create registry for rmi port 9999
                    r = LocateRegistry.createRegistry(Integer.valueOf(rmiAdapterPort));
                }
            }
            JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" + rmiAdapterPort + "/red5");
            //if SSL is requested to secure rmi connections
            if (enableSsl) {
                // Environment map
                log.debug("Initialize the environment map");
                env = new HashMap();
                // Provide SSL-based RMI socket factories
                SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
                SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory();
                env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf);
                env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf);
            }

            //if authentication is requested
            if (StringUtils.isNotBlank(remoteAccessProperties)) {
                //if ssl is not used this will be null
                if (null == env) {
                    env = new HashMap();
                }
                //check the existance of the files
                //in the war version the full path is needed
                File file = new File(remoteAccessProperties);
                if (!file.exists()) {
                    log.debug("Access file was not found on path, will prepend config_root");
                    //pre-pend the system property set in war startup
                    remoteAccessProperties = System.getProperty("red5.config_root") + '/'
                            + remoteAccessProperties;
                    remotePasswordProperties = System.getProperty("red5.config_root") + '/'
                            + remotePasswordProperties;
                }
                env.put("jmx.remote.x.access.file", remoteAccessProperties);
                env.put("jmx.remote.x.password.file", remotePasswordProperties);
            }

            // create the connector server
            cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
            // add a listener for shutdown
            cs.addNotificationListener(this, null, null);
            // Start the RMI connector server
            log.debug("Start the RMI connector server");
            cs.start();
            log.info("JMX RMI connector server successfully started");
        } catch (ConnectException e) {
            log.warn("Could not establish RMI connection to port " + rmiAdapterPort
                    + ", please make sure \"rmiregistry\" is running and configured to listen on this port.");
        } catch (IOException e) {
            String errMsg = e.getMessage();
            if (errMsg.indexOf("NameAlreadyBoundException") != -1) {
                log.error("JMX connector (red5) already registered, you will need to restart your rmiregistry");
            } else {
                log.error("{}", e);
            }
        } catch (Exception e) {
            log.error("Error in setup of JMX subsystem (RMI connector)", e);
        }
    } else {
        log.info("JMX RMI adapter was not enabled");
    }
}

From source file:org.wso2.andes.server.management.JMXManagedObjectRegistry.java

public void start() throws IOException, ConfigurationException {

    CurrentActor.get().message(ManagementConsoleMessages.STARTUP());

    //check if system properties are set to use the JVM's out-of-the-box JMXAgent
    if (areOutOfTheBoxJMXOptionsSet()) {
        CurrentActor.get().message(ManagementConsoleMessages.READY(true));
        return;/*from  w w  w .j av  a 2  s.c  o m*/
    }

    IApplicationRegistry appRegistry = ApplicationRegistry.getInstance();
    int port = appRegistry.getConfiguration().getJMXManagementPort();

    //Socket factories for the RMIConnectorServer, either default or SLL depending on configuration
    RMIClientSocketFactory csf;
    RMIServerSocketFactory ssf;

    //check ssl enabled option in config, default to true if option is not set
    boolean sslEnabled = appRegistry.getConfiguration().getManagementSSLEnabled();

    if (sslEnabled) {
        //set the SSL related system properties used by the SSL RMI socket factories to the values
        //given in the configuration file, unless command line settings have already been specified
        String keyStorePath;

        if (System.getProperty("javax.net.ssl.keyStore") != null) {
            keyStorePath = System.getProperty("javax.net.ssl.keyStore");
        } else {
            keyStorePath = appRegistry.getConfiguration().getManagementKeyStorePath();
        }

        //check the keystore path value is valid
        if (keyStorePath == null) {
            throw new ConfigurationException("JMX management SSL keystore path not defined, "
                    + "unable to start SSL protected JMX ConnectorServer");
        } else {
            //ensure the system property is set
            System.setProperty("javax.net.ssl.keyStore", keyStorePath);

            //check the file is usable
            File ksf = new File(keyStorePath);

            if (!ksf.exists()) {
                throw new FileNotFoundException("Cannot find JMX management SSL keystore file " + ksf + "\n"
                        + "Check broker configuration, or see create-example-ssl-stores script"
                        + "in the bin/ directory if you need to generate an example store.");
            }
            if (!ksf.canRead()) {
                throw new FileNotFoundException(
                        "Cannot read JMX management SSL keystore file: " + ksf + ". Check permissions.");
            }

            CurrentActor.get().message(ManagementConsoleMessages.SSL_KEYSTORE(ksf.getAbsolutePath()));
        }

        //check the key store password is set
        if (System.getProperty("javax.net.ssl.keyStorePassword") == null) {

            if (appRegistry.getConfiguration().getManagementKeyStorePassword() == null) {
                throw new ConfigurationException("JMX management SSL keystore password not defined, "
                        + "unable to start requested SSL protected JMX server");
            } else {
                System.setProperty("javax.net.ssl.keyStorePassword",
                        appRegistry.getConfiguration().getManagementKeyStorePassword());
            }
        }

        //create the SSL RMI socket factories
        csf = new SslRMIClientSocketFactory();
        ssf = new SslRMIServerSocketFactory();
    } else {
        //Do not specify any specific RMI socket factories, resulting in use of the defaults.
        csf = null;
        ssf = null;
    }

    //add a JMXAuthenticator implementation the env map to authenticate the RMI based JMX connector server
    RMIPasswordAuthenticator rmipa = new RMIPasswordAuthenticator();
    rmipa.setAuthenticationManager(appRegistry.getAuthenticationManager());
    HashMap<String, Object> env = new HashMap<String, Object>();
    env.put(JMXConnectorServer.AUTHENTICATOR, rmipa);

    /*
     * Start a RMI registry on the management port, to hold the JMX RMI ConnectorServer stub. 
     * Using custom socket factory to prevent anyone (including us unfortunately) binding to the registry using RMI.
     * As a result, only binds made using the object reference will succeed, thus securing it from external change. 
     */
    System.setProperty("java.rmi.server.randomIDs", "true");
    if (_useCustomSocketFactory) {
        _rmiRegistry = LocateRegistry.createRegistry(port, null, new CustomRMIServerSocketFactory());
    } else {
        _rmiRegistry = LocateRegistry.createRegistry(port, null, null);
    }

    CurrentActor.get().message(ManagementConsoleMessages.LISTENING("RMI Registry", port));

    /*
     * We must now create the RMI ConnectorServer manually, as the JMX Factory methods use RMI calls 
     * to bind the ConnectorServer to the registry, which will now fail as for security we have
     * locked it from any RMI based modifications, including our own. Instead, we will manually bind 
     * the RMIConnectorServer stub to the registry using its object reference, which will still succeed.
     * 
     * The registry is exported on the defined management port 'port'. We will export the RMIConnectorServer
     * on 'port +1'. Use of these two well-defined ports will ease any navigation through firewall's. 
     */
    final RMIServerImpl rmiConnectorServerStub = new RMIJRMPServerImpl(port + PORT_EXPORT_OFFSET, csf, ssf,
            env);
    String localHost;
    try {
        localHost = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException ex) {
        localHost = "127.0.0.1";
    }
    final String hostname = localHost;
    final JMXServiceURL externalUrl = new JMXServiceURL("service:jmx:rmi://" + hostname + ":"
            + (port + PORT_EXPORT_OFFSET) + "/jndi/rmi://" + hostname + ":" + port + "/jmxrmi");

    final JMXServiceURL internalUrl = new JMXServiceURL("rmi", hostname, port + PORT_EXPORT_OFFSET);
    _cs = new RMIConnectorServer(internalUrl, env, rmiConnectorServerStub, _mbeanServer) {
        @Override
        public synchronized void start() throws IOException {
            try {
                //manually bind the connector server to the registry at key 'jmxrmi', like the out-of-the-box agent                        
                _rmiRegistry.bind("jmxrmi", rmiConnectorServerStub);
            } catch (AlreadyBoundException abe) {
                //key was already in use. shouldnt happen here as its a new registry, unbindable by normal means.

                //IOExceptions are the only checked type throwable by the method, wrap and rethrow
                IOException ioe = new IOException(abe.getMessage());
                ioe.initCause(abe);
                throw ioe;
            }

            //now do the normal tasks
            super.start();
        }

        @Override
        public synchronized void stop() throws IOException {
            try {
                if (_rmiRegistry != null) {
                    _rmiRegistry.unbind("jmxrmi");
                }
            } catch (NotBoundException nbe) {
                //ignore
            }

            //now do the normal tasks
            super.stop();
        }

        @Override
        public JMXServiceURL getAddress() {
            //must return our pre-crafted url that includes the full details, inc JNDI details
            return externalUrl;
        }

    };

    //Add the custom invoker as an MBeanServerForwarder, and start the RMIConnectorServer.
    MBeanServerForwarder mbsf = MBeanInvocationHandlerImpl.newProxyInstance();
    _cs.setMBeanServerForwarder(mbsf);

    NotificationFilterSupport filter = new NotificationFilterSupport();
    filter.enableType(JMXConnectionNotification.OPENED);
    filter.enableType(JMXConnectionNotification.CLOSED);
    filter.enableType(JMXConnectionNotification.FAILED);
    // Get the handler that is used by the above MBInvocationHandler Proxy.
    // which is the MBeanInvocationHandlerImpl and so also a NotificationListener
    _cs.addNotificationListener((NotificationListener) Proxy.getInvocationHandler(mbsf), filter, null);

    _cs.start();

    String connectorServer = (sslEnabled ? "SSL " : "") + "JMX RMIConnectorServer";
    CurrentActor.get().message(ManagementConsoleMessages.LISTENING(connectorServer, port + PORT_EXPORT_OFFSET));

    CurrentActor.get().message(ManagementConsoleMessages.READY(false));
}

From source file:xbird.server.RemoteServerBase.java

protected void bind() throws RemoteException, NamingException {
    final Remote stub;
    if (RMI_PROTOCOL.equals(ServerConstants.RMI_PROTOCOL_JRMP_SSL)) {
        stub = (Remote) UnicastRemoteObject.exportObject(this, _exportPort, new SslRMIClientSocketFactory(),
                new SslRMIServerSocketFactory());
    } else {//from  www.  j av a2 s. c  o m
        assert (RMI_PROTOCOL.equals("jrmp"));
        stub = (Remote) UnicastRemoteObject.exportObject(this, _exportPort);
    }
    // Bind the remote object's stub in the registry
    try {
        Naming.rebind(_bindUrl, stub);
    } catch (MalformedURLException e) {
        throw new IllegalStateException("Illegal regist url:" + _bindUrl, e);
    }
    LOG.info("Remote object is bounded at " + _bindUrl);
}