-
Notifications
You must be signed in to change notification settings - Fork 3
/
exploit-searcher.py
431 lines (349 loc) · 17.3 KB
/
exploit-searcher.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
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
import requests
from bs4 import BeautifulSoup
import argparse
from termcolor import colored
import json
import re
import sys
from datetime import datetime
# from drivers.export_drivers import init_webdriver
# from selenium.webdriver.common.keys import Keys
# from selenium.webdriver.common.by import By
# 12-18 Start time : 10:30
# v1.3
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose",action="store_true",
help="\tadd verbosity")
parser.add_argument("-s", "--search", type=str,
help="\tthe search term to query all databases for (exploit, vulnerability, CVE, technology, framework)",
required=True)
parser.add_argument("-e", "--engine", nargs='+', choices=['github', 'rapid7', 'packetstorm', 'cve', 'nvd'],
help="engines to use in query; defaults to ALL when not specified. values must be SPACE seperated (not comma).")
parser.add_argument("-c", "--cve", type=str,
help="\tCVE ID to refine search")
parser.add_argument("-l", "--limit", type=str, default=False,
help=" number of results to display from each source (experimental)")
parser.add_argument("-q", "--quiet", action="store_true",
help="\tdon't print the banner when running")
args = parser.parse_args()
SEARCHTERM = args.search # for running with command line
CVE_ID = args.cve
ENGINES = args.engine
LIMIT = args.limit
# PROD : uncomment the above to pass command line options to the script; removed for testing purposes
#SEARCHTERM='smb'
interesting = ['root', 'code execution', 'exploit', 'command','execute','malicious','payload',
'remote','code','execution','arbitrary','information','leak',
'vulnerability', 'unrestricted', 'remotely',
'remote-code-execution','PoC','poc','POC']
def title_banner():
title="""
📄📄📄📄📄📄📄📄
📄 ___ __ __ ___ __ ___ __ __ ___ __
📄 |__ \_/ |__) | / \ | | 🎯 /__` |__ /\ |__) / ` |__| |__ |__)
📄 |___ / \ | |___ \__/ | | 🎯 .__/ |___ /~~\ | \ \__, | | |___ | \
📄
📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄📄
"""
print(title)
def banner(title):
center = str(title).center(20)
h1 = colored('◄✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸►◄✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸►' , 'blue')
h2 = colored(f'◄✸✸✸✸✸{center}✸✸✸✸✸►' , 'blue') * 2
h3 = colored('◄✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸►◄✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸✸►' , 'blue')
print(f"{h1}\n{h2}\n{h3}")
print()
def resultify(key_string, value_string, color='yellow',end=False): # end = set the end rather than the text color for the key
if end == True:
print(f"{colored(key_string, 'yellow')}: {colored(value_string, color)}")
return
print(f"{colored(key_string, color)}: {value_string}")
def query_packetstorm(CVE_ID=None): # bugg with idx+1 [x]TODO
banner('Packet Storm')
url = f"https://packetstormsecurity.com/search/?q={SEARCHTERM}"
page = requests.get(url)
text = page.text
base_url = 'https://packetstormsecurity.com'
# parse number of "Page y of y"
n_pages = list(set(re.findall(r'href="/search/files/page(\d)/\?q=.*?"',text))) #grab 1,2,3,x for pagination
n_pages_len = len(n_pages)
# pagination link examples
# url = f"https://packetstormsecurity.com/search/page1/?q={SEARCHTERM}"
# https://packetstormsecurity.com/search/files/page3/?q=shellshock
all_page_urls = [f"https://packetstormsecurity.com/search/files/page{i}/?q={SEARCHTERM}" for i in range(1,n_pages_len+1)] # works
for link in all_page_urls: #loop around pagination
# set up BS4 object
url = link
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
div_frame = soup.find('div', {'id':'m'})
exploit_frames = div_frame.find_all('dl')#boxes containing exploit name, author, tags, date posted, and advisories
for frame in exploit_frames:
#TODO: count = 0 if count is less than number of exploits passed ...
exploit_link = frame.find('dt').a['href']
exploit_title = frame.find('dt').a.text
exploit_date = frame.find('dd', class_='datetime').a.text
exploit_description = frame.find('dd', class_='detail').p.text
exploit_tags = ''.join([str(a.text).replace('tags | ','') for a in frame.find_all('dd', class_='tags')]) #string-list
exploit_cves = ''.join([str(dd.text).replace('advisories | ','') for dd in frame.find_all('dd', class_='cve') ]) #string-list
exploit_systems = ''.join([str(dd.text).replace('systems | ','') for dd in frame.find_all('dd', class_='os') ]) #string-list
# Highlight remote command execution
compare_interesting = [i.lower() for i in exploit_title.split(' ')]
if any(item in interesting for item in compare_interesting) :
exploit_title = colored(exploit_title, 'red')
# Highlight root, exploit, RCE in tags
split_tags = [t.strip() for t in exploit_tags.split(',')]
if any(item in interesting for item in split_tags):
exploit_tags = colored(exploit_tags, 'red')
# Colorize certain trigger words on exploit description
exploit_description = exploit_description.split(' ')
colored_description = []
for word in exploit_description:
# if there is a juicy word highlight it red in summary output
if word in interesting:
colored_description.append(colored(word,'red'))
else:
colored_description.append(word)
#reassign the cve description
exploit_description = ' '.join(colored_description)
resultify('TITLE', exploit_title)
resultify('SUMMARY', exploit_description)
resultify('DATE', exploit_date)
if exploit_cves:
resultify('CVE', exploit_cves)
if exploit_systems:
resultify('SYSTEMS', exploit_systems)
resultify('TAGS', exploit_tags)
resultify('URL', f'{base_url+exploit_link}', 'blue', end=True)
print() # add space between exploit outputs
print()
def query_nvd(CVE_ID=None):
# Dev help https://nvd.nist.gov/developers/vulnerabilities
# other people doing the same thing https://linuxtut.com/en/97e385ed0a78dc28534f/
### 11 Results (grabs the most results)
banner('NVD Results')
nvd_url = f'https://services.nvd.nist.gov/rest/json/cves/1.0?apiKey=857af2a5-d596-4593-a3a6-afda6cf9ba40&resultsPerPage=100&keyword={SEARCHTERM}'
cves = requests.get(nvd_url)
json_cves = json.loads(cves.text)
vulns = json_cves['result']['CVE_Items']
for vuln in vulns:
try:
cve_id = vuln['cve']['CVE_data_meta']['ID'] #"ID": "CVE-2021-44224",
except IndexError:
print("NO CVE FOUND")
#import pdb ; pdb.set_trace()
try:
cve_title = vuln['cve']['references']['reference_data'][0]['name'] # link or title could be here
except IndexError:
print("NO TITLE FOUND")
try:
cve_reflink = vuln['cve']['references']['reference_data'][0]['url'] # url is always here
except IndexError:
print("NO REFERENCE FOUND")
try:
cve_description = vuln['cve']['description']['description_data'][0]['value']
except IndexError:
print("NO DESCRIPTION FOUND")
#update these for more colored output in the summary
cve_description_split = cve_description.split(' ')
colored_description = []
for word in cve_description_split:
# if there is a juicy word highlight it red in summary output
if word in interesting:
colored_description.append(colored(word,'red'))
else:
colored_description.append(word)
#reassign the cve description
cve_description = ' '.join(colored_description)
if 'baseMetricV3' in vuln['impact']:
v3score = vuln['impact']['baseMetricV3']['cvssV3']['baseScore'] # CRIT|HIGH|MED|LOW
v3severity = vuln['impact']['baseMetricV3']['cvssV3']['baseSeverity'] # CRIT|HIGH|MED|LOW
if v3severity == 'HIGH' or v3severity == 'CRITICAL':
v3severity = colored(v3severity, 'red')
v3score = colored(v3score, 'red')
else :
v3score = None
v3severity = None
if 'baseMetricV2' in vuln['impact']:
v2score = vuln['impact']['baseMetricV2']['cvssV2']['baseScore'] # HIGH|MED|LOW
v2severity = vuln['impact']['baseMetricV2']['severity'] # HIGH|MED|LOW
if v2severity == 'HIGH': # set both to red
v2severity = colored(v2severity, 'red')
v2score = colored(v2score, 'red')
else:
v2score = None
v2severity = None
# TODO RESULTIFY THIS
if str(cve_title).strip()[0:4] != 'http':
print(f"{colored('TITLE','yellow')}: {cve_title}")
print(f"{colored('CSSV2','yellow')}: {v2score}:{v2severity} | {colored('CSSV3','yellow')}: {v3score}:{v3severity} | {colored('CVE','yellow')}: {colored(cve_id,'yellow')}")
print(f"{colored('SUMMARY','yellow')}: {cve_description}")
print(f"{colored('REFERENCE','yellow')}: {colored(cve_reflink,'blue')}")
print()
###
# addOns=dictionaryCpes
# apiKey optional
# cpeMatchString optional
# cvssV2Severity=HIGH|MEDIUM|LOW
# cvssV3Severity=CRITICAL|HIGH|MEDIUM|LOW
# isExactMatch=true optional
# keyword= found in the vulnerability description or reference links.
def query_github(CVE_ID=None):
banner('GitHub')
headers={
'Accept':'application/vnd.github.v3+json'
}
# SEARCH_KEYWORD_1 SEARCH_KEYWORD_N QUALIFIER_1 QUALIFIER_N
# GitHub Octocat in:readme user:defunkt
# q=tetris+language:assembly&sort=stars&order=desc
# Costruct the query based on the assigned argumetns
url = f'https://api.github.com/search/repositories?q={SEARCHTERM}+PoC+'
# append the CVE_ID to the search
if CVE_ID:
url += f'{CVE_ID}'
# Show highest valued first
url += '&sort=stars&order=desc'
# Limit number of pages returned
if LIMIT:
url += f'&per_page={LIMIT}'
response = requests.get(url)
#print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))
jres = json.loads(response.text)
for i in jres['items']:
repo_name = i['full_name']
description = i['description']
html_link = i['html_url']
create_date = str(i['created_at'])[:10]
forks = i['forks_count']
language = i['language']
ftags = i['topics']
last_updated = str(i['updated_at'])[:10]
# convert tags to red if in interesting
tags = []
for i in ftags:
if i in interesting:
tags.append(colored(i, 'red'))
else:
tags.append(i)
tags = ', '.join(tags)
resultify('TITLE', repo_name, end=True)
if description:
resultify('SUMMARY', description)
# have to use colored because joining string derp
print(f"{colored('PUBLISHED','yellow')}: {create_date} | {colored('UPDATED', 'yellow')}: {last_updated}")
if tags:
resultify('TAGS', tags)
# have to use colored because joining string derp
print(f"{colored('LANGUAGE','yellow')}: {language} | {colored('FORKS', 'yellow')}: {forks}")
# resultify('LANGUAGE', language) + ' | ' + resultify('FORKS', forks)
resultify('URL', html_link, 'blue', end=True)
print()
def query_rapid7(CVE_ID=None): #TODO
banner('Rapid7')
print('COMMING SOON!')
print()
pass
def query_cve(CVE_ID=None):
banner('CVE Details')
print('COMMING SOON!')
print()
pass
def query_edb(): # abandoned for now due to the website not rendering exploits over http.
# exploit results are only rendered in the browser making scraping impossible.
headers={
'Host': 'www.exploit-db.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive'}
# website advanced searc parmeters https://www.exploit-db.com/search?
# q=TITLE
# &cve=1111-1111
# &type=remote
# &platform=windows
# &text=EXPLOIT_CONTENT
# &port=66
# &verified=true
# &nomsf=true
# https://www.exploit-db.com/search?type=remote&platform=windows&port=445
# returns remote windows exploits on port 445 with no provided title or CVE
banner('Exploit Database')
EDB_TYPES=["dos","local","remote","shellcode","papers","webapps"]
EDB_PLATFORMS=["aix","alpha","android","arm","ashx","asp","aspx",
"atheos","beos","bsd","bsdi_x86","bsd_ppc",
"bsd_x86","cfm","cgi","ezine","freebsd","freebsd_x86",
"freebsd_x86","generator","hardware","hp","immunix",
"ios","irix","java","json","jsp","linux","linux_crisv32",
"linux_mips","linux_ppc","linux_sparc","linux_x86",
"linux_x86","lua","macos","magazine","minix",
"multiple","netbsd_x86","netware","nodejs",
"novell","openbsd","openbsd_x86","osx","osx_ppc",
"palm_os","perl","php","plan9","python","python2",
"python3","qnx","ruby","sco","sco_x86","solaris",
"solaris_mips","solaris_sparc","solaris_x86","superh_sh4",
"system_z","tru64","ultrix","unix","unixware","vxworks",
"watchos","windows","windows_x86","windows_x86"]
EDB_TAGS=["Authentication Bypass / Credentials Bypass (AB/CB)",
"Buffer Overflow","Bug Report","Client Side","Code Injection",
"Command Injection","Console","Cross-Site Request Forgery (CSRF)",
"Cross-Site Scripting (XSS)","Denial of Service (DoS)",
"Deserialization","File Inclusion (LFI/RFI)","Heap Overflow",
"Integer Overflow","Local","Malware","Metasploit Framework (MSF)",
"NULL Pointer Dereference","Object Injection","Out Of Bounds",
"Pwn2Own","Race Condition","Remote","Server-Side Request Forgery (SSRF)",
"SQL Injection (SQLi)","Traversal","Type Confusion","Use After Free (UAF)",
"WordPress Core","WordPress Plugin","XML External Entity (XXE)"]
#url = f"https://www.exploit-db.com/search?q={SEARCHTERM}"
#page = requests.get(url, headers=headers)
#soup = BeautifulSoup(page.content, 'html.parser')
#exploit_table = soup.find('table', {'id':'exploits-table'})
#exploit_table = soup.find_all('tr', class_='odd')
# TODO lets try using selenium to grab the exploits.
# # TESTING selenium (scrapping this idea)
# driver = init_webdriver()
# driver.get(f"https://www.exploit-db.com/search?q={SEARCHTERM}")
# test = driver.find_elements(By.ID, 'exploits-table')
# test = driver.find_elements(By.ID, 'exploits-table')
# #exp_last = driver.find_elements(By.CLASS_NAME, 'odd')
# exp_block = driver.find_elements_by_xpath('//tr[@class="even"')
# for i in exp_block:
# print(i)
# driver.close()
def main():
# pass the cve-id somewhere in here
# Dont print banner
if not args.quiet:
title_banner()
# Engines
if ENGINES: # pass the list of differnt engines to be parsed
if 'rapid7' in ENGINES:
query_rapid7()
if 'packetstorm' in ENGINES:
query_packetstorm()
if 'cve' in ENGINES:
query_cve()
if 'nvd' in ENGINES:
query_nvd()
if 'github' in ENGINES:
query_github()
quit()
# Default (run everything)
query_github()
query_rapid7()
query_packetstorm()
query_cve()
query_nvd()
quit()
# TODO / ON HOLD
#query_edb()
# ### Rapid7
# f"https://www.rapid7.com/db/?q={SEARCHTERM}&type="
# site:www.rapid7.com/db/modules/exploit/* "{SEARCHTERM}"
# ### CVE Details Section
# f"https://www.cvedetails.com/google-search-results.php?q={SEARCHTERM}&sa=Search"
# if CVE_ID:
# f"https://www.exploit-db.com/search?q={SEARCHTERM}&cve={CVE_ID}"
# f"https://www.cvedetails.com/cve-details.php?t=1&cve_id=CVE-{CVE_ID}"
if __name__ == '__main__':
main()