-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
1910 lines (1553 loc) Β· 78.4 KB
/
main.py
File metadata and controls
1910 lines (1553 loc) Β· 78.4 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
"""
Sirra Framework v4.5 - Professional Security Tool
Enhanced with Security Features and Liability Disclaimer
Author: Security Team
Version: 4.5.0
Disclaimer: We are not responsible for any malicious modules added by the user. Use at your own risk.
"""
import os
import sys
import json
import time
import signal
import textwrap
import random
import threading
import subprocess
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Any, Optional
# Fix encoding for all platforms
if sys.platform == 'win32':
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
# First, try to import colorama before dependency check
try:
from colorama import init, Fore, Back, Style
COLORAMA_AVAILABLE = True
except ImportError:
COLORAMA_AVAILABLE = False
# Simple color class if colorama not available
class SimpleColors:
CYAN = '\033[96m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
WHITE = '\033[97m'
RESET = '\033[0m'
BRIGHT_CYAN = '\033[96m'
BRIGHT_GREEN = '\033[92m'
BRIGHT_YELLOW = '\033[93m'
BRIGHT_BLUE = '\033[94m'
BRIGHT_MAGENTA = '\033[95m'
BRIGHT_WHITE = '\033[97m'
# Dependency check
def check_dependencies():
"""Check and install missing dependencies"""
required_packages = ['requests']
missing_packages = []
for package in required_packages:
try:
__import__(package)
except ImportError:
missing_packages.append(package)
if missing_packages:
print("\n" + "="*60)
print(" MISSING DEPENDENCIES ".center(60, "!"))
print("="*60)
print("\nThe following packages are required but not installed:")
for pkg in missing_packages:
print(f" - {pkg}")
print("\n" + "-"*60)
print("To install missing packages, run:")
print(f" pip install {' '.join(missing_packages)}")
print("\n" + "="*60)
# Auto-fix suggestion
try:
confirm = input("\nDo you want to install missing packages now? (y/N): ").strip().lower()
if confirm == 'y':
subprocess.check_call([sys.executable, "-m", "pip", "install"] + missing_packages)
print("\n[β] Dependencies installed successfully!")
print("[*] Please restart the application.")
return True
except:
print("\n[!] Automatic installation failed.")
print("[*] Please install packages manually.")
return False
return True
# Check dependencies before proceeding
if not check_dependencies():
print("\n[!] Exiting due to missing dependencies.")
sys.exit(1)
# Now import dependencies
import requests
# Initialize colorama if available
if COLORAMA_AVAILABLE:
init(autoreset=True)
# Import local modules
try:
from core.orchestrator import get_brain
# Create utils/common if it doesn't exist
try:
from utils.common import Colors, clean_screen
except ImportError:
# Define Colors class locally
class Colors:
CYAN = SimpleColors.CYAN
GREEN = SimpleColors.GREEN
YELLOW = SimpleColors.YELLOW
RED = SimpleColors.RED
BLUE = SimpleColors.BLUE
MAGENTA = SimpleColors.MAGENTA
WHITE = SimpleColors.WHITE
RESET = SimpleColors.RESET
BRIGHT_CYAN = SimpleColors.BRIGHT_CYAN
BRIGHT_GREEN = SimpleColors.BRIGHT_GREEN
BRIGHT_YELLOW = SimpleColors.BRIGHT_YELLOW
BRIGHT_BLUE = SimpleColors.BRIGHT_BLUE
BRIGHT_MAGENTA = SimpleColors.BRIGHT_MAGENTA
BRIGHT_WHITE = SimpleColors.BRIGHT_WHITE
# Define clean_screen function
def clean_screen():
os.system('cls' if os.name == 'nt' else 'clear')
print("[*] Using built-in utilities")
except ImportError as e:
print(f"\n[!] Error importing local modules: {e}")
print("[*] Creating directory structure...")
# Create directory structure
BASE_DIR = Path(__file__).resolve().parent
for dir_name in ["core", "utils", "modules", "config", "output", "logs"]:
(BASE_DIR / dir_name).mkdir(exist_ok=True)
# Create __init__.py files
for init_file in ["core/__init__.py", "utils/__init__.py"]:
(BASE_DIR / init_file).touch()
print("[β] Directory structure created")
print("[*] Please restart the application.")
sys.exit(1)
# Dynamic path management
BASE_DIR = Path(__file__).resolve().parent
# Color setup using our Colors class
C, G, Y, R, B, M, W, RS = Colors.CYAN, Colors.GREEN, Colors.YELLOW, Colors.RED, Colors.BLUE, Colors.MAGENTA, Colors.WHITE, Colors.RESET
BC, BG, BY, BB, BM, BW = Colors.BRIGHT_CYAN, Colors.BRIGHT_GREEN, Colors.BRIGHT_YELLOW, Colors.BRIGHT_BLUE, Colors.BRIGHT_MAGENTA, Colors.BRIGHT_WHITE
class ProxyManager:
"""Professional proxy management with rotation"""
def __init__(self, proxy_list: List[str] = None):
self.proxies = proxy_list or []
self.current_index = 0
self.rotation_lock = threading.Lock()
self.rotation_count = 0
self.failed_proxies = set()
def add_proxy(self, proxy: str) -> bool:
"""Add a proxy to the list"""
if self.validate_proxy_format(proxy) and proxy not in self.proxies:
self.proxies.append(proxy)
return True
return False
def validate_proxy_format(self, proxy: str) -> bool:
"""Validate proxy format (IP:Port or protocol://IP:Port)"""
proxy = proxy.strip()
# Check if it has protocol prefix
if '://' in proxy:
protocol, address = proxy.split('://', 1)
if protocol not in ['http', 'https', 'socks4', 'socks5']:
return False
else:
address = proxy
# Validate IP:Port format
if ':' not in address:
return False
ip, port = address.split(':', 1)
# Validate IP
parts = ip.split('.')
if len(parts) != 4:
return False
for part in parts:
if not part.isdigit():
return False
num = int(part)
if num < 0 or num > 255:
return False
# Validate port
if not port.isdigit():
return False
port_num = int(port)
if port_num < 1 or port_num > 65535:
return False
return True
def rotate_proxy(self) -> Optional[Dict[str, str]]:
"""Get next proxy with rotation"""
if not self.proxies:
return None
with self.rotation_lock:
# Filter out failed proxies
available_proxies = [p for p in self.proxies if p not in self.failed_proxies]
if not available_proxies:
# Reset if all proxies failed
self.failed_proxies.clear()
available_proxies = self.proxies
# Select proxy based on mode (simple round-robin)
if self.current_index >= len(available_proxies):
self.current_index = 0
selected_proxy = available_proxies[self.current_index]
self.current_index = (self.current_index + 1) % len(available_proxies)
self.rotation_count += 1
# Format proxy dict for requests
if '://' in selected_proxy:
return {'http': selected_proxy, 'https': selected_proxy}
else:
return {'http': f'http://{selected_proxy}', 'https': f'http://{selected_proxy}'}
def mark_failed(self, proxy: str):
"""Mark a proxy as failed"""
self.failed_proxies.add(proxy)
def clear_failed(self):
"""Clear failed proxies list"""
self.failed_proxies.clear()
def get_random_proxy(self) -> Optional[Dict[str, str]]:
"""Get a random proxy"""
if not self.proxies:
return None
available_proxies = [p for p in self.proxies if p not in self.failed_proxies]
if not available_proxies:
self.failed_proxies.clear()
available_proxies = self.proxies
selected = random.choice(available_proxies)
if '://' in selected:
return {'http': selected, 'https': selected}
else:
return {'http': f'http://{selected}', 'https': f'http://{selected}'}
def get_count(self) -> int:
"""Get total proxy count"""
return len(self.proxies)
def get_active_count(self) -> int:
"""Get active (non-failed) proxy count"""
return len([p for p in self.proxies if p not in self.failed_proxies])
class SirraFramework:
def __init__(self):
"""Initialize the framework"""
try:
self.brain = get_brain()
self.config_dir = BASE_DIR / "config"
self.config_file = self.config_dir / "settings.json"
self.running = True
self._exit_flag = False
# Initialize proxy manager
self.proxy_manager = None
# Default settings - COMPLETE DEFAULTS
self.default_settings = {
"proxy_mode": "Rotate",
"proxy_list": [],
"custom_names": {},
"auto_refresh_proxies": True,
"request_timeout": 10,
"max_threads": 5,
"log_level": "INFO",
"output_format": "text",
"save_logs": True,
"enable_security_scan": True,
"disable_security": False,
"show_disclaimer": True,
"proxy_test_enabled": True,
"auto_remove_failed_proxies": True,
"max_retry_attempts": 3,
"theme": "dark",
"compact_mode": False,
"font_size": "normal"
}
# Initialize with defaults
self.settings = self.default_settings.copy()
self.stats = {
"rotations": 0,
"current_ip": "Direct Connection",
"total_scans": 0,
"successful_scans": 0,
"failed_scans": 0,
"security_blocks": 0,
"proxy_failures": 0,
"start_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"total_execution_time": 0
}
self.load_settings()
# Initialize proxy manager with loaded proxies
self.proxy_manager = ProxyManager(self.settings['proxy_list'])
# Setup signal handler
self._setup_signal_handler()
print(f"{G}[β] Sirra Framework initialized successfully{RS}")
print(f"{G}[β] Security Scanner: {'ENABLED' if not self.settings['disable_security'] else 'DISABLED'}{RS}")
except Exception as e:
self.handle_error(f"Failed to initialize framework: {e}", critical=True)
def _setup_signal_handler(self):
"""Setup signal handler for graceful shutdown"""
def signal_handler(signum, frame):
"""Handle Ctrl+C (SIGINT) gracefully"""
if self._exit_flag:
# Second Ctrl+C - force exit
print(f"\n{R}[!] Force exiting...{RS}")
sys.exit(1)
self._exit_flag = True
print(f"\n{Y}[!] Interrupt detected. Press Ctrl+C again to force exit.{RS}")
signal.signal(signal.SIGINT, signal_handler)
def get_terminal_width(self):
"""Get dynamic terminal width with proper fallback"""
try:
width = os.get_terminal_size().columns
# Apply compact mode adjustment
if self.settings.get('compact_mode', False):
width = min(width, 70)
# Apply font size adjustment
font_size = self.settings.get('font_size', 'normal')
if font_size == 'large':
width = max(width, 80) # Ensure minimum width for large font
elif font_size == 'small':
width = min(width, 100) # Limit max width for small font
# Ensure reasonable bounds
width = max(60, min(width, 120))
return width
except:
# Fallback based on settings
if self.settings.get('compact_mode', False):
return 65
return 80
def handle_error(self, message, critical=False):
"""Handle errors with proper logging"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
error_msg = f"[{timestamp}] ERROR: {message}"
# Print to console
print(f"\n{R}[!] {message}{RS}")
# Log to file if enabled
if self.settings.get('save_logs', True):
log_file = BASE_DIR / "logs" / "error.log"
try:
log_file.parent.mkdir(exist_ok=True)
with open(log_file, 'a', encoding='utf-8') as f:
f.write(error_msg + "\n")
except:
pass
if critical:
print(f"\n{R}[!] Critical error. Exiting...{RS}")
sys.exit(1)
time.sleep(2)
def load_settings(self):
"""Load settings from JSON file with recovery - FIXED VERSION"""
if self.config_file.exists():
try:
with open(self.config_file, 'r', encoding='utf-8') as f:
loaded_data = json.load(f)
if not isinstance(loaded_data, dict):
print(f"{Y}[*] Settings file corrupted. Creating backup...{RS}")
self._backup_settings_file()
raise ValueError("Settings file must contain a JSON object")
# Merge loaded data with defaults (ensuring all keys exist)
for key in self.default_settings:
if key in loaded_data:
# Type validation and assignment
value = loaded_data[key]
if key in ['request_timeout', 'max_threads', 'max_retry_attempts']:
if isinstance(value, (int, float)) and value > 0:
self.settings[key] = int(value)
elif key in ['auto_refresh_proxies', 'save_logs', 'enable_security_scan',
'disable_security', 'show_disclaimer', 'proxy_test_enabled',
'auto_remove_failed_proxies', 'compact_mode']:
if isinstance(value, bool):
self.settings[key] = value
elif key == 'proxy_mode':
if value in ['Direct', 'Rotate', 'Random']:
self.settings[key] = value
elif key == 'log_level':
if value in ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']:
self.settings[key] = value
elif key == 'output_format':
if value in ['text', 'json', 'csv', 'html']:
self.settings[key] = value
elif key == 'proxy_list':
if isinstance(value, list):
self.settings[key] = value
elif key == 'theme':
if value in ['dark', 'light', 'auto']:
self.settings[key] = value
elif key == 'font_size':
if value in ['small', 'normal', 'large']:
self.settings[key] = value
elif key == 'custom_names':
if isinstance(value, dict):
self.settings[key] = value
else:
# Key not in loaded data, use default
self.settings[key] = self.default_settings[key]
print(f"{G}[β] Settings loaded successfully{RS}")
except json.JSONDecodeError as e:
self.handle_error(f"JSON syntax error in settings file: {e}")
print(f"{Y}[*] Creating new settings file with defaults...{RS}")
self._backup_settings_file()
self.save_settings()
except Exception as e:
self.handle_error(f"Error loading settings: {e}")
print(f"{Y}[*] Using default settings...{RS}")
self.settings = self.default_settings.copy()
self.save_settings()
else:
print(f"{Y}[*] Settings file not found. Creating default...{RS}")
self.save_settings()
def _backup_settings_file(self):
"""Backup corrupted settings file"""
if self.config_file.exists():
backup_file = self.config_file.with_suffix('.json.bak')
try:
import shutil
shutil.copy2(self.config_file, backup_file)
print(f"{G}[β] Settings backed up to: {backup_file}{RS}")
except:
print(f"{R}[!] Failed to backup settings{RS}")
def save_settings(self):
"""Save settings to JSON file"""
try:
self.config_dir.mkdir(exist_ok=True)
# Update proxy list from manager if exists
if self.proxy_manager:
self.settings['proxy_list'] = self.proxy_manager.proxies
with open(self.config_file, 'w', encoding='utf-8') as f:
json.dump(self.settings, f, indent=4, ensure_ascii=False, sort_keys=True)
print(f"{G}[β] Settings saved{RS}")
return True
except Exception as e:
self.handle_error(f"Failed to save settings: {e}")
return False
def banner(self):
"""Display application banner with disclaimer"""
clean_screen()
# Get dynamic width
width = self.get_terminal_width()
# Liability Disclaimer
if self.settings.get('show_disclaimer', True):
disclaimer = "β οΈ DISCLAIMER: We are not responsible for any malicious modules added by the user. Use at your own risk."
disclaimer_lines = textwrap.wrap(disclaimer, width=width-4)
print(f"{R}β{'β' * (width - 2)}β{RS}")
for line in disclaimer_lines:
print(f"{R}β {line.center(width - 4)} β{RS}")
print(f"{R}β{'β' * (width - 2)}β{RS}")
print()
# Main Banner
print(f"{BC}β{'β' * (width - 2)}β{RS}")
# ASCII Art - Responsive
if width >= 80:
ascii_art = [
"ββββββββββββββββββ βββββββ ββββββ ",
"βββββββββββββββββββββββββββββββββββ",
"βββββββββββββββββββββββββββββββββββ",
"βββββββββββββββββββββββββββββββββββ",
"ββββββββββββββ ββββββ ββββββ βββ",
"ββββββββββββββ ββββββ ββββββ βββ"
]
elif width >= 70:
ascii_art = [
"ββββββββββββββββββ βββββββ ββββββ",
"βββββββββββββββββββββββββββββββββββ",
"βββββββββββββββββββββββββββββββββββ",
"βββββββββββββββββββββββββββββββββββ",
"ββββββββββββββ ββββββ ββββββ βββ",
"ββββββββββββββ ββββββ ββββββ βββ"
]
else: # Compact mode
ascii_art = [
"SIRRA FRAMEWORK",
"v4.5 - Professional Edition"
]
for line in ascii_art:
print(f"{BC}β{BW}{line.center(width - 2)}{BC}β{RS}")
if width >= 70:
print(f"{BC}β{BW}{'v4.5 - Professional Edition'.center(width - 2)}{BC}β{RS}")
print(f"{BC}β{BW}{'With Enhanced Security Scanner'.center(width - 2)}{BC}β{RS}")
print(f"{BC}β{'β' * (width - 2)}β{RS}")
# Status line
proxy_status = ""
if self.proxy_manager:
if self.settings['proxy_mode'] == 'Direct':
proxy_status = "Direct Connection"
else:
active = self.proxy_manager.get_active_count()
total = self.proxy_manager.get_count()
proxy_status = f"{self.settings['proxy_mode']} ({active}/{total})"
status = f"{BC}β£{RS} MODE: {BY}{proxy_status}{RS} | SCANS: {BY}{self.stats['total_scans']}{RS} {BC}β«{RS}"
print(status.center(width + 10))
# Stats
success_rate = 0
if self.stats['total_scans'] > 0:
success_rate = (self.stats['successful_scans'] / self.stats['total_scans']) * 100
stats_line = f"{BC}π Success: {G}{self.stats['successful_scans']}{RS} | Failed: {R}{self.stats['failed_scans']}{RS} | Rate: {BY}{success_rate:.1f}%{RS}"
print(stats_line.center(width + 10))
# Security stats
security_status = f"{R}π‘οΈ Security: DISABLED{RS}" if self.settings['disable_security'] else f"{G}π‘οΈ Security: ENABLED{RS}"
print(security_status.center(width + 10))
if self.stats.get('security_blocks', 0) > 0:
security_line = f"{R}π« Security Blocks: {self.stats['security_blocks']}{RS}"
print(security_line.center(width + 10))
print()
def fetch_proxies(self, test_proxies=True):
"""Fetch fresh proxy list and test them"""
print(f"\n{Y}[*] Fetching fresh proxy list...{RS}")
try:
sources = [
"https://raw.githubusercontent.com/TheSpeedX/SOCKS-List/master/http.txt",
"https://raw.githubusercontent.com/clarketm/proxy-list/master/proxy-list.txt",
"https://www.proxy-list.download/api/v1/get?type=http"
]
all_proxies = []
timeout = self.settings.get('request_timeout', 10)
for url in sources:
try:
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers, timeout=timeout)
response.raise_for_status()
raw_proxies = response.text.splitlines()
for proxy in raw_proxies:
proxy = proxy.strip()
if not proxy:
continue
# Clean and format proxy
if '://' in proxy:
parts = proxy.split('://')
if len(parts) == 2:
proxy = parts[1]
if ':' in proxy:
ip, port = proxy.split(':', 1)
if port.isdigit() and 1 <= int(port) <= 65535:
if self.validate_ip(ip):
formatted_proxy = f"{ip}:{port}"
if formatted_proxy not in all_proxies:
all_proxies.append(formatted_proxy)
print(f"{G}[+] Found {len(raw_proxies)} proxies from source{RS}")
except Exception as e:
print(f"{R}[!] Failed to fetch from {url}: {e}{RS}")
if all_proxies:
# Test proxies if enabled
if test_proxies and self.settings.get('proxy_test_enabled', True):
print(f"{Y}[*] Testing {len(all_proxies)} proxies...{RS}")
working_proxies = self.test_proxies(all_proxies)
if working_proxies:
self.settings['proxy_list'] = working_proxies
if self.proxy_manager:
self.proxy_manager.proxies = working_proxies
self.proxy_manager.clear_failed()
self.save_settings()
print(f"{G}[β] {len(working_proxies)} working proxies loaded{RS}")
if len(all_proxies) - len(working_proxies) > 0:
print(f"{Y}[*] {len(all_proxies) - len(working_proxies)} proxies failed test{RS}")
return True
else:
print(f"{R}[!] No working proxies found{RS}")
return False
else:
# Skip testing, add all proxies
self.settings['proxy_list'] = all_proxies
if self.proxy_manager:
self.proxy_manager.proxies = all_proxies
self.save_settings()
print(f"{G}[β] {len(all_proxies)} proxies loaded (untested){RS}")
return True
else:
print(f"{R}[!] No valid proxies found{RS}")
except Exception as e:
print(f"{R}[!] Error: {e}{RS}")
return False
def test_proxies(self, proxies, max_workers=10):
"""Test a list of proxies"""
import concurrent.futures
test_url = "http://httpbin.org/ip"
timeout = self.settings.get('request_timeout', 5)
working_proxies = []
def test_proxy(proxy):
try:
proxy_dict = {'http': f'http://{proxy}', 'https': f'http://{proxy}'}
response = requests.get(test_url, proxies=proxy_dict, timeout=timeout)
if response.status_code == 200:
return proxy
except:
pass
return None
print(f"{Y}[*] Testing proxies (max {max_workers} concurrent)...{RS}")
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
future_to_proxy = {executor.submit(test_proxy, proxy): proxy for proxy in proxies[:100]} # Test first 100
for future in concurrent.futures.as_completed(future_to_proxy):
proxy = future_to_proxy[future]
try:
result = future.result(timeout=timeout + 2)
if result:
working_proxies.append(result)
print(f"{G}[+] Working: {result}{RS}", end='\r')
except:
pass
print() # New line after progress
return working_proxies
def validate_ip(self, ip):
"""Basic IP validation"""
parts = ip.split('.')
if len(parts) != 4:
return False
for part in parts:
if not part.isdigit():
return False
num = int(part)
if num < 0 or num > 255:
return False
return True
def get_proxy_for_request(self):
"""Get proxy based on current mode"""
if self.settings['proxy_mode'] == 'Direct' or not self.proxy_manager:
return None
if self.settings['proxy_mode'] == 'Rotate':
return self.proxy_manager.rotate_proxy()
elif self.settings['proxy_mode'] == 'Random':
return self.proxy_manager.get_random_proxy()
return None
def get_user_inputs(self, input_config):
"""Get user inputs based on module configuration"""
inputs = {}
if not input_config:
# Default input if no config provided
target = input(f"\n{BC}β{RS} {Y}π― Target URL/IP: {RS}").strip()
return {'target': target}
width = self.get_terminal_width()
print(f"\n{BC}β{'β' * (width - 2)}β{RS}")
print(f"{BC}β{BW} π MODULE INPUTS {BW}{' ' * (width - 22)}{BC}β{RS}")
print(f"{BC}β{'β' * (width - 2)}β€{RS}")
for input_field in input_config:
name = input_field.get('name', 'input')
field_type = input_field.get('type', 'text')
prompt = input_field.get('prompt', f'Enter {name}')
required = input_field.get('required', True)
default = input_field.get('default', '')
choices = input_field.get('choices', [])
while True:
if field_type == 'select' and choices:
# Display choices
print(f"{BC}β{RS} {G}β {prompt}{RS}")
for idx, choice in enumerate(choices, 1):
choice_display = str(choice)
if len(choice_display) > width - 15:
choice_display = choice_display[:width - 18] + "..."
print(f"{BC}β{RS} {C}{idx}.{RS} {choice_display}")
choice_input = input(f"{BC}β{RS} {Y}Select option (1-{len(choices)}): {RS}").strip()
if choice_input.isdigit():
idx = int(choice_input)
if 1 <= idx <= len(choices):
inputs[name] = choices[idx-1]
break
elif choice_input == '' and not required:
inputs[name] = default
break
print(f"{BC}β{RS} {R}[!] Invalid selection{RS}")
elif field_type == 'boolean':
yn_input = input(f"{BC}β{RS} {Y}{prompt} (y/N): {RS}").strip().lower()
if yn_input in ['y', 'yes']:
inputs[name] = True
elif yn_input in ['n', 'no', '']:
inputs[name] = False
break
else: # text, number, etc.
value_input = input(f"{BC}β{RS} {Y}{prompt}: {RS}").strip()
if not value_input and required:
if default:
inputs[name] = default
print(f"{BC}β{RS} {G}[*] Using default: {default}{RS}")
break
else:
print(f"{BC}β{RS} {R}[!] This field is required{RS}")
continue
elif not value_input and not required:
inputs[name] = default
break
else:
# Validate based on type
if field_type == 'number' and not value_input.replace('.', '', 1).isdigit():
print(f"{BC}β{RS} {R}[!] Please enter a valid number{RS}")
continue
elif field_type == 'url' and not (value_input.startswith('http://') or value_input.startswith('https://')):
print(f"{BC}β{RS} {Y}[!] URL should start with http:// or https://{RS}")
continue
elif field_type == 'ip' and not self.validate_ip(value_input):
print(f"{BC}β{RS} {R}[!] Invalid IP address format{RS}")
continue
inputs[name] = value_input
break
print(f"{BC}β{'β' * (width - 2)}β{RS}")
return inputs
def execute_tool(self, tool):
"""Execute selected tool with dynamic inputs and security checks"""
self.banner()
# Security warning for modules if security is enabled
if (not self.settings['disable_security'] and
tool.get('security_status') != 'SAFE' and
self.settings.get('enable_security_scan', True)):
print(f"{R}[!] WARNING: This module has not passed full security scan{RS}")
print(f"{R}[!] Security Status: {tool.get('security_status', 'UNKNOWN')}{RS}")
confirm = input(f"{Y}Continue anyway? (y/N): {RS}").strip().lower()
if confirm != 'y':
print(f"{Y}[*] Execution cancelled{RS}")
time.sleep(1)
return
# Module info display
width = self.get_terminal_width()
box_width = width - 2
print(f"{BC}β{'β' * box_width}β{RS}")
print(f"{BC}β{BW} π MODULE LAUNCHER {BW}{' ' * (box_width - 22)}{BC}β{RS}")
print(f"{BC}β{'β' * box_width}β€{RS}")
# Module name
name_display = f"{BG}π¦ {tool['display_name']}{RS}"
print(f"{BC}β {name_display:<{box_width-3}} {BC}β{RS}")
print(f"{BC}β{'β' * box_width}β€{RS}")
# Module info
security_status = "DISABLED" if self.settings['disable_security'] else tool.get('security_status', 'UNKNOWN')
security_color = G if security_status == 'SAFE' or self.settings['disable_security'] else R
info_items = [
(f"{BC}β {RS}Version", f"{G}{tool.get('version', '1.0.0')}{RS}"),
(f"{BC}π€ {RS}Author", f"{C}{tool.get('author', 'Unknown')}{RS}"),
(f"{BC}π {RS}Category", f"{Y}{tool.get('category', 'General')}{RS}"),
(f"{BC}π‘οΈ {RS}Security", f"{security_color}{security_status}{RS}")
]
for label, value in info_items:
line = f" {label}: {value}"
print(f"{BC}β {line:<{box_width-3}} {BC}β{RS}")
print(f"{BC}β{'β' * box_width}β€{RS}")
# Description
desc = tool.get('description', 'No description provided')
print(f"{BC}β{BW} π Description:{RS}{' ' * (box_width - 18)}{BC}β{RS}")
print(f"{BC}β{'β' * box_width}β€{RS}")
desc_lines = textwrap.wrap(desc, width=box_width-6)
for line in desc_lines:
print(f"{BC}β {W}{line:<{box_width-6}}{BC} β{RS}")
# Show input configuration if exists
if 'inputs' in tool and tool['inputs']:
print(f"{BC}β{'β' * box_width}β€{RS}")
print(f"{BC}β{BW} π Required Inputs:{RS}{' ' * (box_width - 22)}{BC}β{RS}")
print(f"{BC}β{'β' * box_width}β€{RS}")
for input_field in tool['inputs']:
name = input_field.get('name', 'input')
field_type = input_field.get('type', 'text')
required = "π΄ Required" if input_field.get('required', True) else "π’ Optional"
line = f" β’ {C}{name}{RS} ({Y}{field_type}{RS}) - {required}"
print(f"{BC}β {line:<{box_width-3}} {BC}β{RS}")
print(f"{BC}β{'β' * box_width}β{RS}")
# Get dynamic inputs based on module configuration
input_config = tool.get('inputs', [])
module_inputs = self.get_user_inputs(input_config)
if not module_inputs:
print(f"\n{R}[!] No inputs provided{RS}")
time.sleep(1)
return
# Prepare options
options = {
"proxy_mode": self.settings['proxy_mode'],
"proxy_list": self.settings['proxy_list'],
"get_proxy": self.get_proxy_for_request,
"callback": self.update_stats,
"timeout": self.settings.get('request_timeout', 10),
"max_threads": self.settings.get('max_threads', 5),
"security_mode": not self.settings['disable_security'],
"disable_security": self.settings['disable_security']
}
print(f"\n{Y}[*] Starting execution...{RS}")
print(f"{Y}[*] Security Scanner: {'ENABLED' if not self.settings['disable_security'] else 'DISABLED'}{RS}")
time.sleep(0.5)
start_time = time.time()
try:
# Execute module with dynamic inputs
result = self.brain.run_module(
tool['path'],
module_inputs,
options,
disable_security=self.settings['disable_security']
)
execution_time = time.time() - start_time
self.stats['total_execution_time'] += execution_time
if result is not None:
self.stats['total_scans'] += 1
# Check result for success/failure
if isinstance(result, dict):
if result.get('success', True):
self.stats['successful_scans'] += 1
print(f"\n{G}[β] Execution successful ({execution_time:.2f}s){RS}")
else:
self.stats['failed_scans'] += 1
error_msg = result.get('error', 'Unknown error')
print(f"\n{R}[β] Execution failed: {error_msg} ({execution_time:.2f}s){RS}")
else:
# Non-dict result assumed successful
self.stats['successful_scans'] += 1
print(f"\n{G}[β] Execution completed ({execution_time:.2f}s){RS}")
# Show result if available
if isinstance(result, dict) and 'result' in result:
self.display_result(result['result'])
else:
self.stats['total_scans'] += 1
self.stats['failed_scans'] += 1
if not self.settings['disable_security']:
self.stats['security_blocks'] = self.stats.get('security_blocks', 0) + 1
print(f"\n{R}[β] Execution blocked due to security issues{RS}")
else:
print(f"\n{R}[β] Execution failed{RS}")
except Exception as e:
self.stats['total_scans'] += 1
self.stats['failed_scans'] += 1
self.handle_error(f"Execution failed: {e}")
input(f"\n{G}Press Enter to continue...{RS}")
def display_result(self, result):
"""Display execution result in appropriate format"""
width = self.get_terminal_width()
title = " EXECUTION RESULT "
title_length = len(title)
print(f"\n{BC}β{'β' * ((width - title_length) // 2 - 1)}{title}{'β' * (width - (width - title_length) // 2 - title_length - 2)}β{RS}")
if isinstance(result, dict):
for key, value in result.items():
if isinstance(value, (dict, list)):
value_str = json.dumps(value, indent=2)
else:
value_str = str(value)
# Truncate long values
if len(value_str) > width - 15:
value_str = value_str[:width - 18] + "..."
print(f"{BC}β{RS} {G}{key}:{RS} {W}{value_str}{RS}")
elif isinstance(result, list):
max_items = 8 if self.settings.get('compact_mode', False) else 10
for i, item in enumerate(result[:max_items], 1):
item_str = str(item)
if len(item_str) > width - 10: