-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcdn_scanner_plus.py
More file actions
1751 lines (1505 loc) · 79.9 KB
/
Copy pathcdn_scanner_plus.py
File metadata and controls
1751 lines (1505 loc) · 79.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
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
import socket
import ssl
import concurrent.futures
import time
import dns.resolver
import json
import os
import random
from datetime import datetime
from ipaddress import ip_address, ip_network, IPv4Network, IPv6Network
from colorama import init, Fore, Back, Style
import urllib3
import requests
import logging
from typing import List, Dict, Tuple, Optional, Union, Any
import configparser
import argparse
import subprocess
import platform
import re
import shutil
from timeit import default_timer as timer
import csv
import signal
# Constants
DEFAULT_TIMEOUT = 5
MAX_RETRIES = 3
MAX_WORKERS = 20
RATE_LIMIT_DELAY = 0.1 # seconds between requests
USER_AGENTS = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0'
]
# Disable SSL warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Initialize colorama for Windows console colors
init(autoreset=True)
# Cloudflare HTTPS Ports
CF_HTTPS_PORTS = [443, 2053, 2083, 2087, 2096, 8443]
class CDNScannerPlus:
def __init__(self, config_file: str = 'config.ini'):
self.config_file = config_file
self._initialize_defaults()
self._setup_infrastructure()
self.load_config()
self.setup_logging()
def _initialize_defaults(self):
"""Initialize all default values"""
self.gcore_test_domains = [
'gcore.com', 'www.gcore.com', 'images.gcore.com',
'static.gcore.com', 'api.gcore.com', 'cdn.gcdn.co',
'cdn.gcorelabs.com', 'demo-cdn.gcore.com'
]
self.cdn_test_domains = {
'cloudflare': ['www.cloudflare.com', 'www.speedtest.net'],
'fastly': ['fastly.net', 'fastly.com'],
'gcore': self.gcore_test_domains
}
self.cdn_ranges = {
'cloudflare': [
'104.16.0.0/13', '172.64.0.0/13', '162.158.0.0/15',
'108.162.192.0/18', '173.245.48.0/20', '141.101.64.0/18',
'190.93.240.0/20', '188.114.96.0/20'
],
'gcore': [
'158.160.0.0/16', '92.223.84.0/24', '185.209.160.0/24',
'45.133.144.0/24', '45.135.240.0/22', '45.159.216.0/22'
],
'fastly': [
'151.101.0.0/16', '199.232.0.0/16', '2a04:4e40::/32',
'23.235.32.0/20', '43.249.72.0/22'
]
}
self.valid_pairs = []
self.scanned_domains = 0
self.total_tests = 0
self.start_time = None
self.debug_mode = False
self.verbose_mode = False
self.rate_limit_delay = RATE_LIMIT_DELAY
self.dns_servers = ['1.1.1.1', '8.8.8.8', '9.9.9.9', '208.67.222.222']
self.output_dir = 'results'
self.proxies = None
def _setup_infrastructure(self):
"""Set up connections and sessions"""
self.session = requests.Session()
self.session.verify = False
self.session.headers.update({'User-Agent': random.choice(USER_AGENTS)})
# Configure adapters for connection pooling
adapter = requests.adapters.HTTPAdapter(
pool_connections=20,
pool_maxsize=20,
max_retries=3
)
self.session.mount('http://', adapter)
self.session.mount('https://', adapter)
def load_config(self) -> None:
"""Load configuration from file or set defaults"""
config = configparser.ConfigParser()
# Default configuration
config['DEFAULT'] = {
'debug_mode': 'False',
'verbose_mode': 'False',
'rate_limit_delay': str(RATE_LIMIT_DELAY),
'dns_servers': ','.join(self.dns_servers),
'output_dir': self.output_dir,
'proxies': ''
}
# Try to read or create config file
try:
if os.path.exists(self.config_file):
config.read(self.config_file)
else:
with open(self.config_file, 'w') as configfile:
config.write(configfile)
print(Fore.YELLOW + f"[*] Created default config file: {self.config_file}" + Style.RESET_ALL)
except Exception as e:
print(Fore.RED + f"[!] Error loading config: {e}" + Style.RESET_ALL)
return
# Apply configuration
try:
self.debug_mode = config.getboolean('DEFAULT', 'debug_mode', fallback=False)
self.verbose_mode = config.getboolean('DEFAULT', 'verbose_mode', fallback=False)
self.rate_limit_delay = config.getfloat('DEFAULT', 'rate_limit_delay', fallback=RATE_LIMIT_DELAY)
self.dns_servers = [s.strip() for s in config.get('DEFAULT', 'dns_servers').split(',')]
self.output_dir = config.get('DEFAULT', 'output_dir', fallback='results')
proxy_str = config.get('DEFAULT', 'proxies', fallback='')
if proxy_str:
self.configure_proxy(proxy_str)
# Create output directory if it doesn't exist
os.makedirs(self.output_dir, exist_ok=True)
# Load ranges from files if they exist (overriding config)
for cdn in self.cdn_ranges:
filename = f"{cdn}.txt"
if os.path.exists(filename):
try:
with open(filename, 'r') as f:
self.cdn_ranges[cdn] = [line.strip() for line in f if line.strip()]
except Exception as e:
print(Fore.RED + f"[!] Error loading {cdn} ranges: {e}" + Style.RESET_ALL)
except Exception as e:
print(Fore.RED + f"[!] Error applying config: {e}" + Style.RESET_ALL)
def scan_cloudflare_multiport(self) -> None:
"""Enhanced Scanner to find Clean IPs for Xray/VLESS Nodes"""
self.print_banner()
print(Fore.GREEN + "--- Multi-Port CDN Scanner (GFW Bypass Mode) ---" + Style.RESET_ALL)
# 1. FILE DETECTION
files_to_check = {
"1": ("valid_pairs.json", "Option 2: Random Scan Results"),
"2": ("xray_working.json", "Option 9: Xray-Tested Results")
}
available_files = {k: v for k, v in files_to_check.items() if os.path.exists(os.path.join(self.output_dir, v[0]))}
test_ips = []
source_name = ""
# 2. USER CHOICE MENU
print(Fore.CYAN + "\n[?] Select source for Clean IPs:")
if available_files:
for key, (fname, desc) in available_files.items():
print(f"{Fore.YELLOW}[{key}]{Style.RESET_ALL} {desc} ({fname})")
else:
print(Fore.RED + " [!] No result files found. You should run a scan first." + Style.RESET_ALL)
print(f"{Fore.YELLOW}[3]{Style.RESET_ALL} Scan new random Cloudflare ranges (Fallback)")
choice = input(Fore.WHITE + "\nEnter choice (1-3): " + Style.RESET_ALL).strip()
# 3. ROBUST PARSING (Handles standard JSON and Xray List format)
if choice in available_files:
selected_filename = available_files[choice][0]
target_path = os.path.join(self.output_dir, selected_filename)
source_name = selected_filename
try:
with open(target_path, 'r') as f:
content = f.read().strip()
if content:
try:
# Try loading as [ {...}, {...} ]
data = json.loads(content)
entries = data if isinstance(data, list) else [data]
for entry in entries:
ip = entry.get('ip') or entry.get('host')
if ip: test_ips.append(ip)
except json.JSONDecodeError:
# Fallback to line-by-line { "ip": ... }
f.seek(0)
for line in f:
line = line.strip().rstrip(',')
if not line or line in ['[', ']']: continue
try:
entry = json.loads(line)
ip = entry.get('ip') or entry.get('host')
if ip: test_ips.append(ip)
except: continue
test_ips = list(set(test_ips)) # De-duplicate
except Exception as e:
print(Fore.RED + f"[✘] Error loading source: {e}")
# Fallback to random generation if choice 3 or loading failed
if choice == '3' or not test_ips:
source_name = "Cloudflare Random Ranges"
if hasattr(self, 'cdn_ranges') and 'cloudflare' in self.cdn_ranges:
cidr = random.choice(self.cdn_ranges['cloudflare'])
test_ips = self.generate_random_ips(cidr, 50)
else:
print(Fore.RED + "[!] Critical: No IP ranges found.")
return
# 4. STATUS BOX
print(Fore.CYAN + "\n┌────────────────────────────────────────────────────────────┐")
print(f"│ {Fore.GREEN}SOURCE:{Style.RESET_ALL} {source_name:<19} | {Fore.GREEN}IPs LOADED:{Style.RESET_ALL} {len(test_ips):<6} │")
print(Fore.CYAN + "└────────────────────────────────────────────────────────────┘" + Style.RESET_ALL)
# 5. SNI SELECTION (Commonly unblocked SNIs in Iran)
print(Fore.CYAN + "\n--- Select SNI for Scanning ---")
print(f"{Fore.YELLOW}[1]{Style.RESET_ALL} Cloudflare (www.speedtest.net) - High Success")
print(f"{Fore.YELLOW}[2]{Style.RESET_ALL} GCore (gcore.com)")
print(f"{Fore.YELLOW}[3]{Style.RESET_ALL} Fastly (fastly.com)")
print(f"{Fore.YELLOW}[4]{Style.RESET_ALL} Fastly (fastly.net)")
print(f"{Fore.YELLOW}[5]{Style.RESET_ALL} Custom SNI")
sni_choice = input(Fore.YELLOW + "Choice (1-5): " + Style.RESET_ALL).strip()
sni_map = {"1": "www.speedtest.net", "2": "gcore.com", "3": "fastly.com", "4": "fastly.net"}
sni = sni_map.get(sni_choice) or input(Fore.YELLOW + "Enter Custom SNI: " + Style.RESET_ALL).strip() or "www.speedtest.net"
# 6. PORT SELECTION
port_input = input(Fore.YELLOW + "\nEnter ports (e.g. 443,2053,2083) or 'all': " + Style.RESET_ALL).strip().lower()
selected_ports = [443, 2053, 2083, 2087, 2096, 8443] if port_input in ['all', ''] else [int(p.strip()) for p in port_input.split(',')]
# 7. EXECUTION
print(Fore.CYAN + f"\n[*] Scanning {len(test_ips)} IPs for {sni} compatibility...")
txt_file = os.path.join(self.output_dir, "multiport_results.txt")
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
futures = {executor.submit(self.test_sni_pair, ip, sni, 10, port): (ip, port) for ip in test_ips for port in selected_ports}
for future in concurrent.futures.as_completed(futures):
result = future.result()
if result and result.get('https_works'):
ip, port, ping = result['ip'], result['port'], result['ping']
print(Fore.GREEN + f" [+] CLEAN IP FOUND: {ip}:{port} | Ping: {ping}ms" + Style.RESET_ALL)
with open(txt_file, 'a') as f:
f.write(f"{ip}:{port} | SNI: {sni} | Ping: {ping}ms\n")
print(Fore.YELLOW + f"\n[*] Done! Use these IPs in your VLESS nodes. Results: multiport_results.txt")
input("\nPress Enter to return...")
def configure_proxy(self, proxy_url: str):
"""Configure HTTP/S proxy"""
self.proxies = {
'http': proxy_url,
'https': proxy_url
}
self.session.proxies = self.proxies
logging.info(f"Proxy configured: {proxy_url}")
def setup_logging(self) -> None:
"""Configure logging system"""
log_format = '%(asctime)s - %(levelname)s - %(message)s'
level = logging.DEBUG if self.debug_mode else logging.INFO
logging.basicConfig(
level=level,
format=log_format,
filename=os.path.join(self.output_dir, 'cdn_scanner.log'),
filemode='a'
)
def clear_screen(self) -> None:
"""Clear the console screen"""
os.system('cls' if os.name == 'nt' else 'clear')
def print_banner(self) -> None:
"""Display the program banner"""
self.clear_screen()
print(Fore.CYAN + r"""
____ ____ _ _ ____ ___ ____ _ _ _____
/ ___| _ \| \ | | / ___|_ _/ ___| \ | |_ _|
| | | | | | \| | \___ \| | | _| \| | | |
| |___| |_| | |\ | ___) | | |_| | |\ | | |
\____|____/|_| \_| |____/___\____|_| \_| |_|
CDN SNI Scanner PLUS - IRAN OPTIMIZED By Jeet
""" + Style.RESET_ALL)
print(Fore.YELLOW + "VLESS+WS/Xray Support | GFW Bypass | Enhanced Reporting" + Style.RESET_ALL)
def print_menu(self) -> None:
"""Display the main menu"""
self.print_banner()
debug_status = f"{Fore.GREEN}●{Style.RESET_ALL}" if self.debug_mode else f"{Fore.RED}○{Style.RESET_ALL}"
verbose_status = f"{Fore.GREEN}●{Style.RESET_ALL}" if self.verbose_mode else f"{Fore.RED}○{Style.RESET_ALL}"
print(f"{debug_status} Debug Mode | {verbose_status} Verbose Mode | Proxies: {'Enabled' if self.proxies else 'Disabled'}\n")
print(Fore.YELLOW + "[1]" + Style.RESET_ALL + " Scan single domain")
print(Fore.YELLOW + "[2]" + Style.RESET_ALL + " Scan random IPs")
print(Fore.YELLOW + "[3]" + Style.RESET_ALL + " Scan from file")
print(Fore.YELLOW + "[4]" + Style.RESET_ALL + " View results")
print(Fore.YELLOW + "[5]" + Style.RESET_ALL + " Toggle debug")
print(Fore.YELLOW + "[6]" + Style.RESET_ALL + " Test known CDNs")
print(Fore.YELLOW + "[7]" + Style.RESET_ALL + " Deep CDN Test")
print(Fore.CYAN + "[8]" + Style.RESET_ALL + " Update CDN IP ranges")
print(Fore.GREEN + "[9]" + Style.RESET_ALL + " Test Xray/V2Ray compatibility")
print(Fore.WHITE + "[10]" + Style.RESET_ALL + " CDN Multi-Port Scanner")
print(Fore.GREEN + "[11]" + Style.RESET_ALL + " Generate HTML report")
print(Fore.YELLOW + "[12]" + Style.RESET_ALL + " Configuration")
print(Fore.YELLOW + "[13]" + Style.RESET_ALL + " Export to CSV/Excel")
print(Fore.RED + "[0]" + Style.RESET_ALL + " Exit")
print("\n")
def resolve_domain(self, domain: str) -> List[str]:
"""Resolve domain to IP addresses"""
ips = set()
record_types = ['A', 'AAAA'] # Both IPv4 and IPv6
for dns_server in self.dns_servers:
try:
resolver = dns.resolver.Resolver()
resolver.nameservers = [dns_server]
for record_type in record_types:
try:
answers = resolver.resolve(domain, record_type)
ips.update(str(r) for r in answers)
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
continue
if ips:
break
except Exception as e:
logging.warning(f"DNS resolution failed with {dns_server} for {domain}: {e}")
if self.debug_mode:
print(Fore.RED + f"[DEBUG] DNS resolution failed with {dns_server} for {domain}: {type(e).__name__}" + Style.RESET_ALL)
return list(ips)
def is_ip_in_cdn_ranges(self, ip: str, cdn_name: str) -> bool:
"""Check if IP belongs to CDN ranges"""
try:
ip_obj = ip_address(ip)
for network in self.cdn_ranges.get(cdn_name.lower(), []):
try:
if ip_obj.version == 4:
if ip_obj in IPv4Network(network):
return True
elif ip_obj.version == 6:
if ip_obj in IPv6Network(network):
return True
except ValueError:
continue
return False
except ValueError:
logging.warning(f"Invalid IP address: {ip}")
if self.debug_mode:
print(Fore.RED + f"[DEBUG] Invalid IP address: {ip}" + Style.RESET_ALL)
return False
def get_ping(self, ip: str, count: int = 3) -> Optional[float]:
"""
Get average ping time to an IP address
Returns average ping in milliseconds or None if failed
"""
try:
# Ping command differs between Windows and Unix-like systems
param = '-n' if platform.system().lower() == 'windows' else '-c'
command = ['ping', param, str(count), ip]
output = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=10
).stdout
# Parse ping output for average time
if platform.system().lower() == 'windows':
match = re.search(r'Average = (\d+)ms', output)
else:
match = re.search(r'min/avg/max/\w+ = [\d.]+/([\d.]+)/', output)
if match:
return float(match.group(1))
return None
except:
return None
def test_http(self, ip: str, hostname: str, timeout: int = DEFAULT_TIMEOUT) -> bool:
"""Test if IP responds to HTTP (port 80) with given Host header"""
try:
# Create a socket connection
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
sock.connect((ip, 80))
# Send HTTP request
request = f"GET / HTTP/1.1\r\nHost: {hostname}\r\nConnection: close\r\n\r\n"
sock.sendall(request.encode())
# Get response (just the first part is enough)
response = sock.recv(1024).decode()
# Check if we got a valid HTTP response
if "HTTP/" in response and any(str(code) in response for code in [200, 301, 302, 403, 404]):
return True
except:
return False
finally:
try:
sock.close()
except:
pass
return False
def test_sni_pair(self, ip: str, sni: str, timeout: int = DEFAULT_TIMEOUT, port: int = 443) -> Optional[Dict]:
"""Test if IP accepts the SNI with detailed performance metrics"""
for attempt in range(MAX_RETRIES):
try:
# FIXED: Added 'port' here so it actually passes it to the worker function
return self._test_sni_pair(ip, sni, timeout, port)
except Exception as e:
if attempt == MAX_RETRIES - 1:
if self.debug_mode:
print(Fore.YELLOW + f"[DEBUG] Test failed for {sni} @ {ip}:{port}: {e}" + Style.RESET_ALL)
return None
time.sleep(random.uniform(0.5, 1.5))
return None
def _test_sni_pair(self, ip: str, sni: str, timeout: int, port: int) -> Optional[Dict]:
"""Actual implementation of SNI testing"""
self.total_tests += 1
time.sleep(self.rate_limit_delay)
result = {
'ip': ip,
'sni': sni,
'https_works': False,
'http_works': False,
'ping': None,
'ssl_handshake_time': None,
'http_response_time': None,
'reverse_dns': self.reverse_dns_lookup(ip),
'server_header': None,
'port': port # Correctly capture the port used
}
# Test HTTPS
ssl_success = False
try:
# FIXED: Ensure socket is created using the passed port
sock = socket.create_connection((ip, port), timeout=timeout)
sock.settimeout(timeout)
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
start_time = timer()
with context.wrap_socket(sock, server_hostname=sni) as ssl_sock:
# If handshake finishes, we consider it a success for that port
result['ssl_handshake_time'] = (timer() - start_time) * 1000
try:
request = f"HEAD / HTTP/1.1\r\nHost: {sni}\r\nConnection: close\r\n\r\n"
ssl_sock.sendall(request.encode())
response = ssl_sock.recv(1024).decode(errors='ignore')
if "HTTP/" in response:
result['https_works'] = True
ssl_success = True
if 'Server:' in response:
result['server_header'] = response.split('Server:')[1].split('\r\n')[0].strip()
except:
# Even if request fails, if SSL handshake worked, the port is open
result['https_works'] = True
ssl_success = True
except Exception as e:
if self.debug_mode:
print(Fore.RED + f"[-] {ip}:{port} failed: {e}" + Style.RESET_ALL)
# Only ping if the connection was successful
if ssl_success:
ping_time = self.get_ping(ip)
result['ping'] = ping_time
return result
return None
def test_sni_pair(self, ip: str, sni: str, timeout: int = DEFAULT_TIMEOUT, port: int = 443) -> Optional[Dict]:
"""Test if IP accepts the SNI with detailed performance metrics"""
for attempt in range(MAX_RETRIES):
try:
# FIXED: Added 'port' here so it actually passes it to the worker function
return self._test_sni_pair(ip, sni, timeout, port)
except Exception as e:
if attempt == MAX_RETRIES - 1:
if self.debug_mode:
print(Fore.YELLOW + f"[DEBUG] Test failed for {sni} @ {ip}:{port}: {e}" + Style.RESET_ALL)
return None
time.sleep(random.uniform(0.5, 1.5))
return None
def _test_sni_pair(self, ip: str, sni: str, timeout: int, port: int) -> Optional[Dict]:
"""Actual implementation of SNI testing"""
self.total_tests += 1
time.sleep(self.rate_limit_delay)
result = {
'ip': ip,
'sni': sni,
'https_works': False,
'http_works': False,
'ping': None,
'ssl_handshake_time': None,
'http_response_time': None,
'reverse_dns': self.reverse_dns_lookup(ip),
'server_header': None,
'port': port # Correctly capture the port used
}
# Test HTTPS
ssl_success = False
try:
# FIXED: Ensure socket is created using the passed port
sock = socket.create_connection((ip, port), timeout=timeout)
sock.settimeout(timeout)
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
start_time = timer()
with context.wrap_socket(sock, server_hostname=sni) as ssl_sock:
# If handshake finishes, we consider it a success for that port
result['ssl_handshake_time'] = (timer() - start_time) * 1000
try:
request = f"HEAD / HTTP/1.1\r\nHost: {sni}\r\nConnection: close\r\n\r\n"
ssl_sock.sendall(request.encode())
response = ssl_sock.recv(1024).decode(errors='ignore')
if "HTTP/" in response:
result['https_works'] = True
ssl_success = True
if 'Server:' in response:
result['server_header'] = response.split('Server:')[1].split('\r\n')[0].strip()
except:
# Even if request fails, if SSL handshake worked, the port is open
result['https_works'] = True
ssl_success = True
except Exception as e:
if self.debug_mode:
print(Fore.RED + f"[-] {ip}:{port} failed: {e}" + Style.RESET_ALL)
# Only ping if the connection was successful
if ssl_success:
ping_time = self.get_ping(ip)
result['ping'] = ping_time
return result
return None
def reverse_dns_lookup(self, ip: str) -> List[str]:
"""Perform a reverse DNS lookup (PTR record) to find domains linked to an IP."""
try:
hostnames = socket.gethostbyaddr(ip)
return [hostnames[0]] + hostnames[1] # Primary + aliases
except (socket.herror, socket.gaierror):
return []
except Exception as e:
if self.debug_mode:
print(Fore.YELLOW + f"[DEBUG] Reverse DNS failed for {ip}: {e}" + Style.RESET_ALL)
return []
def scan_domain(self, domain: str, output_file: Optional[str] = None) -> List[Dict]:
"""Scan a single domain for CDN IPs"""
self.scanned_domains += 1
print(Fore.GREEN + f"\n[*] Scanning {domain}" + Style.RESET_ALL)
ips = self.resolve_domain(domain)
if not ips:
print(Fore.YELLOW + f"[!] No IPs found for {domain}" + Style.RESET_ALL)
return []
valid_pairs = []
for cdn_name in self.cdn_ranges:
cdn_ips = [ip for ip in ips if self.is_ip_in_cdn_ranges(ip, cdn_name)]
if not cdn_ips:
if self.debug_mode:
print(Fore.CYAN + f"[DEBUG] No {cdn_name} IPs found for {domain}" + Style.RESET_ALL)
continue
print(Fore.CYAN + f"[*] Found {len(cdn_ips)} {cdn_name} IPs" + Style.RESET_ALL)
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
futures = {executor.submit(self.test_sni_pair, ip, domain): (ip, domain, cdn_name) for ip in cdn_ips}
for future in concurrent.futures.as_completed(futures):
ip, domain, cdn_name = futures[future]
try:
result = future.result()
if result:
pair = {
"ip": ip,
"sni": domain,
"cdn": cdn_name,
"https_works": result.get('https_works', False),
"http_works": result.get('http_works', False),
"ping": result.get('ping', None),
"ssl_handshake_time": result.get('ssl_handshake_time', None),
"http_response_time": result.get('http_response_time', None),
"reverse_dns": result.get('reverse_dns', []),
"server_header": result.get('server_header', None),
"timestamp": datetime.now().isoformat()
}
# Build status message
status_parts = []
if pair['https_works']:
status_parts.append("HTTPS")
if pair['http_works']:
status_parts.append("HTTP")
status = "+".join(status_parts) if status_parts else "None"
ping_display = f"{pair['ping']}ms" if pair['ping'] is not None else "N/A"
ssl_time_display = f"{pair['ssl_handshake_time']:.1f}ms" if pair['ssl_handshake_time'] is not None else "N/A"
http_time_display = f"{pair['http_response_time']:.1f}ms" if pair['http_response_time'] is not None else "N/A"
reverse_dns_display = ", ".join(pair['reverse_dns']) if pair['reverse_dns'] else "None"
server_header_display = pair['server_header'] or "N/A"
print(Fore.GREEN + f"[+] Valid: {domain} @ {ip} ({cdn_name}) - Protocols: {status} - Ping: {ping_display}" + Style.RESET_ALL)
print(Fore.CYAN + f" SSL Handshake: {ssl_time_display} - HTTP Response: {http_time_display}" + Style.RESET_ALL)
print(Fore.CYAN + f" Server: {server_header_display}" + Style.RESET_ALL)
print(Fore.CYAN + f" Reverse DNS: {reverse_dns_display}" + Style.RESET_ALL)
valid_pairs.append(pair)
if output_file:
self.save_result(pair, output_file)
except Exception as e:
print(Fore.RED + f"[!] Error testing {domain} @ {ip}: {type(e).__name__}" + Style.RESET_ALL)
return valid_pairs
def save_result(self, pair: Dict, output_file: str) -> None:
"""Save a valid pair to output file"""
try:
with open(output_file, 'a') as f:
f.write(json.dumps(pair) + "\n")
except IOError as e:
print(Fore.RED + f"[!] Failed to save results: {e}" + Style.RESET_ALL)
def save_to_txt(self, results: List[Dict], filename: str) -> None:
"""Save results to TXT file with ping info"""
try:
# Sort by ping time (lowest first)
sorted_results = sorted(
results,
key=lambda x: float('inf') if x.get('ping') is None else x['ping']
)
with open(filename, 'w') as f:
for result in sorted_results:
f.write(f"IP: {result.get('ip', 'N/A')}\n")
f.write(f"SNI: {result.get('sni', 'N/A')}\n")
f.write(f"CDN: {result.get('cdn', 'N/A')}\n")
f.write(f"HTTPS Works: {'Yes' if result.get('https_works', False) else 'No'}\n")
f.write(f"HTTP Works: {'Yes' if result.get('http_works', False) else 'No'}\n")
f.write(f"Server Header: {result.get('server_header', 'N/A')}\n")
f.write(f"Reverse DNS: {', '.join(result.get('reverse_dns', [])) or 'None'}\n")
f.write(f"Ping: {result.get('ping', 'N/A')}ms\n")
f.write(f"SSL Handshake Time: {result.get('ssl_handshake_time', 'N/A')}ms\n")
f.write(f"HTTP Response Time: {result.get('http_response_time', 'N/A')}ms\n")
f.write("-" * 40 + "\n")
except Exception as e:
print(Fore.RED + f"[!] Error saving TXT file: {e}" + Style.RESET_ALL)
def view_results(self, results_file: Optional[str] = None) -> None:
"""Display saved results"""
self.print_banner()
if not results_file:
results_file = os.path.join(self.output_dir, "valid_pairs.json")
if not os.path.exists(results_file):
print(Fore.RED + "[!] No results file found" + Style.RESET_ALL)
input("\nPress Enter to return to menu...")
return
try:
with open(results_file, 'r') as f:
results = [json.loads(line) for line in f if line.strip()]
if not results:
print(Fore.YELLOW + "[!] No valid pairs found in results file" + Style.RESET_ALL)
else:
print(Fore.CYAN + "\nSaved Valid SNI + IP Pairs:\n" + Style.RESET_ALL)
for i, pair in enumerate(results, 1):
protocols = []
if pair.get('https_works', False):
protocols.append("HTTPS")
if pair.get('http_works', False):
protocols.append("HTTP")
protocol_str = "+".join(protocols) if protocols else "None"
ping_display = f"{pair.get('ping', 'N/A')}ms"
ssl_time = f"{pair.get('ssl_handshake_time', 'N/A')}ms"
http_time = f"{pair.get('http_response_time', 'N/A')}ms"
reverse_dns = ", ".join(pair.get('reverse_dns', [])) or "None"
server_header = pair.get('server_header', 'N/A')
print(f"{i}. {pair.get('sni', 'N/A')} @ {pair.get('ip', 'N/A')} ({pair.get('cdn', 'N/A')})")
print(f" Protocols: {protocol_str} - Ping: {ping_display}")
print(f" SSL Time: {ssl_time} - HTTP Time: {http_time}")
print(f" Server: {server_header}")
print(f" Reverse DNS: {reverse_dns}")
if 'xray_works' in pair:
xray_status = Fore.GREEN + "WORKING" if pair['xray_works'] else Fore.RED + "FAILED"
print(f" Xray Status: {xray_status}{Style.RESET_ALL}")
print()
print(Fore.GREEN + f"\nTotal valid pairs: {len(results)}" + Style.RESET_ALL)
# Offer to save as TXT
if input("\nSave as TXT file? (y/n): ").lower() == 'y':
txt_file = results_file.replace('.json', '.txt')
self.save_to_txt(results, txt_file)
except Exception as e:
print(Fore.RED + f"[!] Error reading results: {e}" + Style.RESET_ALL)
input("\nPress Enter to return to menu...")
def scan_random_ips(self) -> None:
"""Scan random IPs from CDN ranges"""
self.print_banner()
print(Fore.CYAN + "Random IP Scanner\n" + Style.RESET_ALL)
# Let user select CDN
print("Select CDN to scan:")
for i, cdn in enumerate(self.cdn_ranges.keys(), 1):
print(f"{i}. {cdn} ({len(self.cdn_ranges[cdn])} ranges)")
try:
choice = int(input("Enter choice (1-3): ")) - 1
cdn_name = list(self.cdn_ranges.keys())[choice]
except:
print(Fore.RED + "[!] Invalid choice" + Style.RESET_ALL)
time.sleep(2)
return
# Get number of IPs to test
try:
ip_count = int(input("How many random IPs to test? (10-1000): "))
ip_count = max(10, min(1000, ip_count))
except:
ip_count = 100
# Get SNI hostname
sni = input("Enter SNI hostname to test (e.g., gcore.com,www.speedtest.net for cloudflare,fastly.net or com ): ").strip()
if not sni:
print(Fore.RED + "[!] SNI hostname required" + Style.RESET_ALL)
time.sleep(2)
return
output_file = os.path.join(self.output_dir, "valid_pairs.json")
print(Fore.YELLOW + f"\n[*] Generating {ip_count} random IPs from {cdn_name} ranges..." + Style.RESET_ALL)
# Generate random IPs from all ranges
all_ips = []
for cidr in self.cdn_ranges[cdn_name]:
try:
ips = self.generate_random_ips(cidr, max(1, ip_count // len(self.cdn_ranges[cdn_name])))
all_ips.extend(ips)
except:
continue
# Shuffle and limit to requested count
random.shuffle(all_ips)
test_ips = all_ips[:ip_count]
print(Fore.YELLOW + f"[*] Starting scan of {len(test_ips)} IPs..." + Style.RESET_ALL)
self.start_time = time.time()
valid_pairs = []
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
futures = {executor.submit(self.test_sni_pair, ip, sni, DEFAULT_TIMEOUT, port=443 ): ip for ip in test_ips}
for i, future in enumerate(concurrent.futures.as_completed(futures), 1):
ip = futures[future]
try:
result = future.result()
if result:
pair = {
"ip": ip,
"sni": sni,
"cdn": cdn_name,
"https_works": result.get('https_works', False),
"http_works": result.get('http_works', False),
"ping": result.get('ping', None),
"ssl_handshake_time": result.get('ssl_handshake_time', None),
"http_response_time": result.get('http_response_time', None),
"reverse_dns": result.get('reverse_dns', []),
"server_header": result.get('server_header', None),
"timestamp": datetime.now().isoformat()
}
# Build status message
status_parts = []
if pair['https_works']:
status_parts.append("HTTPS")
if pair['http_works']:
status_parts.append("HTTP")
status = "+".join(status_parts) if status_parts else "None"
ping_display = f"{pair['ping']}ms" if pair['ping'] is not None else "N/A"
ssl_time_display = f"{pair['ssl_handshake_time']:.1f}ms" if pair['ssl_handshake_time'] is not None else "N/A"
http_time_display = f"{pair['http_response_time']:.1f}ms" if pair['http_response_time'] is not None else "N/A"
reverse_dns_display = ", ".join(pair['reverse_dns']) if pair['reverse_dns'] else "None"
server_header_display = pair['server_header'] or "N/A"
print(Fore.GREEN + f"[+] Valid pair found: {sni} @ {ip} ({cdn_name}) - Protocols: {status} - Ping: {ping_display}" + Style.RESET_ALL)
print(Fore.CYAN + f" SSL Handshake: {ssl_time_display} - HTTP Response: {http_time_display}" + Style.RESET_ALL)
print(Fore.CYAN + f" Server: {server_header_display}" + Style.RESET_ALL)
print(Fore.CYAN + f" Reverse DNS: {reverse_dns_display}" + Style.RESET_ALL)
valid_pairs.append(pair)
if output_file:
self.save_result(pair, output_file)
except Exception as e:
print(Fore.RED + f"[!] Error testing {sni} @ {ip}: {type(e).__name__}" + Style.RESET_ALL)
# Progress update
if i % 10 == 0 or i == len(test_ips):
elapsed = time.time() - self.start_time
print(Fore.CYAN + f"[*] Progress: {i}/{len(test_ips)} IPs tested | Found: {len(valid_pairs)} | Elapsed: {elapsed:.1f}s" + Style.RESET_ALL)
elapsed = time.time() - self.start_time
print(Fore.GREEN + f"\n[+] Scan completed in {elapsed:.2f} seconds" + Style.RESET_ALL)
print(Fore.CYAN + f"Valid pairs found: {len(valid_pairs)}" + Style.RESET_ALL)
print(Fore.GREEN + f"[+] Results saved to {output_file}" + Style.RESET_ALL)
input("\nPress Enter to return to menu...")
def generate_random_ips(self, cidr: str, count: int) -> List[str]:
"""Generate random IPs from a CIDR range"""
try:
network = IPv4Network(cidr)
return [str(network[random.randint(0, network.num_addresses - 1)]) for _ in range(count)]
except ValueError:
try:
network = IPv6Network(cidr)
return [str(network[random.randint(0, network.num_addresses - 1)]) for _ in range(count)]
except ValueError:
return []
def run_file_scan(self) -> None:
"""Scan domains from a file"""
self.print_banner()
print(Fore.CYAN + "Batch Domain Scan\n" + Style.RESET_ALL)
input_file = input("Enter path to domains file: ").strip()
if not input_file:
print(Fore.RED + "[!] No file specified" + Style.RESET_ALL)
time.sleep(2)
return
output_file = os.path.join(self.output_dir, "valid_pairs.json")
domains = self.load_domains_from_file(input_file)
if not domains:
time.sleep(2)
return
print(Fore.YELLOW + f"\n[*] Found {len(domains)} domains to scan" + Style.RESET_ALL)
print(Fore.YELLOW + "[*] Starting scan..." + Style.RESET_ALL)
self.start_time = time.time()
all_valid_pairs = []
for domain in domains:
valid_pairs = self.scan_domain(domain, output_file)
all_valid_pairs.extend(valid_pairs)
elapsed = time.time() - self.start_time
print(Fore.GREEN + f"\n[+] Scan completed in {elapsed:.2f} seconds" + Style.RESET_ALL)
print(Fore.CYAN + f"Total valid pairs found: {len(all_valid_pairs)}" + Style.RESET_ALL)
print(Fore.GREEN + f"[+] Results saved to {output_file}" + Style.RESET_ALL)
input("\nPress Enter to return to menu...")
def load_domains_from_file(self, file_path: str) -> List[str]:
"""Load domains from a text file"""
try:
with open(file_path, 'r') as f:
return [line.strip() for line in f if line.strip() and not line.startswith('#')]
except FileNotFoundError:
print(Fore.RED + f"[!] File not found: {file_path}" + Style.RESET_ALL)
return []
except Exception as e:
print(Fore.RED + f"[!] Error reading file: {e}" + Style.RESET_ALL)
return []
def test_known_cdns(self) -> None:
"""Test with known CDN domains"""
print(Fore.CYAN + "\n[*] Testing with known CDN domains..." + Style.RESET_ALL)
self.start_time = time.time()
all_results = []
for cdn_name, domains in self.cdn_test_domains.items():
for domain in domains:
print(Fore.YELLOW + f"\n[*] Testing {domain} (expected: {cdn_name})" + Style.RESET_ALL)
valid_pairs = self.scan_domain(domain)
if valid_pairs:
print(Fore.GREEN + f"[+] Found {len(valid_pairs)} valid pairs for {domain}" + Style.RESET_ALL)
for pair in valid_pairs:
protocols = []
if pair.get('https_works', False):
protocols.append("HTTPS")
if pair.get('http_works', False):
protocols.append("HTTP")
protocol_str = "+".join(protocols) if protocols else "None"
ping_display = f"{pair.get('ping', 'N/A')}ms"
ssl_time = f"{pair.get('ssl_handshake_time', 'N/A')}ms"
http_time = f"{pair.get('http_response_time', 'N/A')}ms"
reverse_dns = ", ".join(pair.get('reverse_dns', [])) or "None"
server_header = pair.get('server_header', 'N/A')
print(f" - {pair.get('ip', 'N/A')} ({pair.get('cdn', 'N/A')})")
print(f" Protocols: {protocol_str} - Ping: {ping_display}")
print(f" SSL Time: {ssl_time} - HTTP Time: {http_time}")
print(f" Server: {server_header}")
print(f" Reverse DNS: {reverse_dns}")
print()
all_results.extend(valid_pairs)
else:
print(Fore.RED + f"[!] No valid pairs found for {domain}" + Style.RESET_ALL)
# Save results
if all_results:
output_json = os.path.join(self.output_dir, "known_cdn_results.json")
with open(output_json, 'w') as f:
json.dump(all_results, f, indent=2)
print(Fore.GREEN + f"\n[+] JSON results saved to {output_json}" + Style.RESET_ALL)
elapsed = time.time() - self.start_time
print(Fore.CYAN + f"\n[*] Test completed in {elapsed:.2f} seconds" + Style.RESET_ALL)
input("\nPress Enter to return to menu...")
def test_specific_cdn(self) -> None:
"""Test specific CDN with its known domains"""
self.print_banner()
print(Fore.CYAN + "Deep CDN Test\n" + Style.RESET_ALL)
print("Select CDN for deep testing:")
for i, cdn in enumerate(self.cdn_test_domains.keys(), 1):
print(f"{i}. {cdn}")
try:
choice = int(input("Enter choice (1-3): ")) - 1
cdn_name = list(self.cdn_test_domains.keys())[choice]
test_domains = self.cdn_test_domains[cdn_name]
except:
print(Fore.RED + "[!] Invalid choice" + Style.RESET_ALL)
time.sleep(2)
return
output_json = os.path.join(self.output_dir, f"{cdn_name}_results.json")
all_results = []
for domain in test_domains:
print(Fore.YELLOW + f"\n[*] Testing: {domain}" + Style.RESET_ALL)
ips = self.resolve_domain(domain)
print(Fore.CYAN + f"[*] Resolved IPs: {ips}" + Style.RESET_ALL)