forked from 0x4m4/hexstrike-ai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreference-server.py
More file actions
15410 lines (13047 loc) · 658 KB
/
reference-server.py
File metadata and controls
15410 lines (13047 loc) · 658 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
"""
HexStrike AI - Advanced Penetration Testing Framework Server
Enhanced with AI-Powered Intelligence & Automation
🚀 Bug Bounty | CTF | Red Team | Security Research
RECENT ENHANCEMENTS (v6.0):
✅ Complete color consistency with reddish hacker theme
✅ Removed duplicate classes (PythonEnvironmentManager, CVEIntelligenceManager)
✅ Enhanced visual output with ModernVisualEngine
✅ Organized code structure with proper section headers
✅ 100+ security tools with intelligent parameter optimization
✅ AI-driven decision engine for tool selection
✅ Advanced error handling and recovery systems
Architecture: Two-script system (hexstrike_server.py + hexstrike_mcp.py)
Framework: FastMCP integration for AI agent communication
"""
import argparse
import json
import logging
import os
import subprocess
import sys
import traceback
import threading
import time
import hashlib
import pickle
import base64
import queue
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta
from typing import Dict, Any, Optional
from collections import OrderedDict
import shutil
import venv
import zipfile
from pathlib import Path
from flask import Flask, request, jsonify
import psutil
import signal
import requests
import re
import socket
import urllib.parse
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Set, Tuple
import asyncio
import aiohttp
from urllib.parse import urljoin, urlparse, parse_qs
from bs4 import BeautifulSoup
import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, WebDriverException
import mitmproxy
from mitmproxy import http as mitmhttp
from mitmproxy.tools.dump import DumpMaster
from mitmproxy.options import Options as MitmOptions
# ============================================================================
# LOGGING CONFIGURATION (MUST BE FIRST)
# ============================================================================
# Configure logging with fallback for permission issues
try:
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('hexstrike.log')
]
)
except PermissionError:
# Fallback to console-only logging if file creation fails
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
# Flask app configuration
app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False
# API Configuration
API_PORT = int(os.environ.get('HEXSTRIKE_PORT', 8888))
API_HOST = os.environ.get('HEXSTRIKE_HOST', '127.0.0.1')
# ============================================================================
# MODERN VISUAL ENGINE (v2.0 ENHANCEMENT)
# ============================================================================
class ModernVisualEngine:
"""Beautiful, modern output formatting with animations and colors"""
# Enhanced color palette with reddish tones and better highlighting
COLORS = {
'MATRIX_GREEN': '\033[38;5;46m',
'NEON_BLUE': '\033[38;5;51m',
'ELECTRIC_PURPLE': '\033[38;5;129m',
'CYBER_ORANGE': '\033[38;5;208m',
'HACKER_RED': '\033[38;5;196m',
'TERMINAL_GRAY': '\033[38;5;240m',
'BRIGHT_WHITE': '\033[97m',
'RESET': '\033[0m',
'BOLD': '\033[1m',
'DIM': '\033[2m',
# New reddish tones and highlighting colors
'BLOOD_RED': '\033[38;5;124m',
'CRIMSON': '\033[38;5;160m',
'DARK_RED': '\033[38;5;88m',
'FIRE_RED': '\033[38;5;202m',
'ROSE_RED': '\033[38;5;167m',
'BURGUNDY': '\033[38;5;52m',
'SCARLET': '\033[38;5;197m',
'RUBY': '\033[38;5;161m',
# Unified theme primary/secondary (used going forward instead of legacy blue/green accents)
'PRIMARY_BORDER': '\033[38;5;160m', # CRIMSON
'ACCENT_LINE': '\033[38;5;196m', # HACKER_RED
'ACCENT_GRADIENT': '\033[38;5;124m', # BLOOD_RED (for subtle alternation)
# Highlighting colors
'HIGHLIGHT_RED': '\033[48;5;196m\033[38;5;15m', # Red background, white text
'HIGHLIGHT_YELLOW': '\033[48;5;226m\033[38;5;16m', # Yellow background, black text
'HIGHLIGHT_GREEN': '\033[48;5;46m\033[38;5;16m', # Green background, black text
'HIGHLIGHT_BLUE': '\033[48;5;51m\033[38;5;16m', # Blue background, black text
'HIGHLIGHT_PURPLE': '\033[48;5;129m\033[38;5;15m', # Purple background, white text
# Status colors with reddish tones
'SUCCESS': '\033[38;5;46m', # Bright green
'WARNING': '\033[38;5;208m', # Orange
'ERROR': '\033[38;5;196m', # Bright red
'CRITICAL': '\033[48;5;196m\033[38;5;15m\033[1m', # Red background, white bold text
'INFO': '\033[38;5;51m', # Cyan
'DEBUG': '\033[38;5;240m', # Gray
# Vulnerability severity colors
'VULN_CRITICAL': '\033[48;5;124m\033[38;5;15m\033[1m', # Dark red background
'VULN_HIGH': '\033[38;5;196m\033[1m', # Bright red bold
'VULN_MEDIUM': '\033[38;5;208m\033[1m', # Orange bold
'VULN_LOW': '\033[38;5;226m', # Yellow
'VULN_INFO': '\033[38;5;51m', # Cyan
# Tool status colors
'TOOL_RUNNING': '\033[38;5;46m\033[5m', # Blinking green
'TOOL_SUCCESS': '\033[38;5;46m\033[1m', # Bold green
'TOOL_FAILED': '\033[38;5;196m\033[1m', # Bold red
'TOOL_TIMEOUT': '\033[38;5;208m\033[1m', # Bold orange
'TOOL_RECOVERY': '\033[38;5;129m\033[1m', # Bold purple
# Progress and animation colors
'PROGRESS_BAR': '\033[38;5;46m', # Green
'PROGRESS_EMPTY': '\033[38;5;240m', # Gray
'SPINNER': '\033[38;5;51m', # Cyan
'PULSE': '\033[38;5;196m\033[5m' # Blinking red
}
# Progress animation styles
PROGRESS_STYLES = {
'dots': ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'],
'bars': ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'],
'arrows': ['←', '↖', '↑', '↗', '→', '↘', '↓', '↙'],
'pulse': ['●', '◐', '◑', '◒', '◓', '◔', '◕', '◖', '◗', '◘']
}
@staticmethod
def create_banner() -> str:
"""Create the enhanced HexStrike banner"""
# Build a blood-red themed border using primary/gradient alternation
border_color = ModernVisualEngine.COLORS['PRIMARY_BORDER']
accent = ModernVisualEngine.COLORS['ACCENT_LINE']
gradient = ModernVisualEngine.COLORS['ACCENT_GRADIENT']
RESET = ModernVisualEngine.COLORS['RESET']
BOLD = ModernVisualEngine.COLORS['BOLD']
title_block = f"{accent}{BOLD}"
banner = f"""
{title_block}
██╗ ██╗███████╗██╗ ██╗███████╗████████╗██████╗ ██╗██╗ ██╗███████╗
██║ ██║██╔════╝╚██╗██╔╝██╔════╝╚══██╔══╝██╔══██╗██║██║ ██╔╝██╔════╝
███████║█████╗ ╚███╔╝ ███████╗ ██║ ██████╔╝██║█████╔╝ █████╗
██╔══██║██╔══╝ ██╔██╗ ╚════██║ ██║ ██╔══██╗██║██╔═██╗ ██╔══╝
██║ ██║███████╗██╔╝ ██╗███████║ ██║ ██║ ██║██║██║ ██╗███████╗
╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝╚═╝ ╚═╝╚══════╝
{RESET}
{border_color}┌─────────────────────────────────────────────────────────────────────┐
│ {ModernVisualEngine.COLORS['BRIGHT_WHITE']}🚀 HexStrike AI - Blood-Red Offensive Intelligence Core{border_color} │
│ {accent}⚡ AI-Automated Recon | Exploitation | Analysis Pipeline{border_color} │
│ {gradient}🎯 Bug Bounty | CTF | Red Team | Zero-Day Research{border_color} │
└─────────────────────────────────────────────────────────────────────┘{RESET}
{ModernVisualEngine.COLORS['TERMINAL_GRAY']}[INFO] Server starting on {API_HOST}:{API_PORT}
[INFO] 150+ integrated modules | Adaptive AI decision engine active
[INFO] Blood-red theme engaged – unified offensive operations UI{RESET}
"""
return banner
@staticmethod
def create_progress_bar(current: int, total: int, width: int = 50, tool: str = "") -> str:
"""Create a beautiful progress bar with cyberpunk styling"""
if total == 0:
percentage = 0
else:
percentage = min(100, (current / total) * 100)
filled = int(width * percentage / 100)
bar = '█' * filled + '░' * (width - filled)
border = ModernVisualEngine.COLORS['PRIMARY_BORDER']
fill_col = ModernVisualEngine.COLORS['ACCENT_LINE']
return f"""
{border}┌─ {tool} ─{'─' * (width - len(tool) - 4)}┐
│ {fill_col}{bar}{border} │ {percentage:6.1f}%
└─{'─' * (width + 10)}┘{ModernVisualEngine.COLORS['RESET']}"""
@staticmethod
def render_progress_bar(progress: float, width: int = 40, style: str = 'cyber',
label: str = "", eta: float = 0, speed: str = "") -> str:
"""Render a beautiful progress bar with multiple styles"""
# Clamp progress between 0 and 1
progress = max(0.0, min(1.0, progress))
# Calculate filled and empty portions
filled_width = int(width * progress)
empty_width = width - filled_width
# Style-specific rendering
if style == 'cyber':
filled_char = '█'
empty_char = '░'
bar_color = ModernVisualEngine.COLORS['ACCENT_LINE']
progress_color = ModernVisualEngine.COLORS['PRIMARY_BORDER']
elif style == 'matrix':
filled_char = '▓'
empty_char = '▒'
bar_color = ModernVisualEngine.COLORS['ACCENT_LINE']
progress_color = ModernVisualEngine.COLORS['ACCENT_GRADIENT']
elif style == 'neon':
filled_char = '━'
empty_char = '─'
bar_color = ModernVisualEngine.COLORS['PRIMARY_BORDER']
progress_color = ModernVisualEngine.COLORS['CYBER_ORANGE']
else: # default
filled_char = '█'
empty_char = '░'
bar_color = ModernVisualEngine.COLORS['ACCENT_LINE']
progress_color = ModernVisualEngine.COLORS['PRIMARY_BORDER']
# Build the progress bar
filled_part = bar_color + filled_char * filled_width
empty_part = ModernVisualEngine.COLORS['TERMINAL_GRAY'] + empty_char * empty_width
percentage = f"{progress * 100:.1f}%"
# Add ETA and speed if provided
extra_info = ""
if eta > 0:
extra_info += f" ETA: {eta:.1f}s"
if speed:
extra_info += f" Speed: {speed}"
# Build final progress bar
bar_display = f"[{filled_part}{empty_part}{ModernVisualEngine.COLORS['RESET']}] {progress_color}{percentage}{ModernVisualEngine.COLORS['RESET']}"
if label:
return f"{label}: {bar_display}{extra_info}"
else:
return f"{bar_display}{extra_info}"
@staticmethod
def create_live_dashboard(processes: Dict[int, Dict[str, Any]]) -> str:
"""Create a live dashboard showing all active processes"""
if not processes:
return f"""
{ModernVisualEngine.COLORS['PRIMARY_BORDER']}╭─────────────────────────────────────────────────────────────────────────────╮
│ {ModernVisualEngine.COLORS['ACCENT_LINE']}📊 HEXSTRIKE LIVE DASHBOARD{ModernVisualEngine.COLORS['PRIMARY_BORDER']} │
├─────────────────────────────────────────────────────────────────────────────┤
│ {ModernVisualEngine.COLORS['TERMINAL_GRAY']}No active processes currently running{ModernVisualEngine.COLORS['PRIMARY_BORDER']} │
╰─────────────────────────────────────────────────────────────────────────────╯{ModernVisualEngine.COLORS['RESET']}
"""
dashboard_lines = [
f"{ModernVisualEngine.COLORS['PRIMARY_BORDER']}╭─────────────────────────────────────────────────────────────────────────────╮",
f"│ {ModernVisualEngine.COLORS['ACCENT_LINE']}📊 HEXSTRIKE LIVE DASHBOARD{ModernVisualEngine.COLORS['PRIMARY_BORDER']} │",
f"├─────────────────────────────────────────────────────────────────────────────┤"
]
for pid, proc_info in processes.items():
status = proc_info.get('status', 'unknown')
command = proc_info.get('command', 'unknown')[:50] + "..." if len(proc_info.get('command', '')) > 50 else proc_info.get('command', 'unknown')
duration = proc_info.get('duration', 0)
status_color = ModernVisualEngine.COLORS['ACCENT_LINE'] if status == 'running' else ModernVisualEngine.COLORS['HACKER_RED']
dashboard_lines.append(
f"│ {ModernVisualEngine.COLORS['CYBER_ORANGE']}PID {pid}{ModernVisualEngine.COLORS['PRIMARY_BORDER']} | {status_color}{status}{ModernVisualEngine.COLORS['PRIMARY_BORDER']} | {ModernVisualEngine.COLORS['BRIGHT_WHITE']}{command}{ModernVisualEngine.COLORS['PRIMARY_BORDER']} │"
)
dashboard_lines.append(f"╰─────────────────────────────────────────────────────────────────────────────╯{ModernVisualEngine.COLORS['RESET']}")
return "\n".join(dashboard_lines)
@staticmethod
def format_vulnerability_card(vuln_data: Dict[str, Any]) -> str:
"""Format vulnerability as a beautiful card"""
severity = vuln_data.get('severity', 'unknown').upper()
name = vuln_data.get('name', 'Unknown Vulnerability')
description = vuln_data.get('description', 'No description available')
# Severity color mapping
severity_colors = {
'CRITICAL': ModernVisualEngine.COLORS['VULN_CRITICAL'],
'HIGH': ModernVisualEngine.COLORS['HACKER_RED'],
'MEDIUM': ModernVisualEngine.COLORS['ACCENT_GRADIENT'],
'LOW': ModernVisualEngine.COLORS['CYBER_ORANGE'],
'INFO': ModernVisualEngine.COLORS['TERMINAL_GRAY']
}
color = severity_colors.get(severity, ModernVisualEngine.COLORS['TERMINAL_GRAY'])
return f"""
{color}┌─ 🚨 VULNERABILITY DETECTED ─────────────────────────────────────┐
│ {ModernVisualEngine.COLORS['BRIGHT_WHITE']}{name:<60}{color} │
│ {ModernVisualEngine.COLORS['TERMINAL_GRAY']}Severity: {color}{severity:<52}{color} │
│ {ModernVisualEngine.COLORS['TERMINAL_GRAY']}{description[:58]:<58}{color} │
└─────────────────────────────────────────────────────────────────┘{ModernVisualEngine.COLORS['RESET']}"""
@staticmethod
def format_error_card(error_type: str, tool_name: str, error_message: str, recovery_action: str = "") -> str:
"""Format error information as a highlighted card with reddish tones"""
error_colors = {
'CRITICAL': ModernVisualEngine.COLORS['VULN_CRITICAL'],
'ERROR': ModernVisualEngine.COLORS['TOOL_FAILED'],
'TIMEOUT': ModernVisualEngine.COLORS['TOOL_TIMEOUT'],
'RECOVERY': ModernVisualEngine.COLORS['TOOL_RECOVERY'],
'WARNING': ModernVisualEngine.COLORS['WARNING']
}
color = error_colors.get(error_type.upper(), ModernVisualEngine.COLORS['ERROR'])
card = f"""
{color}┌─ 🔥 ERROR DETECTED ─────────────────────────────────────────────┐{ModernVisualEngine.COLORS['RESET']}
{color}│ {ModernVisualEngine.COLORS['BRIGHT_WHITE']}Tool: {tool_name:<55}{color} │{ModernVisualEngine.COLORS['RESET']}
{color}│ {ModernVisualEngine.COLORS['BRIGHT_WHITE']}Type: {error_type:<55}{color} │{ModernVisualEngine.COLORS['RESET']}
{color}│ {ModernVisualEngine.COLORS['BRIGHT_WHITE']}Error: {error_message[:53]:<53}{color} │{ModernVisualEngine.COLORS['RESET']}"""
if recovery_action:
card += f"""
{color}│ {ModernVisualEngine.COLORS['TOOL_RECOVERY']}Recovery: {recovery_action[:50]:<50}{color} │{ModernVisualEngine.COLORS['RESET']}"""
card += f"""
{color}└─────────────────────────────────────────────────────────────────┘{ModernVisualEngine.COLORS['RESET']}"""
return card
@staticmethod
def format_tool_status(tool_name: str, status: str, target: str = "", progress: float = 0.0) -> str:
"""Format tool execution status with enhanced highlighting"""
status_colors = {
'RUNNING': ModernVisualEngine.COLORS['TOOL_RUNNING'],
'SUCCESS': ModernVisualEngine.COLORS['TOOL_SUCCESS'],
'FAILED': ModernVisualEngine.COLORS['TOOL_FAILED'],
'TIMEOUT': ModernVisualEngine.COLORS['TOOL_TIMEOUT'],
'RECOVERY': ModernVisualEngine.COLORS['TOOL_RECOVERY']
}
color = status_colors.get(status.upper(), ModernVisualEngine.COLORS['INFO'])
# Create progress bar if progress > 0
progress_bar = ""
if progress > 0:
filled = int(20 * progress)
empty = 20 - filled
progress_bar = f" [{ModernVisualEngine.COLORS['PROGRESS_BAR']}{'█' * filled}{ModernVisualEngine.COLORS['PROGRESS_EMPTY']}{'░' * empty}{ModernVisualEngine.COLORS['RESET']}] {progress*100:.1f}%"
return f"{color}🔧 {tool_name.upper()}{ModernVisualEngine.COLORS['RESET']} | {color}{status}{ModernVisualEngine.COLORS['RESET']} | {ModernVisualEngine.COLORS['BRIGHT_WHITE']}{target}{ModernVisualEngine.COLORS['RESET']}{progress_bar}"
@staticmethod
def format_highlighted_text(text: str, highlight_type: str = "RED") -> str:
"""Format text with highlighting background"""
highlight_colors = {
'RED': ModernVisualEngine.COLORS['HIGHLIGHT_RED'],
'YELLOW': ModernVisualEngine.COLORS['HIGHLIGHT_YELLOW'],
'GREEN': ModernVisualEngine.COLORS['HIGHLIGHT_GREEN'],
'BLUE': ModernVisualEngine.COLORS['HIGHLIGHT_BLUE'],
'PURPLE': ModernVisualEngine.COLORS['HIGHLIGHT_PURPLE']
}
color = highlight_colors.get(highlight_type.upper(), ModernVisualEngine.COLORS['HIGHLIGHT_RED'])
return f"{color} {text} {ModernVisualEngine.COLORS['RESET']}"
@staticmethod
def format_vulnerability_severity(severity: str, count: int = 0) -> str:
"""Format vulnerability severity with appropriate colors"""
severity_colors = {
'CRITICAL': ModernVisualEngine.COLORS['VULN_CRITICAL'],
'HIGH': ModernVisualEngine.COLORS['VULN_HIGH'],
'MEDIUM': ModernVisualEngine.COLORS['VULN_MEDIUM'],
'LOW': ModernVisualEngine.COLORS['VULN_LOW'],
'INFO': ModernVisualEngine.COLORS['VULN_INFO']
}
color = severity_colors.get(severity.upper(), ModernVisualEngine.COLORS['INFO'])
count_text = f" ({count})" if count > 0 else ""
return f"{color}{severity.upper()}{count_text}{ModernVisualEngine.COLORS['RESET']}"
@staticmethod
def create_section_header(title: str, icon: str = "🔥", color: str = "FIRE_RED") -> str:
"""Create a section header with reddish styling"""
header_color = ModernVisualEngine.COLORS.get(color, ModernVisualEngine.COLORS['FIRE_RED'])
return f"""
{header_color}{'═' * 70}{ModernVisualEngine.COLORS['RESET']}
{header_color}{icon} {title.upper()}{ModernVisualEngine.COLORS['RESET']}
{header_color}{'═' * 70}{ModernVisualEngine.COLORS['RESET']}"""
@staticmethod
def format_command_execution(command: str, status: str, duration: float = 0.0) -> str:
"""Format command execution with enhanced styling"""
status_colors = {
'STARTING': ModernVisualEngine.COLORS['INFO'],
'RUNNING': ModernVisualEngine.COLORS['TOOL_RUNNING'],
'SUCCESS': ModernVisualEngine.COLORS['TOOL_SUCCESS'],
'FAILED': ModernVisualEngine.COLORS['TOOL_FAILED'],
'TIMEOUT': ModernVisualEngine.COLORS['TOOL_TIMEOUT']
}
color = status_colors.get(status.upper(), ModernVisualEngine.COLORS['INFO'])
duration_text = f" ({duration:.2f}s)" if duration > 0 else ""
return f"{color}▶ {command[:60]}{'...' if len(command) > 60 else ''} | {status.upper()}{duration_text}{ModernVisualEngine.COLORS['RESET']}"
# ============================================================================
# INTELLIGENT DECISION ENGINE (v6.0 ENHANCEMENT)
# ============================================================================
class TargetType(Enum):
"""Enumeration of different target types for intelligent analysis"""
WEB_APPLICATION = "web_application"
NETWORK_HOST = "network_host"
API_ENDPOINT = "api_endpoint"
CLOUD_SERVICE = "cloud_service"
MOBILE_APP = "mobile_app"
BINARY_FILE = "binary_file"
UNKNOWN = "unknown"
class TechnologyStack(Enum):
"""Common technology stacks for targeted testing"""
APACHE = "apache"
NGINX = "nginx"
IIS = "iis"
NODEJS = "nodejs"
PHP = "php"
PYTHON = "python"
JAVA = "java"
DOTNET = "dotnet"
WORDPRESS = "wordpress"
DRUPAL = "drupal"
JOOMLA = "joomla"
REACT = "react"
ANGULAR = "angular"
VUE = "vue"
UNKNOWN = "unknown"
@dataclass
class TargetProfile:
"""Comprehensive target analysis profile for intelligent decision making"""
target: str
target_type: TargetType = TargetType.UNKNOWN
ip_addresses: List[str] = field(default_factory=list)
open_ports: List[int] = field(default_factory=list)
services: Dict[int, str] = field(default_factory=dict)
technologies: List[TechnologyStack] = field(default_factory=list)
cms_type: Optional[str] = None
cloud_provider: Optional[str] = None
security_headers: Dict[str, str] = field(default_factory=dict)
ssl_info: Dict[str, Any] = field(default_factory=dict)
subdomains: List[str] = field(default_factory=list)
endpoints: List[str] = field(default_factory=list)
attack_surface_score: float = 0.0
risk_level: str = "unknown"
confidence_score: float = 0.0
def to_dict(self) -> Dict[str, Any]:
"""Convert TargetProfile to dictionary for JSON serialization"""
return {
"target": self.target,
"target_type": self.target_type.value,
"ip_addresses": self.ip_addresses,
"open_ports": self.open_ports,
"services": self.services,
"technologies": [tech.value for tech in self.technologies],
"cms_type": self.cms_type,
"cloud_provider": self.cloud_provider,
"security_headers": self.security_headers,
"ssl_info": self.ssl_info,
"subdomains": self.subdomains,
"endpoints": self.endpoints,
"attack_surface_score": self.attack_surface_score,
"risk_level": self.risk_level,
"confidence_score": self.confidence_score
}
@dataclass
class AttackStep:
"""Individual step in an attack chain"""
tool: str
parameters: Dict[str, Any]
expected_outcome: str
success_probability: float
execution_time_estimate: int # seconds
dependencies: List[str] = field(default_factory=list)
class AttackChain:
"""Represents a sequence of attacks for maximum impact"""
def __init__(self, target_profile: TargetProfile):
self.target_profile = target_profile
self.steps: List[AttackStep] = []
self.success_probability: float = 0.0
self.estimated_time: int = 0
self.required_tools: Set[str] = set()
self.risk_level: str = "unknown"
def add_step(self, step: AttackStep):
"""Add a step to the attack chain"""
self.steps.append(step)
self.required_tools.add(step.tool)
self.estimated_time += step.execution_time_estimate
def calculate_success_probability(self):
"""Calculate overall success probability of the attack chain"""
if not self.steps:
self.success_probability = 0.0
return
# Use compound probability for sequential steps
prob = 1.0
for step in self.steps:
prob *= step.success_probability
self.success_probability = prob
def to_dict(self) -> Dict[str, Any]:
"""Convert AttackChain to dictionary"""
return {
"target": self.target_profile.target,
"steps": [
{
"tool": step.tool,
"parameters": step.parameters,
"expected_outcome": step.expected_outcome,
"success_probability": step.success_probability,
"execution_time_estimate": step.execution_time_estimate,
"dependencies": step.dependencies
}
for step in self.steps
],
"success_probability": self.success_probability,
"estimated_time": self.estimated_time,
"required_tools": list(self.required_tools),
"risk_level": self.risk_level
}
class IntelligentDecisionEngine:
"""AI-powered tool selection and parameter optimization engine"""
def __init__(self):
self.tool_effectiveness = self._initialize_tool_effectiveness()
self.technology_signatures = self._initialize_technology_signatures()
self.attack_patterns = self._initialize_attack_patterns()
self._use_advanced_optimizer = True # Enable advanced optimization by default
def _initialize_tool_effectiveness(self) -> Dict[str, Dict[str, float]]:
"""Initialize tool effectiveness ratings for different target types"""
return {
TargetType.WEB_APPLICATION.value: {
"nmap": 0.8,
"gobuster": 0.9,
"nuclei": 0.95,
"nikto": 0.85,
"sqlmap": 0.9,
"ffuf": 0.9,
"feroxbuster": 0.85,
"katana": 0.88,
"httpx": 0.85,
"wpscan": 0.95, # High for WordPress sites
"burpsuite": 0.9,
"dirsearch": 0.87,
"gau": 0.82,
"waybackurls": 0.8,
"arjun": 0.9,
"paramspider": 0.85,
"x8": 0.88,
"jaeles": 0.92,
"dalfox": 0.93, # High for XSS detection
"anew": 0.7, # Utility tool
"qsreplace": 0.75, # Utility tool
"uro": 0.7 # Utility tool
},
TargetType.NETWORK_HOST.value: {
"nmap": 0.95,
"nmap-advanced": 0.97, # Enhanced Nmap with NSE scripts
"masscan": 0.92, # Enhanced with intelligent rate limiting
"rustscan": 0.9, # Ultra-fast scanning
"autorecon": 0.95, # Comprehensive automated recon
"enum4linux": 0.8,
"enum4linux-ng": 0.88, # Enhanced version
"smbmap": 0.85,
"rpcclient": 0.82,
"nbtscan": 0.75,
"arp-scan": 0.85, # Great for network discovery
"responder": 0.88, # Excellent for credential harvesting
"hydra": 0.8,
"netexec": 0.85,
"amass": 0.7
},
TargetType.API_ENDPOINT.value: {
"nuclei": 0.9,
"ffuf": 0.85,
"arjun": 0.95, # Excellent for API parameter discovery
"paramspider": 0.88,
"httpx": 0.9, # Great for API probing
"x8": 0.92, # Excellent for hidden parameters
"katana": 0.85, # Good for API endpoint discovery
"jaeles": 0.88,
"postman": 0.8
},
TargetType.CLOUD_SERVICE.value: {
"prowler": 0.95, # Excellent for AWS security assessment
"scout-suite": 0.92, # Great for multi-cloud assessment
"cloudmapper": 0.88, # Good for AWS network visualization
"pacu": 0.85, # AWS exploitation framework
"trivy": 0.9, # Excellent for container scanning
"clair": 0.85, # Good for container vulnerability analysis
"kube-hunter": 0.9, # Excellent for Kubernetes penetration testing
"kube-bench": 0.88, # Great for CIS benchmarks
"docker-bench-security": 0.85, # Good for Docker security
"falco": 0.87, # Great for runtime monitoring
"checkov": 0.9, # Excellent for IaC scanning
"terrascan": 0.88 # Great for IaC security
},
TargetType.BINARY_FILE.value: {
"ghidra": 0.95, # Excellent for comprehensive analysis
"radare2": 0.9, # Great for reverse engineering
"gdb": 0.85,
"gdb-peda": 0.92, # Enhanced debugging
"angr": 0.88, # Excellent for symbolic execution
"pwntools": 0.9, # Great for exploit development
"ropgadget": 0.85,
"ropper": 0.88, # Enhanced gadget searching
"one-gadget": 0.82, # Specific to libc
"libc-database": 0.8, # Specific to libc identification
"checksec": 0.75,
"strings": 0.7,
"objdump": 0.75,
"binwalk": 0.8,
"pwninit": 0.85 # Great for CTF setup
}
}
def _initialize_technology_signatures(self) -> Dict[str, Dict[str, List[str]]]:
"""Initialize technology detection signatures"""
return {
"headers": {
TechnologyStack.APACHE.value: ["Apache", "apache"],
TechnologyStack.NGINX.value: ["nginx", "Nginx"],
TechnologyStack.IIS.value: ["Microsoft-IIS", "IIS"],
TechnologyStack.PHP.value: ["PHP", "X-Powered-By: PHP"],
TechnologyStack.NODEJS.value: ["Express", "X-Powered-By: Express"],
TechnologyStack.PYTHON.value: ["Django", "Flask", "Werkzeug"],
TechnologyStack.JAVA.value: ["Tomcat", "JBoss", "WebLogic"],
TechnologyStack.DOTNET.value: ["ASP.NET", "X-AspNet-Version"]
},
"content": {
TechnologyStack.WORDPRESS.value: ["wp-content", "wp-includes", "WordPress"],
TechnologyStack.DRUPAL.value: ["Drupal", "drupal", "/sites/default"],
TechnologyStack.JOOMLA.value: ["Joomla", "joomla", "/administrator"],
TechnologyStack.REACT.value: ["React", "react", "__REACT_DEVTOOLS"],
TechnologyStack.ANGULAR.value: ["Angular", "angular", "ng-version"],
TechnologyStack.VUE.value: ["Vue", "vue", "__VUE__"]
},
"ports": {
TechnologyStack.APACHE.value: [80, 443, 8080, 8443],
TechnologyStack.NGINX.value: [80, 443, 8080],
TechnologyStack.IIS.value: [80, 443, 8080],
TechnologyStack.NODEJS.value: [3000, 8000, 8080, 9000]
}
}
def _initialize_attack_patterns(self) -> Dict[str, List[Dict[str, Any]]]:
"""Initialize common attack patterns for different scenarios"""
return {
"web_reconnaissance": [
{"tool": "nmap", "priority": 1, "params": {"scan_type": "-sV -sC", "ports": "80,443,8080,8443"}},
{"tool": "httpx", "priority": 2, "params": {"probe": True, "tech_detect": True}},
{"tool": "katana", "priority": 3, "params": {"depth": 3, "js_crawl": True}},
{"tool": "gau", "priority": 4, "params": {"include_subs": True}},
{"tool": "waybackurls", "priority": 5, "params": {"get_versions": False}},
{"tool": "nuclei", "priority": 6, "params": {"severity": "critical,high", "tags": "tech"}},
{"tool": "dirsearch", "priority": 7, "params": {"extensions": "php,html,js,txt", "threads": 30}},
{"tool": "gobuster", "priority": 8, "params": {"mode": "dir", "extensions": "php,html,js,txt"}}
],
"api_testing": [
{"tool": "httpx", "priority": 1, "params": {"probe": True, "tech_detect": True}},
{"tool": "arjun", "priority": 2, "params": {"method": "GET,POST", "stable": True}},
{"tool": "x8", "priority": 3, "params": {"method": "GET", "wordlist": "/usr/share/wordlists/x8/params.txt"}},
{"tool": "paramspider", "priority": 4, "params": {"level": 2}},
{"tool": "nuclei", "priority": 5, "params": {"tags": "api,graphql,jwt", "severity": "high,critical"}},
{"tool": "ffuf", "priority": 6, "params": {"mode": "parameter", "method": "POST"}}
],
"network_discovery": [
{"tool": "arp-scan", "priority": 1, "params": {"local_network": True}},
{"tool": "rustscan", "priority": 2, "params": {"ulimit": 5000, "scripts": True}},
{"tool": "nmap-advanced", "priority": 3, "params": {"scan_type": "-sS", "os_detection": True, "version_detection": True}},
{"tool": "masscan", "priority": 4, "params": {"rate": 1000, "ports": "1-65535", "banners": True}},
{"tool": "enum4linux-ng", "priority": 5, "params": {"shares": True, "users": True, "groups": True}},
{"tool": "nbtscan", "priority": 6, "params": {"verbose": True}},
{"tool": "smbmap", "priority": 7, "params": {"recursive": True}},
{"tool": "rpcclient", "priority": 8, "params": {"commands": "enumdomusers;enumdomgroups;querydominfo"}}
],
"vulnerability_assessment": [
{"tool": "nuclei", "priority": 1, "params": {"severity": "critical,high,medium", "update": True}},
{"tool": "jaeles", "priority": 2, "params": {"threads": 20, "timeout": 20}},
{"tool": "dalfox", "priority": 3, "params": {"mining_dom": True, "mining_dict": True}},
{"tool": "nikto", "priority": 4, "params": {"comprehensive": True}},
{"tool": "sqlmap", "priority": 5, "params": {"crawl": 2, "batch": True}}
],
"comprehensive_network_pentest": [
{"tool": "autorecon", "priority": 1, "params": {"port_scans": "top-1000-ports", "service_scans": "default"}},
{"tool": "rustscan", "priority": 2, "params": {"ulimit": 5000, "scripts": True}},
{"tool": "nmap-advanced", "priority": 3, "params": {"aggressive": True, "nse_scripts": "vuln,exploit"}},
{"tool": "enum4linux-ng", "priority": 4, "params": {"shares": True, "users": True, "groups": True, "policy": True}},
{"tool": "responder", "priority": 5, "params": {"wpad": True, "duration": 180}}
],
"binary_exploitation": [
{"tool": "checksec", "priority": 1, "params": {}},
{"tool": "ghidra", "priority": 2, "params": {"analysis_timeout": 300, "output_format": "xml"}},
{"tool": "ropper", "priority": 3, "params": {"gadget_type": "rop", "quality": 2}},
{"tool": "one-gadget", "priority": 4, "params": {"level": 1}},
{"tool": "pwntools", "priority": 5, "params": {"exploit_type": "local"}},
{"tool": "gdb-peda", "priority": 6, "params": {"commands": "checksec\ninfo functions\nquit"}}
],
"ctf_pwn_challenge": [
{"tool": "pwninit", "priority": 1, "params": {"template_type": "python"}},
{"tool": "checksec", "priority": 2, "params": {}},
{"tool": "ghidra", "priority": 3, "params": {"analysis_timeout": 180}},
{"tool": "ropper", "priority": 4, "params": {"gadget_type": "all", "quality": 3}},
{"tool": "angr", "priority": 5, "params": {"analysis_type": "symbolic"}},
{"tool": "one-gadget", "priority": 6, "params": {"level": 2}}
],
"aws_security_assessment": [
{"tool": "prowler", "priority": 1, "params": {"provider": "aws", "output_format": "json"}},
{"tool": "scout-suite", "priority": 2, "params": {"provider": "aws"}},
{"tool": "cloudmapper", "priority": 3, "params": {"action": "collect"}},
{"tool": "pacu", "priority": 4, "params": {"modules": "iam__enum_users_roles_policies_groups"}}
],
"kubernetes_security_assessment": [
{"tool": "kube-bench", "priority": 1, "params": {"output_format": "json"}},
{"tool": "kube-hunter", "priority": 2, "params": {"report": "json"}},
{"tool": "falco", "priority": 3, "params": {"duration": 120, "output_format": "json"}}
],
"container_security_assessment": [
{"tool": "trivy", "priority": 1, "params": {"scan_type": "image", "severity": "HIGH,CRITICAL"}},
{"tool": "clair", "priority": 2, "params": {"output_format": "json"}},
{"tool": "docker-bench-security", "priority": 3, "params": {}}
],
"iac_security_assessment": [
{"tool": "checkov", "priority": 1, "params": {"output_format": "json"}},
{"tool": "terrascan", "priority": 2, "params": {"scan_type": "all", "output_format": "json"}},
{"tool": "trivy", "priority": 3, "params": {"scan_type": "config", "severity": "HIGH,CRITICAL"}}
],
"multi_cloud_assessment": [
{"tool": "scout-suite", "priority": 1, "params": {"provider": "aws"}},
{"tool": "prowler", "priority": 2, "params": {"provider": "aws"}},
{"tool": "checkov", "priority": 3, "params": {"framework": "terraform"}},
{"tool": "terrascan", "priority": 4, "params": {"scan_type": "all"}}
],
"bug_bounty_reconnaissance": [
{"tool": "amass", "priority": 1, "params": {"mode": "enum", "passive": False}},
{"tool": "subfinder", "priority": 2, "params": {"silent": True, "all_sources": True}},
{"tool": "httpx", "priority": 3, "params": {"probe": True, "tech_detect": True, "status_code": True}},
{"tool": "katana", "priority": 4, "params": {"depth": 3, "js_crawl": True, "form_extraction": True}},
{"tool": "gau", "priority": 5, "params": {"include_subs": True}},
{"tool": "waybackurls", "priority": 6, "params": {"get_versions": False}},
{"tool": "paramspider", "priority": 7, "params": {"level": 2}},
{"tool": "arjun", "priority": 8, "params": {"method": "GET,POST", "stable": True}}
],
"bug_bounty_vulnerability_hunting": [
{"tool": "nuclei", "priority": 1, "params": {"severity": "critical,high", "tags": "rce,sqli,xss,ssrf"}},
{"tool": "dalfox", "priority": 2, "params": {"mining_dom": True, "mining_dict": True}},
{"tool": "sqlmap", "priority": 3, "params": {"batch": True, "level": 2, "risk": 2}},
{"tool": "jaeles", "priority": 4, "params": {"threads": 20, "timeout": 20}},
{"tool": "ffuf", "priority": 5, "params": {"match_codes": "200,204,301,302,307,401,403", "threads": 40}}
],
"bug_bounty_high_impact": [
{"tool": "nuclei", "priority": 1, "params": {"severity": "critical", "tags": "rce,sqli,ssrf,lfi,xxe"}},
{"tool": "sqlmap", "priority": 2, "params": {"batch": True, "level": 3, "risk": 3, "tamper": "space2comment"}},
{"tool": "jaeles", "priority": 3, "params": {"signatures": "rce,sqli,ssrf", "threads": 30}},
{"tool": "dalfox", "priority": 4, "params": {"blind": True, "mining_dom": True, "custom_payload": "alert(document.domain)"}}
]
}
def analyze_target(self, target: str) -> TargetProfile:
"""Analyze target and create comprehensive profile"""
profile = TargetProfile(target=target)
# Determine target type
profile.target_type = self._determine_target_type(target)
# Basic network analysis
if profile.target_type in [TargetType.WEB_APPLICATION, TargetType.API_ENDPOINT]:
profile.ip_addresses = self._resolve_domain(target)
# Technology detection (basic heuristics)
if profile.target_type == TargetType.WEB_APPLICATION:
profile.technologies = self._detect_technologies(target)
profile.cms_type = self._detect_cms(target)
# Calculate attack surface score
profile.attack_surface_score = self._calculate_attack_surface(profile)
# Determine risk level
profile.risk_level = self._determine_risk_level(profile)
# Set confidence score
profile.confidence_score = self._calculate_confidence(profile)
return profile
def _determine_target_type(self, target: str) -> TargetType:
"""Determine the type of target for appropriate tool selection"""
# URL patterns
if target.startswith(('http://', 'https://')):
parsed = urllib.parse.urlparse(target)
if '/api/' in parsed.path or parsed.path.endswith('/api'):
return TargetType.API_ENDPOINT
return TargetType.WEB_APPLICATION
# IP address pattern
if re.match(r'^(\d{1,3}\.){3}\d{1,3}$', target):
return TargetType.NETWORK_HOST
# Domain name pattern
if re.match(r'^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', target):
return TargetType.WEB_APPLICATION
# File patterns
if target.endswith(('.exe', '.bin', '.elf', '.so', '.dll')):
return TargetType.BINARY_FILE
# Cloud service patterns
if any(cloud in target.lower() for cloud in ['amazonaws.com', 'azure', 'googleapis.com']):
return TargetType.CLOUD_SERVICE
return TargetType.UNKNOWN
def _resolve_domain(self, target: str) -> List[str]:
"""Resolve domain to IP addresses"""
try:
if target.startswith(('http://', 'https://')):
hostname = urllib.parse.urlparse(target).hostname
else:
hostname = target
if hostname:
ip = socket.gethostbyname(hostname)
return [ip]
except Exception:
pass
return []
def _detect_technologies(self, target: str) -> List[TechnologyStack]:
"""Detect technologies using basic heuristics"""
technologies = []
# This is a simplified version - in practice, you'd make HTTP requests
# and analyze headers, content, etc.
# For now, return some common technologies based on target patterns
if 'wordpress' in target.lower() or 'wp-' in target.lower():
technologies.append(TechnologyStack.WORDPRESS)
if any(ext in target.lower() for ext in ['.php', 'php']):
technologies.append(TechnologyStack.PHP)
if any(ext in target.lower() for ext in ['.asp', '.aspx']):
technologies.append(TechnologyStack.DOTNET)
return technologies if technologies else [TechnologyStack.UNKNOWN]
def _detect_cms(self, target: str) -> Optional[str]:
"""Detect CMS type"""
target_lower = target.lower()
if 'wordpress' in target_lower or 'wp-' in target_lower:
return "WordPress"
elif 'drupal' in target_lower:
return "Drupal"
elif 'joomla' in target_lower:
return "Joomla"
return None
def _calculate_attack_surface(self, profile: TargetProfile) -> float:
"""Calculate attack surface score based on profile"""
score = 0.0
# Base score by target type
type_scores = {
TargetType.WEB_APPLICATION: 7.0,
TargetType.API_ENDPOINT: 6.0,
TargetType.NETWORK_HOST: 8.0,
TargetType.CLOUD_SERVICE: 5.0,
TargetType.BINARY_FILE: 4.0
}
score += type_scores.get(profile.target_type, 3.0)
# Add points for technologies
score += len(profile.technologies) * 0.5
# Add points for open ports
score += len(profile.open_ports) * 0.3
# Add points for subdomains
score += len(profile.subdomains) * 0.2
# CMS adds attack surface
if profile.cms_type:
score += 1.5
return min(score, 10.0) # Cap at 10.0
def _determine_risk_level(self, profile: TargetProfile) -> str:
"""Determine risk level based on attack surface"""
if profile.attack_surface_score >= 8.0:
return "critical"
elif profile.attack_surface_score >= 6.0:
return "high"
elif profile.attack_surface_score >= 4.0:
return "medium"
elif profile.attack_surface_score >= 2.0:
return "low"
else:
return "minimal"
def _calculate_confidence(self, profile: TargetProfile) -> float:
"""Calculate confidence score in the analysis"""
confidence = 0.5 # Base confidence
# Increase confidence based on available data
if profile.ip_addresses:
confidence += 0.1
if profile.technologies and profile.technologies[0] != TechnologyStack.UNKNOWN:
confidence += 0.2
if profile.cms_type:
confidence += 0.1
if profile.target_type != TargetType.UNKNOWN:
confidence += 0.1
return min(confidence, 1.0)
def select_optimal_tools(self, profile: TargetProfile, objective: str = "comprehensive") -> List[str]:
"""Select optimal tools based on target profile and objective"""
target_type = profile.target_type.value
effectiveness_map = self.tool_effectiveness.get(target_type, {})
# Get base tools for target type
base_tools = list(effectiveness_map.keys())
# Apply objective-based filtering
if objective == "quick":
# Select top 3 most effective tools
sorted_tools = sorted(base_tools, key=lambda t: effectiveness_map.get(t, 0), reverse=True)
selected_tools = sorted_tools[:3]
elif objective == "comprehensive":
# Select all tools with effectiveness > 0.7
selected_tools = [tool for tool in base_tools if effectiveness_map.get(tool, 0) > 0.7]
elif objective == "stealth":
# Select passive tools with lower detection probability
stealth_tools = ["amass", "subfinder", "httpx", "nuclei"]
selected_tools = [tool for tool in base_tools if tool in stealth_tools]
else:
selected_tools = base_tools
# Add technology-specific tools
for tech in profile.technologies:
if tech == TechnologyStack.WORDPRESS and "wpscan" not in selected_tools:
selected_tools.append("wpscan")
elif tech == TechnologyStack.PHP and "nikto" not in selected_tools:
selected_tools.append("nikto")