-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathekfiddle_scanner.py
More file actions
3777 lines (3195 loc) · 143 KB
/
Copy pathekfiddle_scanner.py
File metadata and controls
3777 lines (3195 loc) · 143 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
import os
import subprocess
import re
import sys
import argparse
import hashlib
import base64
from html.parser import HTMLParser
from urllib.parse import urlparse, urljoin
from dataclasses import dataclass, field
from typing import List, Dict, Tuple, Optional, Set
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)
# Flask is optional - only needed for API server mode
# Import is deferred to avoid requiring Flask for CLI-only usage
FLASK_AVAILABLE = False
try:
from flask import Flask, request as flask_request, jsonify
FLASK_AVAILABLE = True
except ImportError:
pass # Flask will be installed on-demand when --server is used
import threading
import uuid
import time
import json
# Default request headers for browser emulation
DEFAULT_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',
}
@dataclass
class EKFiddleRule:
"""Represents a single EKFiddle detection rule"""
rule_type: str # SourceCode, URI, Headers, IP, Hash
name: str
pattern: str
description: str = ""
severity: str = "med" # high, med, low
has_and_condition: bool = False
and_patterns: List[str] = field(default_factory=list)
def __post_init__(self):
# Extract severity from name if present
name_lower = self.name.lower()
if name_lower.startswith("high:"):
self.severity = "high"
self.name = self.name[5:].strip()
elif name_lower.startswith("med:"):
self.severity = "med"
self.name = self.name[4:].strip()
elif name_lower.startswith("low:"):
self.severity = "low"
self.name = self.name[4:].strip()
# Check for AND conditions
if " *AND* " in self.pattern:
self.has_and_condition = True
self.and_patterns = [p.strip() for p in self.pattern.split(" *AND* ")]
@dataclass
class Detection:
"""Represents a detection result"""
rule: EKFiddleRule
matches: List[str] = field(default_factory=list)
match_contexts: List[str] = field(default_factory=list)
source_url: str = "" # Which resource this detection came from
source_type: str = "" # main_page, script, iframe, css, redirect, data_uri
@dataclass
class RedirectHop:
"""Represents a single redirect hop"""
url: str
status_code: int
headers: Dict[str, str]
content: Optional[str] = None
@dataclass
class ScannableContent:
"""Represents content that can be scanned"""
url: str
content_type: str # main_page, script, iframe, css, data_uri, redirect, inline_script
content: str
headers: Dict[str, str] = field(default_factory=dict)
source: str = "" # Where this was referenced from
@dataclass
class ExtractedResources:
"""Resources extracted from HTML"""
scripts: List[str] = field(default_factory=list) # External script URLs
iframes: List[str] = field(default_factory=list) # Iframe URLs
css: List[str] = field(default_factory=list) # CSS URLs
inline_scripts: List[str] = field(default_factory=list) # Inline script content
inline_styles: List[str] = field(default_factory=list) # Inline style content
data_uris: List[Tuple[str, str]] = field(default_factory=list) # (type, decoded_content)
imports: List[str] = field(default_factory=list) # @import URLs
@dataclass
class ExtractedIOCs:
"""Indicators of Compromise extracted from content"""
ipv4_addresses: Set[str] = field(default_factory=set)
ipv6_addresses: Set[str] = field(default_factory=set)
domains: Set[str] = field(default_factory=set)
urls: Set[str] = field(default_factory=set)
email_addresses: Set[str] = field(default_factory=set)
bitcoin_addresses: Set[str] = field(default_factory=set)
ethereum_addresses: Set[str] = field(default_factory=set)
file_hashes_md5: Set[str] = field(default_factory=set)
file_hashes_sha1: Set[str] = field(default_factory=set)
file_hashes_sha256: Set[str] = field(default_factory=set)
def is_empty(self) -> bool:
"""Check if no IOCs were found"""
return not any([
self.ipv4_addresses, self.ipv6_addresses, self.domains,
self.urls, self.email_addresses, self.bitcoin_addresses,
self.ethereum_addresses, self.file_hashes_md5,
self.file_hashes_sha1, self.file_hashes_sha256
])
def total_count(self) -> int:
"""Get total count of all IOCs"""
return sum([
len(self.ipv4_addresses), len(self.ipv6_addresses), len(self.domains),
len(self.urls), len(self.email_addresses), len(self.bitcoin_addresses),
len(self.ethereum_addresses), len(self.file_hashes_md5),
len(self.file_hashes_sha1), len(self.file_hashes_sha256)
])
@dataclass
class ExtractedPayloads:
"""Extracted malicious payloads and commands"""
powershell_commands: List[str] = field(default_factory=list)
powershell_encoded: List[Tuple[str, str]] = field(default_factory=list) # (encoded, decoded)
msiexec_commands: List[str] = field(default_factory=list)
mshta_commands: List[str] = field(default_factory=list)
curl_wget_commands: List[str] = field(default_factory=list)
eval_content: List[str] = field(default_factory=list)
download_urls: List[str] = field(default_factory=list)
def is_empty(self) -> bool:
"""Check if no payloads were found"""
return not any([
self.powershell_commands, self.powershell_encoded,
self.msiexec_commands, self.mshta_commands,
self.curl_wget_commands, self.eval_content, self.download_urls
])
class ResourceExtractor(HTMLParser):
"""HTML Parser to extract resources from HTML content"""
def __init__(self, base_url: str):
super().__init__()
self.base_url = base_url
self.resources = ExtractedResources()
self._in_script = False
self._in_style = False
self._current_script = []
self._current_style = []
def handle_starttag(self, tag, attrs):
attrs_dict = dict(attrs)
if tag == 'script':
src = attrs_dict.get('src', '')
if src:
resolved = self._resolve_url(src)
if resolved:
self.resources.scripts.append(resolved)
else:
# Inline script - capture content
self._in_script = True
self._current_script = []
elif tag == 'iframe':
src = attrs_dict.get('src', '')
if src:
resolved = self._resolve_url(src)
if resolved:
self.resources.iframes.append(resolved)
elif tag == 'link':
rel = attrs_dict.get('rel', '').lower()
href = attrs_dict.get('href', '')
if 'stylesheet' in rel and href:
resolved = self._resolve_url(href)
if resolved:
self.resources.css.append(resolved)
elif tag == 'style':
self._in_style = True
self._current_style = []
def handle_endtag(self, tag):
if tag == 'script' and self._in_script:
self._in_script = False
content = ''.join(self._current_script).strip()
if content:
self.resources.inline_scripts.append(content)
# Check for data URIs in script content
self._extract_data_uris(content)
self._current_script = []
elif tag == 'style' and self._in_style:
self._in_style = False
content = ''.join(self._current_style).strip()
if content:
self.resources.inline_styles.append(content)
# Extract @import rules
self._extract_imports(content)
self._current_style = []
def handle_data(self, data):
if self._in_script:
self._current_script.append(data)
elif self._in_style:
self._current_style.append(data)
def _resolve_url(self, url: str) -> Optional[str]:
"""Resolve relative URL to absolute"""
if not url:
return None
# Skip data URIs, javascript:, etc
if url.startswith(('data:', 'javascript:', 'about:', '#')):
if url.startswith('data:'):
self._extract_single_data_uri(url)
return None
# Handle protocol-relative URLs
if url.startswith('//'):
parsed_base = urlparse(self.base_url)
return f"{parsed_base.scheme}:{url}"
# Already absolute
if url.startswith(('http://', 'https://')):
return url
# Relative URL
return urljoin(self.base_url, url)
def _extract_single_data_uri(self, data_uri: str):
"""Extract and decode a single data URI"""
decoded = decode_data_uri(data_uri)
if decoded:
content_type, content = decoded
self.resources.data_uris.append((content_type, content))
def _extract_data_uris(self, content: str):
"""Extract data URIs from content"""
pattern = r'data:([^;,]+)(?:;base64)?,([^\s\"\'\)]+)'
matches = re.findall(pattern, content)
for mime_type, data in matches:
try:
if 'base64' in mime_type or len(data) > 100:
decoded = base64.b64decode(data).decode('utf-8', errors='ignore')
self.resources.data_uris.append((mime_type, decoded))
except:
pass
def _extract_imports(self, css_content: str):
"""Extract @import URLs from CSS"""
patterns = [
r'@import\s+[\'\"](https?://[^\'\"]+)[\'\"]',
r'@import\s+url\([\'\"](https?://[^\'\"]+)[\'\"]\)',
r'@import\s+url\((https?://[^\)]+)\)',
]
for pattern in patterns:
matches = re.findall(pattern, css_content)
for url in matches:
resolved = self._resolve_url(url)
if resolved:
self.resources.imports.append(resolved)
@dataclass
class FormInfo:
"""Information about a form found in HTML"""
action_url: str = ""
method: str = "GET"
has_password_field: bool = False
has_username_field: bool = False
has_email_field: bool = False
has_credit_card_field: bool = False
hidden_fields: List[Tuple[str, str]] = field(default_factory=list)
is_cross_origin: bool = False
is_suspicious: bool = False
suspicion_reasons: List[str] = field(default_factory=list)
class FormExtractor(HTMLParser):
"""HTML Parser to extract and analyze forms"""
def __init__(self, base_url: str):
super().__init__()
self.base_url = base_url
self.forms: List[FormInfo] = []
self._current_form: Optional[FormInfo] = None
# Parse base domain for cross-origin check
parsed = urlparse(base_url)
self._base_domain = parsed.netloc.lower()
def handle_starttag(self, tag, attrs):
attrs_dict = dict(attrs)
if tag == 'form':
self._current_form = FormInfo()
action = attrs_dict.get('action', '')
self._current_form.method = attrs_dict.get('method', 'GET').upper()
# Resolve action URL
if action:
if action.startswith(('http://', 'https://')):
self._current_form.action_url = action
elif action.startswith('//'):
parsed = urlparse(self.base_url)
self._current_form.action_url = f"{parsed.scheme}:{action}"
else:
self._current_form.action_url = urljoin(self.base_url, action)
else:
self._current_form.action_url = self.base_url
# Check cross-origin
try:
action_parsed = urlparse(self._current_form.action_url)
action_domain = action_parsed.netloc.lower()
if action_domain and action_domain != self._base_domain:
self._current_form.is_cross_origin = True
self._current_form.suspicion_reasons.append(f"Form submits to different domain: {action_domain}")
except:
pass
elif tag == 'input' and self._current_form:
input_type = attrs_dict.get('type', 'text').lower()
input_name = attrs_dict.get('name', '').lower()
input_id = attrs_dict.get('id', '').lower()
input_value = attrs_dict.get('value', '')
# Password fields
if input_type == 'password':
self._current_form.has_password_field = True
# Username/email fields
if input_type == 'email' or 'email' in input_name or 'email' in input_id:
self._current_form.has_email_field = True
if any(x in input_name or x in input_id for x in ['user', 'login', 'account', 'uname']):
self._current_form.has_username_field = True
# Credit card detection
if any(x in input_name or x in input_id for x in ['card', 'cc', 'cvv', 'ccnum', 'cardnum', 'expir']):
self._current_form.has_credit_card_field = True
# Hidden fields
if input_type == 'hidden' and input_name:
self._current_form.hidden_fields.append((input_name, input_value))
def handle_endtag(self, tag):
if tag == 'form' and self._current_form:
# Analyze form for suspicious patterns
form = self._current_form
if form.has_password_field:
if form.is_cross_origin:
form.is_suspicious = True
form.suspicion_reasons.append("Login form submits credentials to different domain")
# Check for suspicious action URLs
action_lower = form.action_url.lower()
suspicious_patterns = [
'.php', '/login', '/signin', '/auth',
'verify', 'secure', 'update', 'confirm'
]
if any(p in action_lower for p in suspicious_patterns):
# Not inherently suspicious, but note it
pass
if form.has_credit_card_field:
form.is_suspicious = True
form.suspicion_reasons.append("Form collects credit card information")
if form.is_cross_origin:
form.suspicion_reasons.append("Credit card form submits to different domain")
if len(form.hidden_fields) > 3:
form.suspicion_reasons.append(f"Form has {len(form.hidden_fields)} hidden fields")
self.forms.append(form)
self._current_form = None
def analyze_forms(html_content: str, base_url: str) -> List[FormInfo]:
"""Extract and analyze forms from HTML content"""
parser = FormExtractor(base_url)
try:
parser.feed(html_content)
except:
pass
return parser.forms
@dataclass
class JSRedirect:
"""JavaScript-based redirect detected in content"""
redirect_type: str # location, meta_refresh, document_write, etc.
target_url: str
code_snippet: str
is_obfuscated: bool = False
def detect_js_redirects(content: str) -> List[JSRedirect]:
"""
Detect JavaScript-based redirects in content.
These are often used by malware to evade static analysis.
"""
redirects = []
if not content:
return redirects
# 1. window.location / document.location assignments
location_patterns = [
(r'(?:window|document)\.location\s*=\s*["\']([^"\']+)["\']', 'location_assign'),
(r'(?:window|document)\.location\.href\s*=\s*["\']([^"\']+)["\']', 'location_href'),
(r'location\.replace\s*\(\s*["\']([^"\']+)["\']\s*\)', 'location_replace'),
(r'location\.assign\s*\(\s*["\']([^"\']+)["\']\s*\)', 'location_assign_method'),
(r'window\.open\s*\(\s*["\']([^"\']+)["\']\s*\)', 'window_open'),
]
for pattern, redirect_type in location_patterns:
for match in re.finditer(pattern, content, re.IGNORECASE):
url = match.group(1)
if url.startswith(('http://', 'https://', '//')):
redirects.append(JSRedirect(
redirect_type=redirect_type,
target_url=url,
code_snippet=match.group(0)[:100]
))
# 2. Meta refresh detection
meta_pattern = r'<meta[^>]+http-equiv\s*=\s*["\']?refresh["\']?[^>]+content\s*=\s*["\']?\d+\s*;\s*url\s*=\s*([^"\'>\s]+)'
for match in re.finditer(meta_pattern, content, re.IGNORECASE):
url = match.group(1)
redirects.append(JSRedirect(
redirect_type='meta_refresh',
target_url=url,
code_snippet=match.group(0)[:100]
))
# 3. document.write with redirects
doc_write_pattern = r'document\.write\s*\([^)]*(?:location|redirect|window\.open)[^)]*\)'
for match in re.finditer(doc_write_pattern, content, re.IGNORECASE):
redirects.append(JSRedirect(
redirect_type='document_write',
target_url='(dynamic)',
code_snippet=match.group(0)[:100],
is_obfuscated=True
))
# 4. Obfuscated redirects (eval with location patterns)
eval_redirect_pattern = r'eval\s*\([^)]*(?:location|href|window\.open)[^)]*\)'
for match in re.finditer(eval_redirect_pattern, content, re.IGNORECASE):
redirects.append(JSRedirect(
redirect_type='eval_redirect',
target_url='(obfuscated)',
code_snippet=match.group(0)[:100],
is_obfuscated=True
))
# 5. setTimeout/setInterval with redirects
timeout_pattern = r'set(?:Timeout|Interval)\s*\([^,)]*(?:location|window\.open)[^,)]*,'
for match in re.finditer(timeout_pattern, content, re.IGNORECASE):
redirects.append(JSRedirect(
redirect_type='delayed_redirect',
target_url='(delayed)',
code_snippet=match.group(0)[:100]
))
# 6. Form auto-submit (often used in phishing)
auto_submit_pattern = r'(?:document\.forms\[0\]|form)\.submit\s*\(\s*\)'
if re.search(auto_submit_pattern, content, re.IGNORECASE):
# Check for onload trigger
if re.search(r'(?:onload|DOMContentLoaded)[^{]*{[^}]*submit', content, re.IGNORECASE):
redirects.append(JSRedirect(
redirect_type='form_auto_submit',
target_url='(form action)',
code_snippet='Auto-submitting form on page load'
))
return redirects
def decode_data_uri(data_uri: str) -> Optional[Tuple[str, str]]:
"""
Decode a data URI and return (content_type, decoded_content).
Handles base64 and plain text encoding.
"""
if not data_uri.startswith('data:'):
return None
try:
# Remove 'data:' prefix
data_part = data_uri[5:]
# Split on comma to separate metadata from data
if ',' not in data_part:
return None
metadata, encoded_data = data_part.split(',', 1)
# Parse metadata (e.g., "text/javascript;base64")
is_base64 = ';base64' in metadata.lower()
content_type = metadata.split(';')[0] if metadata else 'text/plain'
if is_base64:
# Decode base64
decoded = base64.b64decode(encoded_data).decode('utf-8', errors='ignore')
else:
# URL decode
from urllib.parse import unquote
decoded = unquote(encoded_data)
return (content_type, decoded)
except Exception:
return None
def extract_resources(html_content: str, base_url: str) -> ExtractedResources:
"""
Extract all resources from HTML content.
Returns ExtractedResources containing scripts, iframes, CSS, etc.
"""
parser = ResourceExtractor(base_url)
try:
parser.feed(html_content)
except Exception:
pass # Continue even if parsing fails
# Also extract data URIs from the raw HTML using regex
# (catches cases the parser might miss)
data_uri_pattern = r'(data:(?:text/javascript|text/html|application/javascript)[^\"\'>\s]+)'
additional_data_uris = re.findall(data_uri_pattern, html_content)
for uri in additional_data_uris:
decoded = decode_data_uri(uri)
if decoded and decoded not in parser.resources.data_uris:
parser.resources.data_uris.append(decoded)
return parser.resources
def fetch_with_redirect_tracking(
url: str,
timeout: int = 30,
max_redirects: int = 10,
proxy: Optional[str] = None
) -> Tuple[Optional[str], Dict[str, str], List[RedirectHop], str]:
"""
Fetch URL while tracking redirect chain.
Returns: (final_content, final_headers, redirect_chain, final_url)
"""
redirect_chain = []
session = requests.Session()
# Configure proxy - explicitly clear system proxies if none provided
if proxy:
proxies = {'http': proxy, 'https': proxy}
session.proxies.update(proxies)
else:
# Clear any system/environment proxy settings
session.proxies = {'http': None, 'https': None}
session.trust_env = False
current_url = url
hop_count = 0
while hop_count < max_redirects:
try:
response = session.get(
current_url,
headers=DEFAULT_HEADERS,
timeout=timeout,
verify=False,
allow_redirects=False
)
hop = RedirectHop(
url=current_url,
status_code=response.status_code,
headers=dict(response.headers),
content=response.text if response.status_code == 200 else None
)
redirect_chain.append(hop)
# Check for redirect
if response.status_code in (301, 302, 303, 307, 308):
location = response.headers.get('Location', '')
if not location:
break
# Handle relative redirects
if not location.startswith(('http://', 'https://')):
location = urljoin(current_url, location)
current_url = location
hop_count += 1
else:
# Not a redirect, we're done
break
except requests.exceptions.SSLError:
# Try HTTP if HTTPS fails
if current_url.startswith('https://'):
current_url = current_url.replace('https://', 'http://', 1)
continue
else:
break
except requests.exceptions.RequestException as e:
print(f"[!] Error fetching {current_url}: {e}")
break
except Exception as e:
print(f"[!] Unexpected error fetching {current_url}: {e}")
break
# Get final content
if redirect_chain:
last_hop = redirect_chain[-1]
if last_hop.status_code == 200 and last_hop.content:
return last_hop.content, last_hop.headers, redirect_chain, last_hop.url
return None, {}, redirect_chain, url
def fetch_single_resource(url: str, timeout: int = 10, proxy: Optional[str] = None) -> Tuple[Optional[str], str]:
"""
Fetch a single resource (script, CSS, etc.).
Returns (content, status) where status is 'ok', 'timeout', 'error', or error message.
Safe: only fetches text content, no execution.
"""
# Configure proxy - explicitly bypass system proxies if none provided
if proxy:
proxies = {'http': proxy, 'https': proxy}
else:
proxies = {'http': None, 'https': None}
try:
session = requests.Session()
session.trust_env = False if not proxy else True
response = session.get(
url,
headers=DEFAULT_HEADERS,
timeout=timeout,
verify=False,
allow_redirects=True,
proxies=proxies
)
response.raise_for_status()
return response.text, 'ok'
except requests.exceptions.Timeout:
return None, 'timeout'
except requests.exceptions.ConnectionError:
return None, 'connection_error'
except requests.exceptions.HTTPError as e:
return None, f'http_{e.response.status_code}'
except Exception as e:
return None, 'error'
def fetch_resources(
resources: ExtractedResources,
base_url: str,
resource_timeout: int = 10,
max_resources: int = 50,
verbose: bool = False,
proxy: Optional[str] = None
) -> Tuple[Dict[str, ScannableContent], Dict[str, str]]:
"""
Fetch all external resources.
Returns (fetched_dict, failed_dict) where:
- fetched_dict: URL -> ScannableContent for successful fetches
- failed_dict: URL -> reason for failed fetches
Safe: Only fetches text content, no JavaScript/HTML execution.
"""
fetched = {}
failed = {}
all_urls = []
# Collect all resource URLs with their types (skip Google domains)
skipped_count = 0
for url in resources.scripts[:max_resources]:
if is_skipped_domain(url):
skipped_count += 1
continue
all_urls.append((url, 'script'))
for url in resources.iframes[:max_resources]:
if is_skipped_domain(url):
skipped_count += 1
continue
all_urls.append((url, 'iframe'))
for url in resources.css[:max_resources]:
if is_skipped_domain(url):
skipped_count += 1
continue
all_urls.append((url, 'css'))
for url in resources.imports[:max_resources]:
if is_skipped_domain(url):
skipped_count += 1
continue
all_urls.append((url, 'css_import'))
if skipped_count > 0 and verbose:
print(f"[*] Skipped {skipped_count} Google/trusted CDN resource(s)")
# Deduplicate while preserving order
seen = set()
unique_urls = []
for url, rtype in all_urls:
if url not in seen:
seen.add(url)
unique_urls.append((url, rtype))
total = len(unique_urls[:max_resources])
if total == 0:
return fetched, failed
# Fetch each resource with progress indicator
success_count = 0
fail_count = 0
for i, (url, resource_type) in enumerate(unique_urls[:max_resources], 1):
# Progress bar
progress = f"[{i}/{total}]"
url_short = url[:50] + "..." if len(url) > 50 else url
# Show progress (overwrite line)
sys.stdout.write(f"\r {progress} Fetching {resource_type}: {url_short:<55}")
sys.stdout.flush()
content, status = fetch_single_resource(url, resource_timeout, proxy)
if content and status == 'ok':
fetched[url] = ScannableContent(
url=url,
content_type=resource_type,
content=content,
source=base_url
)
success_count += 1
if verbose:
print(f" -> {len(content)} bytes")
else:
failed[url] = status
fail_count += 1
if verbose:
print(f" -> FAILED ({status})")
# Clear the progress line and show summary
sys.stdout.write("\r" + " " * 80 + "\r")
sys.stdout.flush()
if fail_count > 0:
print(f" [+] Fetched: {success_count}/{total} resources ({fail_count} failed)")
else:
print(f" [+] Fetched: {success_count}/{total} resources")
return fetched, failed
def build_content_buffer(
main_content: str,
main_url: str,
main_headers: Dict[str, str],
resources: ExtractedResources,
fetched_resources: Dict[str, ScannableContent],
redirect_chain: List[RedirectHop]
) -> List[ScannableContent]:
"""
Build unified buffer of all scannable content.
"""
buffer = []
# Add redirect chain pages (excluding final page which is main_content)
for i, hop in enumerate(redirect_chain[:-1] if len(redirect_chain) > 1 else []):
if hop.content:
buffer.append(ScannableContent(
url=hop.url,
content_type='redirect',
content=hop.content,
headers=hop.headers,
source=f'redirect_hop_{i+1}'
))
# Add main page content
buffer.append(ScannableContent(
url=main_url,
content_type='main_page',
content=main_content,
headers=main_headers,
source='main'
))
# Add inline scripts
for i, script_content in enumerate(resources.inline_scripts):
buffer.append(ScannableContent(
url=f"{main_url}#inline_script_{i+1}",
content_type='inline_script',
content=script_content,
source=main_url
))
# Add inline styles
for i, style_content in enumerate(resources.inline_styles):
buffer.append(ScannableContent(
url=f"{main_url}#inline_style_{i+1}",
content_type='inline_style',
content=style_content,
source=main_url
))
# Add decoded data URIs
for i, (content_type, content) in enumerate(resources.data_uris):
buffer.append(ScannableContent(
url=f"{main_url}#data_uri_{i+1}",
content_type='data_uri',
content=content,
source=main_url
))
# Add fetched external resources
for url, scannable in fetched_resources.items():
buffer.append(scannable)
return buffer
def parse_ekfiddle_rules(filepath: str) -> List[EKFiddleRule]:
"""
Parse EKFiddle format rules file.
Format: Type TAB RuleName TAB Regex TAB OptionalDescription
"""
rules = []
if not os.path.exists(filepath):
print(f"[!] Error: Rules file '{filepath}' not found")
return rules
with open(filepath, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
line = line.rstrip('\n\r')
# Skip empty lines
if not line.strip():
continue
# Skip comments (lines starting with # or ##)
if line.strip().startswith('#'):
continue
# Parse tab-separated fields
parts = line.split('\t')
if len(parts) < 3:
continue
rule_type = parts[0].strip()
name = parts[1].strip()
pattern = parts[2].strip()
description = parts[3].strip() if len(parts) > 3 else ""
# Validate rule type
valid_types = ['SourceCode', 'URI', 'Headers', 'IP', 'Hash']
if rule_type not in valid_types:
continue
# Skip empty patterns
if not pattern:
continue
try:
rule = EKFiddleRule(
rule_type=rule_type,
name=name,
pattern=pattern,
description=description
)
rules.append(rule)
except Exception as e:
print(f"[!] Warning: Failed to parse rule at line {line_num}: {e}")
continue
return rules
def check_and_pattern(rule: EKFiddleRule, content: str) -> Tuple[bool, List[str]]:
"""
Check if all AND conditions in a rule match the content.
Returns (matched, list_of_matched_strings)
"""
if not rule.has_and_condition:
# Single pattern
try:
matches = re.findall(rule.pattern, content, re.IGNORECASE | re.MULTILINE)
if matches:
# Flatten if tuples
flat_matches = []
for m in matches:
if isinstance(m, tuple):
flat_matches.append(m[0] if m[0] else str(m))
else:
flat_matches.append(str(m))
return True, flat_matches
except re.error:
# Invalid regex, skip silently
pass
return False, []
# AND condition - all patterns must match
all_matches = []
for pattern in rule.and_patterns:
try:
matches = re.findall(pattern, content, re.IGNORECASE | re.MULTILINE)
if not matches:
return False, []
# Collect first match from each pattern
if isinstance(matches[0], tuple):
all_matches.append(matches[0][0] if matches[0][0] else str(matches[0]))
else:
all_matches.append(str(matches[0]))
except re.error:
return False, []
return True, all_matches
def extract_urls_from_content(content: str) -> Set[str]:
"""Extract all URLs from HTML/JS content"""
url_pattern = r'https?://[^\s\"\'\<\>\)\]\}]+'
urls = set(re.findall(url_pattern, content, re.IGNORECASE))
# Also extract from common JS patterns
js_patterns = [
r'src=[\'\"](https?://[^\'\"]+)[\'\"]',
r'href=[\'\"](https?://[^\'\"]+)[\'\"]',
r'url\([\'\"](https?://[^\'\"]+)[\'\"]\)',
]
for pattern in js_patterns:
matches = re.findall(pattern, content, re.IGNORECASE)
urls.update(matches)
return urls
def normalize_url(target: str) -> Optional[str]:
"""Normalize a domain or URL to a proper URL format"""
target = target.strip()
if not target: