Repository navigation
Expand file tree
/
Copy pathclickgrab.py
More file actions
executable file
·2255 lines (1927 loc) · 95.2 KB
/
Copy pathclickgrab.py
File metadata and controls
executable file
·2255 lines (1927 loc) · 95.2 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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
ClickGrab
=========
URL Analyzer & Threat-Intel Collector for Fake CAPTCHA ("ClickFix") campaigns.
This command-line tool fetches suspect URLs (live feeds or user-supplied),
downloads their HTML, and statically analyses the content for indicators of
compromise (PowerShell, OAuth redirection abuse, clipboard hijacking, fake
CAPTCHAs, etc.). It leverages a pattern library centralised in
`models.CommonPatterns` and modern Pydantic v2 models to return strongly-typed
results that can be rendered as HTML dashboards or ingested as JSON/CSV.
Key Features
------------
• Pull recent feeds from **URLhaus** & **AlienVault OTX** (tag-filtered).
• Detect and decode Base64, obfuscated JavaScript, encoded/hidden PowerShell.
• Extract URLs, IPs, clipboard commands, OAuth flows, and more.
• Risk-score sites and commands; generate HTML/JSON/CSV reports.
• Designed for automation — GitHub Actions workflow provided.
Author : Michael Haag <https://github.com/MHaggis/ClickGrab>
License: Apache-2.0
"""
import argparse
import csv
import hashlib
import json
import logging
import os
import pathlib
import sys
from datetime import datetime
from pathlib import Path
from typing import List, Dict, Optional, Tuple
from urllib.parse import urlparse
import requests
from dotenv import load_dotenv
import extractors
from models import (
ClickGrabConfig, AnalysisResult, AnalysisReport,
AnalysisVerdict, ReportFormat, CommandRiskLevel, JavaScriptRedirectChain
)
from redirect_follower import collect_redirects
DEFAULT_CLICKFIX_GIST_ID = "9f563dfb78a06fad5db794f33ba93a3f"
DEFAULT_CLICKFIX_GIST_FILENAME = "clickfix_domains.txt"
CLICKFIX_GIST_CACHE_FILE = pathlib.Path("analysis/clickfix_gist_cache.json")
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("clickgrab")
BASE_DIR = Path(__file__).resolve().parent.parent
def load_environment() -> None:
"""Load environment variables from config/env or env file.
Returns:
Optional[str]: OTX API key if found, None otherwise
"""
# Try loading from config/env first
config_env_path = BASE_DIR / "config" / "env"
if os.path.exists(config_env_path):
load_dotenv(config_env_path)
else:
# Fall back to env in root directory
load_dotenv()
def sanitize_url(url: str) -> str:
"""Clean up defanged URLs to make them processable.
Common defanging patterns in threat intelligence:
- [.] -> .
- [:] -> :
- hxxp -> http
- hxxps -> https
- (:) -> :
- (.) -> .
Args:
url: The potentially defanged URL
Returns:
str: Sanitized URL ready for processing
"""
if not url:
return url
# Make a copy to work with
sanitized = url.strip()
# Remove common defanging patterns
defang_patterns = [
('[.]', '.'), # [.] -> .
('[:]', ':'), # [:] -> :
('(.)', '.'), # (.) -> .
('(:)', ':'), # (:) -> :
('[://]', '://'), # [://] -> ://
('hxxp://', 'http://'), # hxxp:// -> http://
('hxxps://', 'https://'), # hxxps:// -> https://
('hXXp://', 'http://'), # hXXp:// -> http://
('hXXps://', 'https://'), # hXXps:// -> https://
]
for pattern, replacement in defang_patterns:
sanitized = sanitized.replace(pattern, replacement)
# Log if we made changes
if sanitized != url:
logger.info(f"URL defanged: '{url}' -> '{sanitized}'")
return sanitized
def _read_text_capped(response, max_bytes: int = 3_000_000, deadline: Optional[float] = None) -> str:
"""Read a streamed response body with a hard byte cap AND wall-clock deadline.
requests' read timeout only bounds the gap *between* chunks, so a host that
trickles one byte just under each read-timeout boundary can keep a single GET
alive indefinitely. Reading via ``iter_content`` against a ``time.monotonic``
deadline bounds total transfer time regardless of how the server behaves.
"""
import time as _t
chunks = []
total = 0
try:
for chunk in response.iter_content(8192):
if chunk:
chunks.append(chunk)
total += len(chunk)
if total >= max_bytes:
break
if deadline is not None and _t.monotonic() > deadline:
logger.debug("Body read hit wall-clock deadline; returning partial content.")
break
except requests.RequestException as exc:
logger.debug(f"Stream read interrupted: {exc}")
raw = b"".join(chunks)
enc = response.encoding or "utf-8"
try:
return raw.decode(enc, errors="ignore")
except (LookupError, TypeError):
return raw.decode("utf-8", errors="ignore")
def get_html_content(
url: str,
proxies: Dict[str, str] | None,
max_redirects: int = 2,
headers: Dict[str, str] | None = None,
) -> Optional[str]:
"""Fetch HTML content from a URL.
Args:
url: The URL to fetch content from
max_redirects: Maximum number of redirects to follow
headers: Optional headers merged over the defaults; overriding User-Agent drops the Sec-CH-UA* hints
Returns:
str: HTML content if successful, None otherwise
"""
try:
# Check if URL is from a CDN known to host malware
suspicious_cdns = [
'cdn.jsdelivr.net',
'code.jquery.com',
'unpkg.com', # Another potentially abused CDN
'stackpath.bootstrapcdn.com' # Also potentially abused
]
parsed_url = urlparse(url)
if any(cdn in parsed_url.netloc.lower() for cdn in suspicious_cdns):
logger.warning(f"URL {url} is from a CDN known to host malware. Proceeding with analysis...")
default_headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
'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.9',
'Sec-CH-UA': '"Chromium";v="122", "Not(A:Brand";v="24", "Google Chrome";v="122"',
'Sec-CH-UA-Mobile': '?0',
'Sec-CH-UA-Platform': '"Windows"',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
'Upgrade-Insecure-Requests': '1',
}
if headers and 'User-Agent' in headers:
# Sec-CH-UA* describe the default Windows Chrome and would contradict another UA
default_headers = {k: v for k, v in default_headers.items() if not k.lower().startswith('sec-ch-ua')}
headers = {**default_headers, **(headers or {})}
# Create a session to handle redirects
import time as _time
body_deadline = _time.monotonic() + 20 # total wall-clock cap for this fetch
with requests.Session() as session:
session.max_redirects = max_redirects
# (connect, read) timeouts bound each socket op; stream=True + a capped,
# deadline-bounded body read bounds TOTAL transfer time, so a host that
# trickles bytes forever can't freeze a scan (slowloris-style C2).
response = session.get(
url, headers=headers, timeout=(5, 15),
allow_redirects=True, verify=False, stream=True, proxies=proxies
)
response.raise_for_status()
# Log redirect chain if any redirects occurred
if len(response.history) > 0:
logger.info(f"Redirect chain for {url}:")
for r in response.history:
logger.info(f" {r.status_code}: {r.url}")
logger.info(f" Final URL: {response.url}")
return _read_text_capped(response, max_bytes=3_000_000, deadline=body_deadline)
except requests.RequestException as e:
logger.error(f"Error fetching URL {url}: {e}")
return None
def download_urlhaus_data(limit: Optional[int] = None, tags: Optional[List[str]] = None) -> List[str]:
"""Download online URLs from URLhaus.
Prefers the authenticated API (if env var URLHAUS_AUTH_KEY or URLHAUS_API_KEY is set),
and falls back to the public CSV feed otherwise.
Args:
limit: Maximum number of URLs to return
tags: List of tags to filter by (e.g. ['FakeCaptcha', 'ClickFix', 'click'])
Returns:
List[str]: List of URLs matching the criteria
"""
if tags is None:
tags = ['FakeCaptcha', 'ClickFix', 'click', 'fakecloudflarecaptcha']
# 1) Try authenticated API first if a key is present
import os
api_key = os.getenv('URLHAUS_AUTH_KEY') or os.getenv('URLHAUS_API_KEY')
if api_key:
try:
# Collect from both recent and tag endpoints
use_limit = max(1, min(int(limit) if limit else 1000, 1000))
combined_entries = []
# 1) Recent
recent_url = f"https://urlhaus-api.abuse.ch/v1/urls/recent/limit/{use_limit}/"
logger.info("Fetching URLhaus recent URLs via Auth API…")
resp = requests.get(recent_url, headers={"Auth-Key": api_key}, timeout=30)
resp.raise_for_status()
data_recent = resp.json()
if data_recent.get('query_status') != 'ok':
logger.warning(f"URLhaus API recent status: {data_recent.get('query_status')}")
combined_entries.extend(data_recent.get('urls', []))
# 2) Tag queries (historical)
tag_endpoint = "https://urlhaus-api.abuse.ch/v1/tag/"
seen_urls = set(e.get('url') for e in combined_entries if isinstance(e, dict))
for tg in set(t.lower() for t in tags):
try:
resp_t = requests.post(
tag_endpoint,
headers={"Auth-Key": api_key},
data={"tag": tg, "limit": str(use_limit)},
timeout=30,
)
resp_t.raise_for_status()
data_t = resp_t.json()
if data_t.get('query_status') != 'ok':
logger.debug(f"Tag query for '{tg}' returned status {data_t.get('query_status')}")
continue
for e in data_t.get('urls', []):
u = e.get('url')
if u and u not in seen_urls:
combined_entries.append(e)
seen_urls.add(u)
except Exception as te:
logger.debug(f"URLhaus tag query error for '{tg}': {te}")
# Filter combined entries
urls: List[str] = []
total_processed = 0
for entry in combined_entries:
total_processed += 1
entry_url = entry.get('url', '')
entry_tags = entry.get('tags') or []
entry_tags_lc = [t.lower() for t in entry_tags if isinstance(t, str)]
url_status = (entry.get('url_status') or '').lower()
logger.debug(f"\nProcessing API entry #{total_processed}:")
logger.debug(f" URL: {entry_url}")
logger.debug(f" Tags: {entry_tags_lc}")
logger.debug(f" Status: {url_status}")
# Tag filter
matching_tags = [tag for tag in tags if tag.lower() in entry_tags_lc]
if not matching_tags:
continue
# Only consider online pages likely to be HTML landing pages
if url_status != 'online':
continue
if not (entry_url.endswith('/') or entry_url.endswith('html') or entry_url.endswith('htm')):
continue
urls.append(entry_url)
if limit and len(urls) >= limit:
break
if urls:
logger.info(f"Found {len(urls)} matching URLs from {total_processed} API entries (recent+tag)")
return urls
else:
logger.info("No matching URLs found via API (recent+tag), falling back to CSV feed…")
except Exception as e:
logger.error(f"URLhaus API error: {e}. Falling back to CSV feed…")
# 2) Fallback to CSV feed
csv_url = "https://urlhaus.abuse.ch/downloads/csv_online"
try:
logger.info("Downloading URL data from URLhaus CSV feed…")
response = requests.get(csv_url, timeout=30)
response.raise_for_status()
lines = response.text.split('\n')
header_idx = next(i for i, line in enumerate(lines) if line.startswith('# id'))
clean_header = lines[header_idx].replace('# ', '')
csv_data = [clean_header] + [line for line in lines[header_idx + 1:] if line and not line.startswith('#')]
reader = csv.DictReader(csv_data)
urls = []
total_processed = 0
for row in reader:
if not row:
continue
total_processed += 1
entry_url = row['url']
url_tags = row['tags'].lower()
threat = row.get('threat', '')
logger.debug(f"\nProcessing CSV entry #{total_processed}:")
logger.debug(f" URL: {entry_url}")
logger.debug(f" Tags: {url_tags}")
logger.debug(f" Threat: {threat}")
matching_tags = [tag for tag in tags if tag.lower() in url_tags]
if matching_tags and (entry_url.endswith('/') or entry_url.endswith('html') or entry_url.endswith('htm')):
urls.append(entry_url)
if limit and len(urls) >= limit:
break
logger.info(f"Found {len(urls)} matching URLs from {total_processed} CSV entries")
return urls
except Exception as e:
logger.error(f"Error downloading URLhaus CSV data: {e}")
return []
def get_latest_gist_url(gist_id: str, filename: str) -> Optional[str]:
"""Fetch the latest raw URL for a specific file in a GitHub Gist using the API.
This ensures we always get the most recent version even if the gist is updated.
Args:
gist_id: The GitHub Gist ID
filename: The name of the file within the gist
Returns:
Optional[str]: The raw URL to the latest version, or None if unavailable
"""
try:
api_url = f"https://api.github.com/gists/{gist_id}"
logger.debug(f"Fetching latest gist metadata from GitHub API: {api_url}")
headers = {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'ClickGrab-URLAnalyzer'
}
response = requests.get(api_url, headers=headers, timeout=30)
response.raise_for_status()
gist_data = response.json()
# Get the file data from the gist
if 'files' in gist_data and filename in gist_data['files']:
file_data = gist_data['files'][filename]
raw_url = file_data.get('raw_url')
if raw_url:
logger.info(f"Retrieved latest raw URL for {filename}")
return raw_url
else:
logger.warning(f"No raw_url found for {filename} in gist {gist_id}")
return None
else:
logger.warning(f"File {filename} not found in gist {gist_id}")
return None
except requests.RequestException as exc:
logger.warning(f"Could not fetch gist metadata from API: {exc}. Falling back to direct URL.")
# Fall back to the standard raw URL format (always points to latest)
return f"https://gist.githubusercontent.com/{gist_id}/raw/{filename}"
except Exception as exc:
logger.warning(f"Unexpected error fetching gist metadata: {exc}")
return f"https://gist.githubusercontent.com/{gist_id}/raw/{filename}"
def fetch_clickfix_gist(gist_id: str = DEFAULT_CLICKFIX_GIST_ID, filename: str = DEFAULT_CLICKFIX_GIST_FILENAME) -> Tuple[List[str], Optional[str]]:
"""Fetch domain list from the public ClickFix gist feed.
The gist is a simple pipe-delimited table with one domain per row. The
function normalizes the entries, deduplicates them, and returns both the
list of domains and a hash of the raw content to allow change detection.
Args:
gist_id: The GitHub Gist ID
filename: The filename within the gist
Returns:
Tuple[List[str], Optional[str]]: unique domain list and optional SHA256 hash.
"""
try:
# Get the latest raw URL from the GitHub API
url = get_latest_gist_url(gist_id, filename)
if not url:
logger.error("Could not determine gist URL")
return [], None
logger.info(f"Fetching ClickFix gist feed from {url}")
response = requests.get(url, timeout=30)
response.raise_for_status()
raw_text = response.text
content_hash = hashlib.sha256(raw_text.encode("utf-8")).hexdigest()
domains: List[str] = []
seen: set[str] = set()
# Parse line by line - handle both plain text and pipe-delimited formats
for line in raw_text.splitlines():
line = line.strip()
# Skip empty lines
if not line:
continue
# Skip markdown table headers and separators
if line.startswith('|') and ('-' in line or 'domain' in line.lower()):
continue
# Handle pipe-delimited format (| domain |) or plain format
if line.startswith('|'):
cleaned = line.strip('|').strip()
else:
cleaned = line
if not cleaned:
continue
# Domains might include URLs; attempt to normalize
domain = cleaned
if domain.startswith("http"):
try:
parsed = urlparse(domain)
domain = parsed.netloc or parsed.path
except Exception:
logger.debug(f"Could not parse domain entry '{cleaned}'")
continue
domain = domain.strip()
if not domain:
continue
domain = domain.lower()
if domain not in seen:
seen.add(domain)
domains.append(domain)
logger.info(f"Fetched {len(domains)} unique domains from ClickFix gist")
return domains, content_hash
except requests.RequestException as exc:
logger.error(f"Error fetching ClickFix gist feed: {exc}")
return [], None
def load_clickfix_cache(gist_id: str) -> Tuple[Optional[str], List[str]]:
"""Load cached ClickFix gist metadata from disk."""
if not CLICKFIX_GIST_CACHE_FILE.exists():
return None, []
try:
with CLICKFIX_GIST_CACHE_FILE.open("r", encoding="utf-8") as cache_file:
data = json.load(cache_file)
if not isinstance(data, dict):
return None, []
cached_gist_id = data.get("gist_id")
if cached_gist_id and cached_gist_id != gist_id:
logger.info(f"Cached gist ID {cached_gist_id} differs from requested {gist_id}, ignoring cache")
return None, []
cached_hash = data.get("hash")
cached_domains = data.get("domains") or []
if not isinstance(cached_domains, list):
cached_domains = []
# Deduplicate while preserving order
deduped_domains = list(dict.fromkeys(str(domain).lower().strip() for domain in cached_domains if domain))
return cached_hash, deduped_domains
except Exception as exc:
logger.warning(f"Could not read ClickFix gist cache: {exc}")
return None, []
def save_clickfix_cache(hash_value: str, domains: List[str], gist_id: str) -> None:
"""Persist ClickFix gist metadata so future runs can skip unchanged feeds."""
try:
CLICKFIX_GIST_CACHE_FILE.parent.mkdir(parents=True, exist_ok=True)
payload = {
"gist_id": gist_id,
"hash": hash_value,
"domains": domains,
"cached_at": datetime.utcnow().isoformat()
}
with CLICKFIX_GIST_CACHE_FILE.open("w", encoding="utf-8") as cache_file:
json.dump(payload, cache_file, indent=2)
except Exception as exc:
logger.warning(f"Failed to write ClickFix gist cache: {exc}")
def build_urls_from_domains(domains: List[str]) -> List[str]:
"""Convert bare domains into full URLs suitable for analysis."""
urls: List[str] = []
seen: set[str] = set()
for domain in domains:
if not domain:
continue
sanitized = sanitize_url(domain.strip())
if not sanitized:
continue
if not sanitized.startswith(("http://", "https://")):
sanitized = f"https://{sanitized}"
sanitized = sanitized.rstrip("/")
if sanitized not in seen:
seen.add(sanitized)
urls.append(sanitized)
return urls
def collect_clickfix_gist_urls(config: ClickGrabConfig) -> List[str]:
"""Return newly observed ClickFix gist domains as URLs."""
# Use custom gist_id if provided, otherwise use default
gist_id = config.clickfix_gist_id or DEFAULT_CLICKFIX_GIST_ID
filename = DEFAULT_CLICKFIX_GIST_FILENAME
logger.info(f"Collecting domains from ClickFix gist ID: {gist_id}")
domains, new_hash = fetch_clickfix_gist(gist_id, filename)
if not domains:
logger.warning("No domains retrieved from ClickFix gist feed")
return []
cached_hash, cached_domains = load_clickfix_cache(gist_id)
if new_hash and cached_hash and new_hash == cached_hash:
logger.info("ClickFix gist has not changed since the last run. Skipping analysis of cached domains.")
return []
cached_domain_set = set(cached_domains)
new_domains = [domain for domain in domains if domain not in cached_domain_set]
if not new_domains:
logger.info("No new ClickFix domains detected compared to cached run.")
else:
logger.info(f"Identified {len(new_domains)} new ClickFix domains for analysis")
if new_hash:
save_clickfix_cache(new_hash, domains, gist_id)
if not new_domains:
return []
return build_urls_from_domains(new_domains)
def download_otx_data(limit: Optional[int] = None, tags: Optional[List[str]] = None, days: int = 30) -> List[str]:
"""Download URLs from AlienVault OTX.
Args:
limit: Maximum number of URLs to return
tags: List of tags to filter by (e.g. ['FakeCaptcha', 'ClickFix', 'click'])
days: Number of days to look back for indicators
Returns:
List[str]: List of URLs matching the criteria
"""
try:
logger.info(f"Downloading URL data from AlienVault OTX (past {days} days)...")
# Get API key from environment
api_key = os.getenv('OTX_API_KEY')
if not api_key:
logger.error("OTX API key not found. Please set OTX_API_KEY in config/env or env file")
return []
if tags is None:
tags = ['FakeCaptcha', 'ClickFix', 'click', 'fakecloudflarecaptcha']
results = []
try:
# Process each tag
for tag in tags:
logger.debug(f"Searching for indicators with tag: {tag}")
# Build initial query URL - similar to PowerShell approach
query = f"{tag.lower()} modified:<{days}d"
otx_query = f"https://otx.alienvault.com/otxapi/indicators?include_inactive=0&sort=-modified&page=1&limit=100&q={query}&type=URL"
page_count = 1
# Use pagination like in PowerShell script
while otx_query:
logger.debug(f"Fetching page {page_count} from AlienVault OTX...")
# Make request with API key
headers = {'X-OTX-API-KEY': api_key}
response = requests.get(otx_query, headers=headers)
response.raise_for_status()
data = response.json()
# Process indicators from this page
if 'results' in data:
for item in data['results']:
url = item.get('indicator')
if url and (url.endswith('/') or url.endswith('html') or url.endswith('htm')):
# Get additional metadata for the URL
try:
meta_url = f"https://otx.alienvault.com/api/v1/indicators/url/{url}/url_list"
meta_response = requests.get(meta_url, headers=headers)
meta_response.raise_for_status()
meta_data = meta_response.json()
# Log metadata if available
if isinstance(meta_data, dict) and meta_data.get('url_list'):
logger.debug(f"Found URL with metadata: {url}")
if isinstance(meta_data['url_list'], list) and meta_data['url_list']:
first_entry = meta_data['url_list'][0]
logger.debug(f" Added: {first_entry.get('date')}")
else:
logger.debug(f"No metadata available for {url}")
except Exception as e:
logger.debug(f"Could not fetch metadata for {url}: {str(e)}")
if url not in results:
results.append(url)
logger.debug(f"Added URL: {url}")
# Check limit
if limit and len(results) >= limit:
logger.debug(f"Reached limit of {limit} URLs from OTX")
return results[:limit]
# Get next page URL if available
otx_query = data.get('next')
page_count += 1
logger.debug(f"Downloaded {len(results)} URLs so far...")
except Exception as e:
logger.error(f"Error fetching OTX indicators: {e}")
return results
logger.info(f"Found {len(results)} matching URLs from AlienVault OTX")
return results
except Exception as e:
logger.error(f"Error downloading AlienVault OTX data: {e}")
return []
def fetch_and_analyze_external_js(base_url: str, html_content: str, proxies) -> List[str]:
"""Fetch external JavaScript files and analyze them for obfuscation.
This ensures we don't claim "heavy obfuscation" without actually
looking at the JS content.
Args:
base_url: The base URL for resolving relative paths
html_content: The HTML content containing script tags
Returns:
List of obfuscation indicators found in external JS files
"""
from bs4 import BeautifulSoup
from urllib.parse import urljoin
results = []
try:
soup = BeautifulSoup(html_content, "html.parser")
# Find external script tags
external_scripts = []
for script_tag in soup.find_all("script", src=True):
raw_src = script_tag.get("src")
if raw_src:
script_url = urljoin(base_url, raw_src.strip())
if script_url not in external_scripts:
external_scripts.append(script_url)
if not external_scripts:
return results
# Limit to first few external scripts AND a wall-clock budget so this
# stage can never dominate a scan (some hosts trickle bytes forever).
import time as _time
_budget_start = _time.monotonic()
for script_url in external_scripts[:4]:
if _time.monotonic() - _budget_start > 12:
logger.debug("External JS analysis budget (12s) exceeded; stopping early.")
break
try:
logger.debug(f"Fetching external JS for obfuscation analysis: {script_url}")
response = requests.get(
script_url,
timeout=(4, 6),
verify=False,
stream=True,
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"},
proxies=proxies,
)
response.raise_for_status()
# Only analyze first 50KB, bounded by the remaining stage budget so a
# trickling host can't stall mid-download.
js_content = _read_text_capped(
response, max_bytes=50000, deadline=_budget_start + 12
)
# Run obfuscation detection on the actual JS content
obfuscation_hits = extractors.extract_heavy_obfuscation(js_content)
for hit in obfuscation_hits:
# Prefix with the source URL so we know where it came from
results.append(f"[External JS: {script_url}] {hit}")
logger.debug(f"Found {len(obfuscation_hits)} obfuscation patterns in {script_url}")
except requests.RequestException as e:
logger.debug(f"Failed to fetch external JS {script_url}: {e}")
continue
except Exception as e:
logger.debug(f"Error analyzing external JS {script_url}: {e}")
continue
except Exception as e:
logger.debug(f"Error in external JS analysis: {e}")
return results
def analyze_url(
url: str,
proxies: Dict[str, str] | None = None,
headers: Dict[str, str] | None = None,
) -> Optional[AnalysisResult]:
"""Analyze a URL for malicious content and return results as a Pydantic model.
Args:
url: The URL to analyze
headers: Optional request headers merged over the defaults (e.g. a custom User-Agent)
Returns:
Optional[AnalysisResult]: Analysis results if successful, None otherwise
"""
logger.info(f"Analyzing URL: {url}")
# Sanitize URL to remove common defanging patterns
url = sanitize_url(url)
# If the URL doesn't start with http:// or https://, assume https://
if not url.startswith(('http://', 'https://')):
url = 'https://' + url
# Create base analysis result
result = AnalysisResult(
URL=url,
RawHTML=""
)
# Get HTML content
html_content = get_html_content(url, proxies=proxies, headers=headers)
if not html_content:
logger.error(f"Failed to retrieve content from {url}")
# Still return a result with empty content and failed status
result.RawHTML = "ERROR: Failed to retrieve content"
result.SuspiciousKeywords = ["failed_to_retrieve"]
# Mark as non-suspicious since we couldn't analyze it
return result
# Update with actual content
result.RawHTML = html_content
# Extract various indicators using optimized extractor functions
result.Base64Strings = extractors.extract_base64_strings(html_content)
result.URLs = extractors.extract_urls(html_content)
result.PowerShellCommands = extractors.extract_powershell_commands(html_content)
result.MshtaCommands = extractors.extract_mshta_commands(html_content)
result.ConhostCommands = extractors.extract_conhost_commands(html_content)
result.EncodedPowerShell = extractors.extract_encoded_powershell(html_content)
result.IPAddresses = extractors.extract_ip_addresses(html_content)
result.ClipboardCommands = extractors.extract_clipboard_commands(html_content)
result.SuspiciousKeywords = extractors.extract_suspicious_keywords(html_content)
result.ClipboardManipulation = extractors.extract_clipboard_manipulation(html_content)
result.PowerShellDownloads = extractors.extract_powershell_downloads(html_content)
result.CaptchaElements = extractors.extract_captcha_elements(html_content)
result.ObfuscatedJavaScript = extractors.extract_obfuscated_javascript(html_content)
result.EtherhidingJavaScript = extractors.extract_etherhiding_payload(html_content, proxies=proxies)
result.SuspiciousCommands = extractors.extract_suspicious_commands(html_content)
# Add new extractions
result.BotDetection = extractors.extract_bot_detection(html_content)
result.SessionHijacking = extractors.extract_session_hijacking(html_content)
result.ProxyEvasion = extractors.extract_proxy_evasion(html_content)
result.JavaScriptRedirects = extractors.extract_js_redirects(html_content)
result.Base64XoredJavaScript = extractors.extract_base64_and_xored_js(html_content)
result.ParkingPageLoaders = extractors.extract_parking_page_loaders(html_content)
# Add November 2025 threat extractions (fake video conferencing, ClickFix instructions, steganography)
result.FakeVideoConferencing = extractors.extract_fake_video_conferencing(html_content)
result.ClickFixInstructions = extractors.extract_clickfix_instructions(html_content)
result.SteganographyIndicators = extractors.extract_steganography_indicators(html_content)
result.FakeWindowsUpdate = extractors.extract_fake_windows_update(html_content)
result.FakeCloudflare = extractors.extract_fake_cloudflare(html_content)
result.HeavyObfuscation = extractors.extract_heavy_obfuscation(html_content)
# Add December 2025 threat extractions (macOS attacks, AI chat links, ErrTraffic toolkit)
result.MacOSTerminalCommands = extractors.extract_macos_terminal_commands(html_content)
result.SharedAIChatLinks = extractors.extract_shared_ai_chat_links(html_content)
result.WinHttpVBScript = extractors.extract_winhttp_vbscript(html_content)
result.FakeGlitchLures = extractors.extract_fake_glitch_lures(html_content)
result.HexEncodedIPs = extractors.extract_hex_encoded_ips(html_content)
# Add 2026 threat extractions (DNS ClickFix, Windows Terminal, WebDAV, CrashFix, etc.)
result.DNSClickFix = extractors.extract_dns_clickfix(html_content)
result.WindowsTerminalClickFix = extractors.extract_windows_terminal_clickfix(html_content)
result.WebDAVClickFix = extractors.extract_webdav_clickfix(html_content)
result.FingerExeAbuse = extractors.extract_finger_exe_abuse(html_content)
result.ConsentFixIndicators = extractors.extract_consentfix_indicators(html_content)
result.FakeSoftwareDownloads = extractors.extract_fake_software_downloads(html_content)
result.LLMArtifactAbuse = extractors.extract_llm_artifact_abuse(html_content)
# 2026: DriveSurge / zTDS (Silent Push) — TDS loader injection + FakeUpdates lures
result.TDSInjection = extractors.extract_tds_injection(html_content)
result.FakeBrowserUpdate = extractors.extract_fake_browser_update(html_content)
# Also check external JS files for obfuscation
external_js_obfuscation = fetch_and_analyze_external_js(url, html_content, proxies)
if external_js_obfuscation:
result.HeavyObfuscation.extend(external_js_obfuscation)
# Collect redirect chains (inline + external + meta) and follow them
try:
redirect_findings = collect_redirects(result.URL, html_content, proxies)
if redirect_findings:
result.RedirectFollows = redirect_findings
for finding in redirect_findings:
if finding.Source == "external_js" and finding.ScriptURL:
result.JavaScriptRedirectChains.append(
JavaScriptRedirectChain(
ScriptURL=finding.ScriptURL,
RedirectType=finding.Method,
DestinationURL=finding.FinalURL or finding.OriginalURL,
Evidence=finding.Evidence,
)
)
except Exception as redirect_exc:
logger.debug(f"Failed to collect redirects for {result.URL}: {redirect_exc}")
logger.debug(f"Analysis complete for {url}. Found {result.TotalIndicators} indicators.")
if result.TotalIndicators > 0:
threat_score = result.ThreatScore
logger.debug(f"Threat score: {threat_score}")
if threat_score >= 60:
logger.warning(f"HIGH THREAT DETECTED in {url} - Score: {threat_score}")
elif threat_score >= 30:
logger.warning(f"MEDIUM THREAT DETECTED in {url} - Score: {threat_score}")
return result
def is_suspicious(result: AnalysisResult) -> bool:
"""Determine if an analysis result indicates a suspicious site.
Args:
result: The analysis result to check
Returns:
bool: True if the site is suspicious, False otherwise
"""
return result.Verdict == AnalysisVerdict.SUSPICIOUS.value
def generate_html_report(results: List[AnalysisResult], config: ClickGrabConfig) -> str:
"""Generate an HTML report from analysis results.
Args:
results: List of analysis results
config: ClickGrab configuration
Returns:
str: Path to the generated HTML report
"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
suspicious_count = sum(1 for result in results if result.Verdict == AnalysisVerdict.SUSPICIOUS.value)
# Output directory
output_dir = config.output_dir
os.makedirs(output_dir, exist_ok=True)
# HTML report path
report_name = f"clickgrab_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
report_path = os.path.join(output_dir, report_name)
# Generate HTML content
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<title>ClickGrab - URL Analysis Report</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 20px; }}
h1, h2, h3 {{ color: #333; }}
.site {{ border: 1px solid #ddd; margin: 10px 0; padding: 10px; border-radius: 5px; }}
.site.suspicious {{ border-color: #ff9999; background-color: #ffeeee; }}
.site-url {{ font-weight: bold; }}
.indicator {{ margin: 5px 0; }}
.indicator-title {{ font-weight: bold; }}
.summary {{ background-color: #f5f5f5; padding: 10px; border-radius: 5px; margin-bottom: 20px; }}
pre {{ background-color: #f8f8f8; padding: 10px; border-radius: 3px; overflow-x: auto; }}
.highlight {{ background-color: yellow; }}
.risk-high {{ color: #d9534f; font-weight: bold; }}
.risk-medium {{ color: #f0ad4e; }}
.risk-low {{ color: #5bc0de; }}
.total-indicators {{ font-size: 1.2em; margin-top: 10px; }}
.score-display {{
display: inline-block;
padding: 5px 10px;
border-radius: 4px;
font-weight: bold;
margin-left: 10px;
color: white;
}}
.score-high {{ background-color: #d9534f; }}
.score-medium {{ background-color: #f0ad4e; }}
.score-low {{ background-color: #5bc0de; }}
.score-none {{ background-color: #5cb85c; }}
</style>
</head>
<body>
<h1>ClickGrab URL Analysis Report</h1>
<div class="summary">
<p><strong>Generated:</strong> {timestamp}</p>
<p><strong>Sites Analyzed:</strong> {len(results)}</p>
<p><strong>Suspicious Sites:</strong> {suspicious_count}</p>
</div>
<h2>Analysis Results</h2>
"""
# Add each site analysis
for result in results:
is_sus = result.Verdict == AnalysisVerdict.SUSPICIOUS.value
sus_class = "suspicious" if is_sus else ""
# Determine threat score styling
threat_score = result.ThreatScore
score_class = "score-none"
if threat_score >= 60:
score_class = "score-high"