-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclickfix_extractor.py
More file actions
577 lines (494 loc) · 23.9 KB
/
Copy pathclickfix_extractor.py
File metadata and controls
577 lines (494 loc) · 23.9 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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
import os
import subprocess
import re
import sys
import argparse
import warnings
from urllib.parse import urlparse
def install_package(package_name):
try:
print(f"[*] Installing required package: {package_name}")
subprocess.check_call([sys.executable, "-m", "pip", "install", package_name],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(f"[+] Successfully installed {package_name}")
return True
except subprocess.CalledProcessError:
print(f"[!] Failed to install {package_name}. Please install manually: pip install {package_name}")
return False
try:
import requests
except ImportError:
print("[!] 'requests' module not found. Attempting to install...")
if not install_package("requests"):
sys.exit(1)
import requests
try:
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except ImportError:
print("[!] 'urllib3' module not found. Attempting to install...")
if not install_package("urllib3"):
sys.exit(1)
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
PATTERNS = {
# MSIEXEC invoking external URL/IP
'msiexec': r'msiexec\s*[\/\\]i\s*(https?:\/\/[^\s\"\'\<\>\)\]]+)',
# MSHTA executing HTTP-based payloads
'mshta': r'mshta\s+(https?:\/\/[^\s\"\'\<\>\)\]]+)',
# PowerShell with URL extraction (iwr, Invoke-WebRequest, wget, curl)
'powershell_iwr': r'(?:iwr|Invoke-WebRequest|wget|curl)[^\n]*[\'\"](https?:\/\/[^\s\"\'\<\>\)\]]+)[\'\"]',
# PowerShell direct URL assignment
'powershell_url': r'\$\w+\s*=\s*[\'\"](https?:\/\/[^\s\"\'\<\>\)\]]+)[\'\"]',
# PowerShell downloadstring/downloadfile
'powershell_download': r'(?:DownloadString|DownloadFile)\s*\(\s*[\'\"](https?:\/\/[^\s\"\'\<\>\)\]]+)[\'\"]',
# Generic HTTP/HTTPS URL with IP address pattern
'ip_url': r'https?:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(?::\d+)?[^\s\"\'\<\>\)\]]*',
# CMD with URL (requires word boundary and proper cmd syntax)
'cmd_url': r'(?:^|[\s\"\'\;])cmd(?:\.exe)?\s*[\/\\][^\n]*?(https?:\/\/[^\s\"\'\<\>\)\]]+)',
# Full PowerShell command patterns (with powershell prefix)
# powershell -c iex(iwr -Uri IP/URL -UseBasicParsing)
'ps_iex_iwr': r'powershell[^\n]*?(?:iex|Invoke-Expression)\s*\(\s*(?:iwr|Invoke-WebRequest)[^\)]*?(?:-Uri\s+)?[\'\"]*?(https?:\/\/[^\s\"\'\)\]]+|[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}[^\s\"\'\)\]]*)',
# powershell -c "IEX(New-Object Net.WebClient).DownloadString('URL')"
'ps_iex_webclient': r'powershell[^\n]*?(?:IEX|Invoke-Expression)\s*\(\s*(?:\(?\s*New-Object\s+)?(?:System\.)?Net\.WebClient[^\)]*?\.DownloadString\s*\(\s*[\'\"](https?:\/\/[^\s\"\'\)\]]+)[\'\"]',
# powershell with -Uri parameter and IP or URL
'ps_uri_param': r'powershell[^\n]*?-Uri\s+[\'\"]*?(https?:\/\/[^\s\"\'\)\]]+|[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}(?::\d+)?[^\s\"\'\)\]]*)',
# powershell with Invoke-RestMethod
'ps_irm': r'powershell[^\n]*?(?:Invoke-RestMethod|irm)\s+[\'\"]*?(https?:\/\/[^\s\"\'\)\]]+)',
# powershell with Start-BitsTransfer
'ps_bits': r'powershell[^\n]*?Start-BitsTransfer[^\n]*?-Source\s+[\'\"](https?:\/\/[^\s\"\'\)\]]+)[\'\"]',
# IEX with DownloadString (standalone in embedded code)
'iex_downloadstring': r'(?:IEX|Invoke-Expression)\s*\([^\)]*?\.DownloadString\s*\(\s*[\'\"](https?:\/\/[^\s\"\'\)\]]+)[\'\"]',
# Invoke-RestMethod standalone
'irm_standalone': r'(?:Invoke-RestMethod|irm)\s+[\'\"]*?(https?:\/\/[^\s\"\'\)\]]+)[\'\"]?',
# certutil download
'certutil': r'certutil[^\n]*?-urlcache[^\n]*?-(?:split\s+-)?f\s+[\'\"]*?(https?:\/\/[^\s\"\'\)\]]+)',
# bitsadmin download
'bitsadmin': r'bitsadmin[^\n]*?\/transfer[^\n]*?(https?:\/\/[^\s\"\'\)\]]+)',
# curl.exe (Windows)
'curl_exe': r'curl(?:\.exe)?\s+[^\n]*?[\'\"]*?(https?:\/\/[^\s\"\'\)\]]+)',
# New-Object Net.WebClient with DownloadFile
'webclient_downloadfile': r'Net\.WebClient[^\n]*?\.DownloadFile\s*\(\s*[\'\"](https?:\/\/[^\s\"\'\)\]]+)[\'\"]',
# WebRequest.Create
'webrequest': r'\[?(?:System\.)?Net\.WebRequest\]?::Create\s*\(\s*[\'\"](https?:\/\/[^\s\"\'\)\]]+)[\'\"]',
# Enhanced PowerShell download patterns
'ps_irm_pipe_iex': r'irm\s+["\']?(https?://[^"\'\)\s]+)["\']?\s*\|\s*iex',
'ps_curl_pipe_iex': r'curl\s+["\']?(https?://[^"\'\)\s]+)["\']?\s*\|\s*iex',
'ps_wget_pipe_iex': r'wget\s+["\']?(https?://[^"\'\)\s]+)["\']?\s*\|\s*iex',
'ps_iwr_outfile': r'(?:iwr|Invoke-WebRequest)\s+["\']?(https?://[^"\'\)\s]+)["\']?\s+-OutFile\s+[^\s;"\']+',
'ps_image_download': r'Invoke-(?:WebRequest|RestMethod)\s+[^\n]*?["\']?(https?://[^\s"\']+\.(?:jpg|jpeg|png|gif|bmp|webp))["\']?[^\n]*-OutFile',
# Hex-encoded IP patterns
'mshta_hex_ip': r'mshta\s+["\']?((?:https?://)?(?:0x[0-9a-fA-F]+\.){3}0x[0-9a-fA-F]+[^\s"\'\)]*)',
'hex_ip_url': r'(https?://(?:0x[0-9a-fA-F]{1,2}\.){3}0x[0-9a-fA-F]{1,2}[^\s"\'\)\]]*)',
'decimal_ip': r'(https?://\d{8,10}(?::\d+)?[^\s"\'\)\]]*)',
'octal_ip': r'(https?://(?:0[0-7]{1,3}\.){3}0[0-7]{1,3}(?::\d+)?[^\s"\'\)\]]*)',
# macOS terminal attack patterns
'curl_bash_url': r'curl\s+(?:-[a-zA-Z]+\s+)*["\']?(https?://[^\s"\']+)["\']?\s*\|\s*(?:ba)?sh',
'wget_bash_url': r'wget\s+["\']?(https?://[^\s"\']+)["\']?\s*\|\s*(?:ba)?sh',
'osascript_url': r'osascript\s+-e[^\n]*["\']?(https?://[^\s"\']+)["\']?',
# WinHttp/VBScript patterns
'vbs_open_get_url': r'\.Open\s+["\']GET["\'][^;]*?["\'](https?://[^"\'\)\s]+)["\']',
'wscript_vbs_url': r'wscript\s+//E:VBScript[^\n]*["\'](https?://[^\s"\']+)["\']',
# Steganography/image payload patterns
'ps_image_extract_url': r'(?:iwr|Invoke-WebRequest|curl|wget)[^\n]*["\']?(https?://[^\s"\']+\.(?:jpg|jpeg|png|gif|bmp|webp))["\']?',
'ps_bitmap_url': r'New-Object\s+System\.Drawing\.Bitmap[^\n]*["\']?(https?://[^\s"\']+)["\']?',
'ps_downloadfile_image_url': r'DownloadFile\s*\(\s*["\']?(https?://[^\s"\']+\.(?:jpg|jpeg|png|gif|bmp|webp))["\']?',
# Extended PowerShell command patterns
'ps_hidden': r'powershell(?:\.exe)?\s+-w\s+hidden[^\n]*["\']?(https?://[^\s"\']+)["\']?',
'ps_noprofile': r'powershell(?:\.exe)?\s+-noprofile[^\n]*["\']?(https?://[^\s"\']+)["\']?',
'ps_bypass': r'powershell(?:\.exe)?\s+-ExecutionPolicy\s+[Bb]ypass[^\n]*["\']?(https?://[^\s"\']+)["\']?',
'ps_cmd_start': r'cmd\s+/c\s+start\s+/min\s+powershell[^\n]*["\']?(https?://[^\s"\']+)["\']?',
'ps_webclient_var': r'\$\w+\s*=\s*New-Object\s+(?:System\.)?Net\.WebClient;\s*\$\w+\.Download(?:String|File)\s*\(\s*["\']?(https?://[^\s"\']+)["\']?',
'ps_env_temp': r'-OutFile\s+\$env:Temp[^\n]*["\']?(https?://[^\s"\']+)["\']?',
# JavaScript embedded command patterns
'js_const_cmd': r'const\s+(?:command|cmd|text)\s*=\s*["\'\`][^"\'\`]*?(https?://[^\s"\'\`]+)',
'js_var_cmd': r'var\s+(?:command|cmd|text)\s*=\s*["\'\`][^"\'\`]*?(https?://[^\s"\'\`]+)',
'js_let_cmd': r'let\s+(?:command|cmd|text)\s*=\s*["\'\`][^"\'\`]*?(https?://[^\s"\'\`]+)',
}
# command extraction
COMMAND_PATTERNS = {
'msiexec_full': r'(msiexec\s*[\/\\][^\n\r\<\>\"\'\;]{10,})',
'mshta_full': r'(mshta\s+[^\n\r\<\>\"\'\;]{10,})',
'powershell_full': r'(powershell[^\n\r\<\>\"\'\;]{20,})',
'cmd_full': r'(cmd\s*[\/\\][^\n\r\<\>\"\'\;]{20,})',
'curl_bash_full': r'(curl\s+[^\|]+\|\s*(?:ba)?sh)',
'wget_bash_full': r'(wget\s+[^\|]+\|\s*(?:ba)?sh)',
'unc_path': r'(\\\\[^\s"\'<>\)\(]+\\[^\s"\'<>\)\(]+\.(?:ps1|bat|cmd|hta))',
}
def is_valid_c2_url(url):
"""Validate that extracted URL looks like a real C2 URL, not garbage"""
if not url:
return False
url = url.strip()
if not url.startswith('http://') and not url.startswith('https://'):
return False
try:
parsed = urlparse(url)
if not parsed.netloc:
return False
domain = parsed.netloc.split(':')[0]
if len(domain) < 3:
return False
if not re.match(r'^[a-zA-Z0-9]([a-zA-Z0-9\-\.]*[a-zA-Z0-9])?$', domain):
return False
if '..' in domain or domain.startswith('.') or domain.endswith('.'):
return False
if len(url) > 2048:
return False
except:
return False
return True
def normalize_url(target):
"""Normalize a domain or URL to a proper URL format"""
target = target.strip()
if not target:
return None
if not target.startswith('http://') and not target.startswith('https://'):
target = 'https://' + target
return target
def fetch_page_content(url, timeout=30):
"""Fetch HTML content from a URL"""
request_headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
}
try:
response = requests.get(url, headers=request_headers, timeout=timeout, verify=False, allow_redirects=True)
response.raise_for_status()
return response.text
except requests.exceptions.SSLError:
# Try HTTP if HTTPS fails
if url.startswith('https://'):
http_url = url.replace('https://', 'http://', 1)
try:
response = requests.get(http_url, headers=request_headers, timeout=timeout, verify=False, allow_redirects=True)
response.raise_for_status()
return response.text
except Exception as e:
print(f"[!] Error fetching {http_url}: {e}")
return None
return None
except requests.exceptions.RequestException as e:
print(f"[!] Error fetching {url}: {e}")
return None
def extract_c2_from_content(content, source_url=""):
"""Extract C2 URLs and commands from page content"""
results = []
if not content:
return results
# Decode common HTML entities and escape sequences
content_decoded = content
content_decoded = content_decoded.replace('\\/', '/')
content_decoded = content_decoded.replace('&', '&')
content_decoded = content_decoded.replace('"', '"')
content_decoded = content_decoded.replace(''', "'")
content_decoded = content_decoded.replace('<', '<')
content_decoded = content_decoded.replace('>', '>')
# Also check for hex-encoded or unicode-escaped URLs
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
content_decoded = content_decoded.encode().decode('unicode_escape')
except:
pass
# Extract C2 URLs
c2_urls = set()
for pattern_name, pattern in PATTERNS.items():
matches = re.findall(pattern, content_decoded, re.IGNORECASE)
for match in matches:
if isinstance(match, tuple):
match = match[0] if match[0] else match[1] if len(match) > 1 else ""
if match:
url = match.strip()
if is_valid_c2_url(url):
c2_urls.add(url)
# Extract full commands
commands = []
for pattern_name, pattern in COMMAND_PATTERNS.items():
matches = re.findall(pattern, content_decoded, re.IGNORECASE)
for match in matches:
# Clean up the command
cmd = match.strip()
cmd = re.sub(r'\s+', ' ', cmd) # Normalize whitespace
if len(cmd) > 20: # Only include substantial commands
commands.append(cmd)
# Build results
for c2_url in c2_urls:
# Extract domain/IP from C2 URL
try:
parsed = urlparse(c2_url)
c2_domain = parsed.netloc if parsed.netloc else c2_url
except:
c2_domain = c2_url
result = {
'source': source_url,
'c2_url': c2_url,
'c2_domain': c2_domain,
'commands': []
}
# Associate commands that contain this C2 URL
for cmd in commands:
if c2_url in cmd or c2_domain in cmd:
result['commands'].append(cmd)
results.append(result)
# Also add commands that might have URLs we missed
for cmd in commands:
# Check if this command has a URL not already captured
urls_in_cmd = re.findall(r'https?:\/\/[^\s\"\'\<\>\)\]]+', cmd, re.IGNORECASE)
for url in urls_in_cmd:
if url not in c2_urls and is_valid_c2_url(url):
try:
parsed = urlparse(url)
c2_domain = parsed.netloc if parsed.netloc else url
except:
c2_domain = url
results.append({
'source': source_url,
'c2_url': url,
'c2_domain': c2_domain,
'commands': [cmd]
})
c2_urls.add(url)
return results
def defang_url(url):
"""Defang a URL for safe display/storage"""
return url.replace(".", "[.]").replace("http", "hxxp")
def process_single_target(target, verbose=False):
"""Process a single domain/URL and extract C2 information"""
url = normalize_url(target)
if not url:
return []
if verbose:
print(f"[*] Fetching: {url}")
content = fetch_page_content(url)
if not content:
if verbose:
print(f"[!] Failed to fetch content from {url}")
return []
if verbose:
print(f"[*] Analyzing content ({len(content)} bytes)...")
results = extract_c2_from_content(content, url)
if verbose:
if results:
print(f"[+] Found {len(results)} C2 indicator(s)")
else:
print(f"[-] No ClickFix indicators found")
return results
def _print_result(r, defang=True, show_commands=True):
"""Print one C2 result to console (Source, C2 Domain, C2 URL, Commands)."""
c2_display = defang_url(r['c2_url']) if defang else r['c2_url']
domain_display = defang_url(r['c2_domain']) if defang else r['c2_domain']
print(f" Source: {r['source']}")
print(f" C2 Domain: {domain_display}")
print(f" C2 URL: {c2_display}")
if show_commands and r['commands']:
print(" Commands:")
for cmd in r['commands']:
display_cmd = cmd[:200] + "..." if len(cmd) > 200 else cmd
print(f" {display_cmd}")
def _format_source_block(r, defang=True):
"""Format one result as Source / C2 / Command block for file output."""
c2_display = defang_url(r['c2_url']) if defang else r['c2_url']
lines = ["Source: " + r['source'], "C2: " + c2_display]
if r.get('commands'):
cmd_text = " | ".join(c[:500] + ("..." if len(c) > 500 else "") for c in r['commands'])
lines.append("Command: " + cmd_text)
else:
lines.append("Command: ")
return "\n".join(lines) + "\n---\n"
def process_file(filepath, verbose=False, defang=True, show_commands=True, c2only=False, c2only_source=False, output_file=None, unique=False):
"""Process a file containing list of domains/URLs. Prints each C2 finding to console as found. When c2only or c2only_source=True, only output lines for targets where C2 was found. When output_file is set, write to file as found. When c2only_source=True, file output is Source/C2/Command blocks."""
all_results = []
only_c2 = c2only or c2only_source
if not os.path.exists(filepath):
print(f"[!] Error: File '{filepath}' not found")
return all_results
with open(filepath, 'r') as f:
targets = [line.strip() for line in f if line.strip() and not line.startswith('#')]
print(f"[*] Processing {len(targets)} target(s) from {filepath}")
out_f = None
written_urls = set()
if output_file:
out_f = open(output_file, 'w')
try:
for i, target in enumerate(targets, 1):
if not only_c2:
if verbose:
print(f"\n[{i}/{len(targets)}] Processing: {target}")
else:
print(f"[{i}/{len(targets)}] {target}", end=" ... ")
results = process_single_target(target, verbose=verbose)
if results:
if out_f:
for r in results:
u = r['c2_url']
if not unique or u not in written_urls:
if unique:
written_urls.add(u)
if c2only_source:
out_f.write(_format_source_block(r, defang=defang))
else:
out_f.write(u + '\n')
out_f.flush()
if not verbose:
if not only_c2:
print(f"found {len(results)} C2(s)")
else:
print(f"[{i}/{len(targets)}] {target} found {len(results)} C2(s)")
for r in results:
_print_result(r, defang=defang, show_commands=show_commands)
else:
if only_c2:
print(f"[{i}/{len(targets)}] {target} found {len(results)} C2(s)")
for r in results:
_print_result(r, defang=defang, show_commands=show_commands)
else:
if not only_c2:
if not verbose:
print("no C2 found")
all_results.extend(results)
finally:
if out_f:
out_f.close()
return all_results
def output_results(results, unique=False, output_file=None, defang=True, show_commands=True, print_console=True, file_written_incrementally=None):
"""Output results to stdout and optionally to file. When print_console=False (e.g. list mode already printed), only write file and summary. When file_written_incrementally is set, skip file write and only print summary for that path."""
if unique and not file_written_incrementally:
seen_urls = set()
unique_results = []
for r in results:
if r['c2_url'] not in seen_urls:
seen_urls.add(r['c2_url'])
unique_results.append(r)
results = unique_results
if print_console:
print(f"\n[*] Unique C2s: {len(results)}")
if not results:
print("\n[!] No ClickFix C2 indicators found")
return
output_lines = [r['c2_url'] for r in results]
if print_console:
print("\n" + "=" * 70)
print("CLICKFIX C2 EXTRACTION RESULTS")
print("=" * 70)
for r in results:
c2_display = defang_url(r['c2_url']) if defang else r['c2_url']
domain_display = defang_url(r['c2_domain']) if defang else r['c2_domain']
print(f"\nSource: {r['source']}")
print(f"C2 Domain: {domain_display}")
print(f"C2 URL: {c2_display}")
if show_commands and r['commands']:
print("Commands:")
for cmd in r['commands']:
display_cmd = cmd[:200] + "..." if len(cmd) > 200 else cmd
print(f" {display_cmd}")
print("\n" + "=" * 70)
if output_file and not file_written_incrementally:
with open(output_file, 'w') as f:
for line in output_lines:
f.write(line + '\n')
if print_console:
print(f"\n[+] C2 URLs saved to: {output_file}")
else:
print(f"\n[*] Total: {len(results)} C2(s). C2 URLs saved to: {output_file}")
elif file_written_incrementally:
print(f"\n[*] Total: {len(results)} C2(s). C2 URLs saved to: {file_written_incrementally}")
def main():
parser = argparse.ArgumentParser(
description='ClickFix Campaign C2 Extractor - Extracts C2 URLs from MSHTA/MSIEXEC/PowerShell payloads',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
Single domain:
python clickfix_extractor.py -d example.com
python clickfix_extractor.py -d example.com/malicious/path
File with list of domains:
python clickfix_extractor.py -l domains.txt -o c2_results.txt
python clickfix_extractor.py -l domains.txt -o c2_results.txt --unique
Additional options:
python clickfix_extractor.py -d example.com --no-defang
python clickfix_extractor.py -l domains.txt -o results.txt --unique -v
python clickfix_extractor.py -l domains.txt --c2only
python clickfix_extractor.py -l domains.txt -o c2_only.txt --c2only
python clickfix_extractor.py -l domains.txt -o c2_source.txt --c2only-source
python clickfix_extractor.py -l domains.txt -o c2_source.txt --c2only-source --unique
Detection patterns:
- msiexec /i https://... (MSIEXEC external URL)
- mshta https://... (MSHTA HTTP payloads)
- powershell iwr/Invoke-WebRequest with URLs
- PowerShell DownloadString/DownloadFile
- URLs with IP addresses
"""
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--domain', '-d',
help='Single domain or domain/path to analyze (e.g., example.com or example.com/path)')
group.add_argument('--list', '-l',
help='Text file containing list of domains/paths (one per line)')
parser.add_argument('--output', '-o',
default=None,
help='Output file for C2 URLs (default: stdout only)')
parser.add_argument('--unique', '-u',
action='store_true',
help='Deduplicate results (output unique C2s only)')
parser.add_argument('--no-defang',
action='store_true',
help='Do not defang URLs in output (show raw URLs)')
parser.add_argument('--no-commands',
action='store_true',
help='Do not show extracted commands in output')
parser.add_argument('--verbose', '-v',
action='store_true',
help='Verbose output')
parser.add_argument('--timeout', '-t',
type=int,
default=30,
help='Request timeout in seconds (default: 30)')
parser.add_argument('--c2only',
action='store_true',
help='File mode only: print or write only entries where C2 was found; suppress no C2 found lines')
parser.add_argument('--c2only-source',
action='store_true',
help='File mode only: like --c2only but output includes source URL, command, and C2; works with --unique')
args = parser.parse_args()
print("[*] ClickFix C2 Extractor")
print("[*] Searching for MSHTA/MSIEXEC/PowerShell C2 indicators\n")
results = []
defang = not args.no_defang
show_commands = not args.no_commands
if args.domain:
results = process_single_target(args.domain, verbose=args.verbose)
output_results(
results,
unique=args.unique,
output_file=args.output,
defang=defang,
show_commands=show_commands,
print_console=True
)
elif args.list:
results = process_file(
args.list,
verbose=args.verbose,
defang=defang,
show_commands=show_commands,
c2only=args.c2only,
c2only_source=args.c2only_source,
output_file=args.output,
unique=args.unique
)
output_results(
results,
unique=args.unique,
output_file=args.output,
defang=defang,
show_commands=show_commands,
print_console=False,
file_written_incrementally=args.output
)
if __name__ == "__main__":
main()