Repository navigation
Expand file tree
/
Copy pathpastebin_monitoring.py
More file actions
335 lines (299 loc) · 13.6 KB
/
Copy pathpastebin_monitoring.py
File metadata and controls
335 lines (299 loc) · 13.6 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
import os
import sys
import aiohttp
import asyncio
from bs4 import BeautifulSoup
from rich.console import Console
from rich.table import Table
from colorama import Fore, init
import re
from urllib.parse import urljoin, urlparse
import base64
import dns.resolver
import argparse
# Add the parent directory to the system path to import utilities and settings
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from utils.util import log_message
from config.settings import API_KEYS
init(autoreset=True)
console = Console()
# Define sensitive data patterns
EMAIL_REGEX = re.compile(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+')
API_KEY_REGEX = re.compile(r'api[_-]?key[:=]\s*[A-Za-z0-9]{10,}')
PASSWORD_REGEX = re.compile(r'password[:=]\s*[A-Za-z0-9@#$%^&+=]{6,}')
# Define paste sites configurations
PASTE_SITES = {
"Pastebin": {
"search_url": "https://pastebin.com/search",
"paste_link_prefix": "https://pastebin.com",
"paste_link_pattern": re.compile(r'^/[A-Za-z0-9]{8}$'),
},
"Ghostbin": {
"search_url": "https://ghostbin.com/search",
"paste_link_prefix": "https://ghostbin.com",
"paste_link_pattern": re.compile(r'^/p/[A-Za-z0-9]{6}$'),
},
"Paste.ee": {
"search_url": "https://api.paste.ee/v1/pastes/search",
"paste_link_prefix": "https://paste.ee/p/",
"paste_link_pattern": re.compile(r'^/p/[A-Za-z0-9]{6,}$'),
},
"ControlC": {
"search_url": "https://controlc.com/search",
"paste_link_prefix": "https://controlc.com",
"paste_link_pattern": re.compile(r'^/[\w]{4,}$'),
},
"Paste.org": {
"search_url": "https://paste.org/search",
"paste_link_prefix": "https://paste.org",
"paste_link_pattern": re.compile(r'^/[\w-]{6,}$'),
}
}
MAX_PAGES = 2 # Define maximum pages to search
DEFAULT_TIMEOUT = 10 # Default timeout for HTTP requests
async def fetch_url(session, url, params=None):
try:
async with session.get(url, params=params, timeout=DEFAULT_TIMEOUT) as response:
if response.status == 200:
return await response.text()
else:
console.print(Fore.RED + f"[!] Failed to fetch {url} with status {response.status}.")
return None
except asyncio.TimeoutError:
console.print(Fore.RED + f"[!] Timeout occurred while fetching {url}.")
except Exception as e:
console.print(Fore.RED + f"[!] Error fetching {url}: {e}")
return None
async def post_url(session, url, data=None, headers=None):
try:
async with session.post(url, json=data, headers=headers, timeout=DEFAULT_TIMEOUT) as response:
if response.status in [200, 201]:
return await response.json()
else:
console.print(Fore.RED + f"[!] POST request to {url} failed with status {response.status}.")
return None
except asyncio.TimeoutError:
console.print(Fore.RED + f"[!] Timeout occurred while posting to {url}.")
except Exception as e:
console.print(Fore.RED + f"[!] Error posting to {url}: {e}")
return None
async def search_paste_site(session, site_name, query):
site = PASTE_SITES.get(site_name)
if not site:
console.print(Fore.RED + f"[!] Paste site {site_name} is not configured.")
return []
results = []
for page in range(1, MAX_PAGES + 1):
if site_name == "Paste.ee":
# Paste.ee uses POST requests for search
search_payload = {
'query': query,
'page': page
}
headers = {
'Content-Type': 'application/json'
}
console.print(Fore.YELLOW + f"[*] Searching {site_name} - Page {page}...")
html_content = await post_url(session, site['search_url'], data=search_payload, headers=headers)
if html_content:
parsed_results = parse_paste_site_results(site_name, html_content, site)
if not parsed_results:
console.print(Fore.YELLOW + f"[!] No more results found on {site_name} at page {page}.")
break
results.extend(parsed_results)
else:
# Other sites use GET requests
params = {'q': query, 'page': page}
console.print(Fore.YELLOW + f"[*] Searching {site_name} - Page {page}...")
html_content = await fetch_url(session, site['search_url'], params=params)
if html_content:
parsed_results = parse_paste_site_results(site_name, html_content, site)
if not parsed_results:
console.print(Fore.YELLOW + f"[!] No more results found on {site_name} at page {page}.")
break
results.extend(parsed_results)
await asyncio.sleep(1) # Small delay to prevent overwhelming the site
return results
def parse_paste_site_results(site_name, html_content, site):
pastes = []
if site_name == "Paste.ee":
# Paste.ee returns JSON
if not html_content.get("data"):
return pastes
for paste in html_content['data']:
paste_title = paste.get('title') or "No Title"
paste_link = site['paste_link_prefix'] + paste['id']
pastes.append({'title': paste_title, 'link': paste_link, 'site': site_name})
else:
soup = BeautifulSoup(html_content, 'html.parser')
for paste in soup.find_all('a', href=site['paste_link_pattern']):
paste_title = paste.text.strip() or "No Title"
paste_link = urljoin(site['paste_link_prefix'], paste['href'])
pastes.append({'title': paste_title, 'link': paste_link, 'site': site_name})
return pastes
def display_pastebin_results(results):
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Site", style="cyan", justify="left")
table.add_column("Title", style="cyan", justify="left")
table.add_column("Link", style="green", justify="left")
for result in results:
table.add_row(result['site'], result['title'], result['link'])
console.print(table)
async def retrieve_paste_content(session, paste):
try:
console.print(Fore.YELLOW + f"[*] Retrieving content from {paste['link']}...")
content = await fetch_url(session, paste['link'])
if content:
return content
except Exception as e:
console.print(Fore.RED + f"[!] Error retrieving paste content from {paste['link']}: {e}")
return ""
def analyze_content(paste, content):
findings = {}
emails = EMAIL_REGEX.findall(content)
api_keys = API_KEY_REGEX.findall(content)
passwords = PASSWORD_REGEX.findall(content)
if emails:
findings['Emails'] = emails
if api_keys:
findings['API Keys'] = api_keys
if passwords:
findings['Passwords'] = passwords
if findings:
display_findings(paste, findings)
log_findings(paste, findings)
def display_findings(paste, findings):
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Site", style="cyan", justify="left")
table.add_column("Title", style="cyan", justify="left")
table.add_column("Link", style="green", justify="left")
table.add_column("Findings", style="red", justify="left")
findings_summary = "; ".join([f"{key}: {len(value)} found" for key, value in findings.items()])
table.add_row(paste['site'], paste['title'], paste['link'], findings_summary)
console.print(table)
def log_findings(paste, findings):
log_entry = f"Site: {paste['site']}, Title: {paste['title']}, Link: {paste['link']}\n"
for key, values in findings.items():
log_entry += f" {key}:\n"
for value in values:
log_entry += f" - {value}\n"
log_message("paste_monitoring.log", log_entry)
async def check_blacklist_services(domain):
console.print(Fore.YELLOW + "[*] Checking blacklist services...")
blacklist_domains = [
"zen.spamhaus.org",
"b.barracudacentral.org"
# Add more blacklist services if needed
]
listed = False
try:
resolver = dns.resolver.Resolver()
resolver.timeout = 5
resolver.lifetime = 5
for blacklist in blacklist_domains:
query = f"{'.'.join(reversed(domain.split('.')))}.{blacklist}"
try:
answers = resolver.resolve(query, 'A')
for rdata in answers:
if rdata.address.startswith("127."):
console.print(Fore.RED + f"[!] Domain {domain} is listed in {blacklist}.")
log_message("paste_monitoring.log", f"Domain {domain} is listed in {blacklist}.")
listed = True
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
continue
except Exception as e:
console.print(Fore.RED + f"[!] DNS query error for {blacklist}: {e}")
log_message("paste_monitoring.log", f"DNS query error for {blacklist}: {e}")
if not listed:
console.print(Fore.GREEN + "[+] Domain not found in public blacklist services.")
log_message("paste_monitoring.log", f"Domain not found in public blacklist services.")
except Exception as e:
console.print(Fore.RED + f"[!] Error during blacklist services check: {e}")
log_message("paste_monitoring.log", f"Error during blacklist services check: {e}")
async def check_virustotal(session, domain):
console.print(Fore.YELLOW + "[*] Checking VirusTotal...")
api_key = API_KEYS.get("VIRUSTOTAL_API_KEY")
if not api_key:
console.print(Fore.RED + "[!] VirusTotal API key not configured.")
log_message("paste_monitoring.log", "VirusTotal API key not configured.")
return
try:
# Step 1: Submit the domain to VirusTotal for analysis
scan_url = f"https://www.virustotal.com/api/v3/domains/{domain}"
headers = {
'x-apikey': api_key
}
async with session.get(scan_url, headers=headers, timeout=DEFAULT_TIMEOUT) as response:
if response.status == 200:
data = await response.json()
stats = data['data']['attributes']['last_analysis_stats']
malicious = stats.get('malicious', 0)
if malicious > 0:
console.print(Fore.RED + f"[!] VirusTotal detected {malicious} malicious sources for domain {domain}.")
log_message("paste_monitoring.log", f"VirusTotal detected {malicious} malicious sources for domain {domain}.")
else:
console.print(Fore.GREEN + f"[+] VirusTotal found no malicious sources for domain {domain}.")
log_message("paste_monitoring.log", f"VirusTotal found no malicious sources for domain {domain}.")
else:
console.print(Fore.RED + f"[!] VirusTotal check failed with status code {response.status}.")
log_message("paste_monitoring.log", f"VirusTotal check failed with status code {response.status}.")
except asyncio.TimeoutError:
console.print(Fore.RED + "[!] Timeout occurred during VirusTotal check.")
log_message("paste_monitoring.log", "Timeout occurred during VirusTotal check.")
except Exception as e:
console.print(Fore.RED + f"[!] Error during VirusTotal check: {e}")
log_message("paste_monitoring.log", f"Error during VirusTotal check: {e}")
async def monitor_paste_sites(query):
all_results = []
async with aiohttp.ClientSession() as session:
# Search all paste sites concurrently
tasks = []
for site in PASTE_SITES.keys():
tasks.append(search_paste_site(session, site, query))
paste_results = await asyncio.gather(*tasks)
for site_results in paste_results:
if site_results:
all_results.extend(site_results)
if all_results:
display_pastebin_results(all_results)
# Analyze each paste content concurrently
analysis_tasks = []
for paste in all_results:
analysis_tasks.append(analyze_paste_content(session, paste))
await asyncio.gather(*analysis_tasks)
else:
console.print(Fore.YELLOW + "[!] No pastes found for the given query.")
async def analyze_paste_content(session, paste):
content = await retrieve_paste_content(session, paste)
if content:
analyze_content(paste, content)
# Extract domain from paste link
parsed_url = urlparse(paste['link'])
domain = parsed_url.netloc
if domain:
await check_blacklist_services(domain)
await check_virustotal(session, domain)
def banner():
console.print(Fore.GREEN + """
=============================================
Argus - Advanced Paste Monitoring
=============================================
""")
def main(query):
banner()
console.print(Fore.WHITE + f"[*] Monitoring paste sites for query: {query}")
asyncio.run(monitor_paste_sites(query))
console.print(Fore.CYAN + "[*] Paste monitoring completed.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Argus - Advanced Paste Monitoring Tool")
parser.add_argument('query', type=str, help='Search query to monitor on paste sites')
args = parser.parse_args()
try:
query = args.query.strip()
if not query:
console.print(Fore.RED + "[!] Query cannot be empty.")
sys.exit(1)
main(query)
except KeyboardInterrupt:
console.print(Fore.RED + "\n[!] Process interrupted by user.")
sys.exit(1)