-
Notifications
You must be signed in to change notification settings - Fork 238
Expand file tree
/
Copy pathneurosploit.py
More file actions
executable file
·2504 lines (2197 loc) · 103 KB
/
neurosploit.py
File metadata and controls
executable file
·2504 lines (2197 loc) · 103 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
"""
NeuroSploitv2 - AI-Powered Penetration Testing Framework
Author: Security Research Team
License: MIT
Version: 2.0.0
"""
import os
import sys
import argparse
import json
import re
from pathlib import Path
from typing import Dict, List, Optional
import logging
from datetime import datetime
import readline
import mistune
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('logs/neurosploit.log'),
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
from core.llm_manager import LLMManager
from core.tool_installer import ToolInstaller, run_installer_menu, PENTEST_TOOLS
from core.pentest_executor import PentestExecutor
from core.report_generator import ReportGenerator
from core.context_builder import ReconContextBuilder
from agents.base_agent import BaseAgent
from tools.recon.recon_tools import FullReconRunner
# Import AI Agents
try:
from backend.core.ai_pentest_agent import AIPentestAgent
except ImportError:
AIPentestAgent = None
try:
from backend.core.autonomous_agent import AutonomousAgent, OperationMode
from backend.core.task_library import get_task_library, Task, TaskCategory
except ImportError:
AutonomousAgent = None
OperationMode = None
get_task_library = None
Task = None
TaskCategory = None
class Completer:
def __init__(self, neurosploit):
self.neurosploit = neurosploit
self.commands = [
"help", "run_agent", "config", "list_roles", "list_profiles",
"set_profile", "set_agent", "discover_ollama", "install_tools",
"scan", "quick_scan", "recon", "full_recon", "check_tools",
"experience", "wizard", "analyze", "agent", "ai_agent",
# Autonomous agent modes
"pentest", "full_auto", "recon_only", "prompt_only", "analyze_only",
# Task library
"tasks", "task", "list_tasks", "create_task", "run_task",
# Flags (for inline completion)
"--kali", "--vpn", "--vpn-user", "--vpn-pass",
"--researcher", "--multi-agent", "--custom-prompts",
"exit", "quit"
]
self.agent_roles = list(self.neurosploit.config.get('agent_roles', {}).keys())
self.llm_profiles = list(self.neurosploit.config.get('llm', {}).get('profiles', {}).keys())
def complete(self, text, state):
line = readline.get_line_buffer()
parts = line.split()
options = []
if state == 0:
if not parts or (len(parts) == 1 and not line.endswith(' ')):
options = [c + ' ' for c in self.commands if c.startswith(text)]
elif len(parts) > 0:
if parts[0] == 'run_agent':
if len(parts) == 1 and line.endswith(' '):
options = [a + ' ' for a in self.agent_roles]
elif len(parts) == 2 and not line.endswith(' '):
options = [a + ' ' for a in self.agent_roles if a.startswith(parts[1])]
elif parts[0] == 'set_agent':
if len(parts) == 1 and line.endswith(' '):
options = [a + ' ' for a in self.agent_roles]
elif len(parts) == 2 and not line.endswith(' '):
options = [a + ' ' for a in self.agent_roles if a.startswith(parts[1])]
elif parts[0] == 'set_profile':
if len(parts) == 1 and line.endswith(' '):
options = [p + ' ' for p in self.llm_profiles]
elif len(parts) == 2 and not line.endswith(' '):
options = [p + ' ' for p in self.llm_profiles if p.startswith(parts[1])]
if state < len(options):
return options[state]
else:
return None
class NeuroSploitv2:
"""Main framework class for NeuroSploitv2"""
def __init__(self, config_path: str = "config/config.json"):
"""Initialize the framework"""
self.config_path = config_path
self.config = self._load_config()
self.session_id = datetime.now().strftime("%Y%m%d_%H%M%S")
self._setup_directories()
# LLMManager instance will be created dynamically per agent role to select specific profiles
self.llm_manager_instance: Optional[LLMManager] = None
self.selected_agent_role: Optional[str] = None
# Initialize tool installer
self.tool_installer = ToolInstaller()
logger.info(f"NeuroSploitv2 initialized - Session: {self.session_id}")
def experience_mode(self):
"""
Experience/Wizard Mode - Guided step-by-step configuration.
Navigate through options to build your pentest configuration.
"""
print("""
╔═══════════════════════════════════════════════════════════╗
║ NEUROSPLOIT - EXPERIENCE MODE (WIZARD) ║
║ Step-by-step Configuration ║
╚═══════════════════════════════════════════════════════════╝
""")
config = {
"target": None,
"context_file": None,
"llm_profile": None,
"agent_role": None,
"prompt": None,
"mode": None
}
# Step 1: Choose Mode
print("\n[STEP 1/6] Choose Operation Mode")
print("-" * 50)
print(" 1. AI Analysis - Analyze recon context with LLM (no tools)")
print(" 2. Full Scan - Run real pentest tools + AI analysis")
print(" 3. Quick Scan - Fast essential checks + AI analysis")
print(" 4. Recon Only - Run reconnaissance tools, save context")
print(" 0. Cancel")
while True:
choice = input("\n Select mode [1-4]: ").strip()
if choice == "0":
print("\n[!] Cancelled.")
return
if choice in ["1", "2", "3", "4"]:
config["mode"] = {"1": "analysis", "2": "full_scan", "3": "quick_scan", "4": "recon"}[choice]
break
print(" Invalid choice. Enter 1-4 or 0 to cancel.")
# Step 2: Target
print(f"\n[STEP 2/6] Set Target")
print("-" * 50)
target = input(" Enter target URL or domain: ").strip()
if not target:
print("\n[!] Target is required. Cancelled.")
return
config["target"] = target
# Step 3: Context File (for analysis mode)
if config["mode"] == "analysis":
print(f"\n[STEP 3/6] Context File")
print("-" * 50)
print(" Context file contains recon data collected previously.")
# List available context files
context_files = list(Path("results").glob("context_*.json"))
if context_files:
print("\n Available context files:")
for i, f in enumerate(context_files[-10:], 1):
print(f" {i}. {f.name}")
print(f" {len(context_files[-10:])+1}. Enter custom path")
choice = input(f"\n Select file [1-{len(context_files[-10:])+1}]: ").strip()
try:
idx = int(choice) - 1
if 0 <= idx < len(context_files[-10:]):
config["context_file"] = str(context_files[-10:][idx])
else:
custom = input(" Enter context file path: ").strip()
if custom:
config["context_file"] = custom
except ValueError:
custom = input(" Enter context file path: ").strip()
if custom:
config["context_file"] = custom
else:
custom = input(" Enter context file path (or press Enter to skip): ").strip()
if custom:
config["context_file"] = custom
if not config["context_file"]:
print("\n[!] Analysis mode requires a context file. Cancelled.")
return
else:
print(f"\n[STEP 3/6] Context File (Optional)")
print("-" * 50)
use_context = input(" Load existing context file? [y/N]: ").strip().lower()
if use_context == 'y':
context_files = list(Path("results").glob("context_*.json"))
if context_files:
print("\n Available context files:")
for i, f in enumerate(context_files[-10:], 1):
print(f" {i}. {f.name}")
choice = input(f"\n Select file [1-{len(context_files[-10:])}] or path: ").strip()
try:
idx = int(choice) - 1
if 0 <= idx < len(context_files[-10:]):
config["context_file"] = str(context_files[-10:][idx])
except ValueError:
if choice:
config["context_file"] = choice
# Step 4: LLM Profile
print(f"\n[STEP 4/6] LLM Profile")
print("-" * 50)
profiles = list(self.config.get('llm', {}).get('profiles', {}).keys())
default_profile = self.config.get('llm', {}).get('default_profile', '')
if profiles:
print(" Available LLM profiles:")
for i, p in enumerate(profiles, 1):
marker = " (default)" if p == default_profile else ""
print(f" {i}. {p}{marker}")
choice = input(f"\n Select profile [1-{len(profiles)}] or Enter for default: ").strip()
if choice:
try:
idx = int(choice) - 1
if 0 <= idx < len(profiles):
config["llm_profile"] = profiles[idx]
except ValueError:
pass
if not config["llm_profile"]:
config["llm_profile"] = default_profile
else:
print(" No LLM profiles configured. Using default.")
config["llm_profile"] = default_profile
# Step 5: Agent Role (optional)
print(f"\n[STEP 5/6] Agent Role (Optional)")
print("-" * 50)
roles = list(self.config.get('agent_roles', {}).keys())
if roles:
print(" Available agent roles:")
for i, r in enumerate(roles, 1):
desc = self.config['agent_roles'][r].get('description', '')[:50]
print(f" {i}. {r} - {desc}")
print(f" {len(roles)+1}. None (use default)")
choice = input(f"\n Select role [1-{len(roles)+1}]: ").strip()
try:
idx = int(choice) - 1
if 0 <= idx < len(roles):
config["agent_role"] = roles[idx]
except ValueError:
pass
# Step 6: Custom Prompt
if config["mode"] in ["analysis", "full_scan", "quick_scan"]:
print(f"\n[STEP 6/6] Custom Prompt")
print("-" * 50)
print(" Enter your instructions for the AI agent.")
print(" (What should it analyze, test, or look for?)")
print(" Press Enter twice to finish.\n")
lines = []
while True:
line = input(" > ")
if line == "" and lines and lines[-1] == "":
break
lines.append(line)
config["prompt"] = "\n".join(lines).strip()
if not config["prompt"]:
config["prompt"] = f"Perform comprehensive security assessment on {config['target']}"
else:
print(f"\n[STEP 6/6] Skipped (Recon mode)")
config["prompt"] = None
# Summary and Confirmation
print(f"\n{'='*60}")
print(" CONFIGURATION SUMMARY")
print(f"{'='*60}")
print(f" Mode: {config['mode']}")
print(f" Target: {config['target']}")
print(f" Context File: {config['context_file'] or 'None'}")
print(f" LLM Profile: {config['llm_profile']}")
print(f" Agent Role: {config['agent_role'] or 'default'}")
if config["prompt"]:
print(f" Prompt: {config['prompt'][:60]}...")
print(f"{'='*60}")
confirm = input("\n Execute with this configuration? [Y/n]: ").strip().lower()
if confirm == 'n':
print("\n[!] Cancelled.")
return
# Execute based on mode
print(f"\n[*] Starting execution...")
context = None
if config["context_file"]:
from core.context_builder import load_context_from_file
context = load_context_from_file(config["context_file"])
if context:
print(f"[+] Loaded context from: {config['context_file']}")
if config["mode"] == "recon":
self.run_full_recon(config["target"], with_ai_analysis=bool(config["agent_role"]))
elif config["mode"] == "analysis":
agent_role = config["agent_role"] or "bug_bounty_hunter"
self.execute_agent_role(
agent_role,
config["prompt"],
llm_profile_override=config["llm_profile"],
recon_context=context
)
elif config["mode"] == "full_scan":
self.execute_real_scan(
config["target"],
scan_type="full",
agent_role=config["agent_role"],
recon_context=context
)
elif config["mode"] == "quick_scan":
self.execute_real_scan(
config["target"],
scan_type="quick",
agent_role=config["agent_role"],
recon_context=context
)
print(f"\n[+] Execution complete!")
def _setup_directories(self):
"""Create necessary directories"""
dirs = ['logs', 'reports', 'data', 'custom_agents', 'results']
for d in dirs:
Path(d).mkdir(exist_ok=True)
def _load_config(self) -> Dict:
"""Load configuration from file"""
if not os.path.exists(self.config_path):
if os.path.exists("config/config-example.json"):
import shutil
shutil.copy("config/config-example.json", self.config_path)
logger.info(f"Created default configuration at {self.config_path}")
else:
logger.error("config-example.json not found. Cannot create default configuration.")
return {}
with open(self.config_path, 'r') as f:
return json.load(f)
def _initialize_llm_manager(self, agent_llm_profile: Optional[str] = None):
"""Initializes LLMManager with a specific profile or default."""
llm_config = self.config.get('llm', {})
if agent_llm_profile:
# Temporarily modify config to set the default profile for LLMManager init
original_default = llm_config.get('default_profile')
llm_config['default_profile'] = agent_llm_profile
self.llm_manager_instance = LLMManager({"llm": llm_config})
llm_config['default_profile'] = original_default # Restore original default
else:
self.llm_manager_instance = LLMManager({"llm": llm_config})
def execute_agent_role(self, agent_role_name: str, user_input: str, additional_context: Optional[Dict] = None, llm_profile_override: Optional[str] = None, recon_context: Optional[Dict] = None):
"""
Execute a specific agent role with a given input.
Args:
agent_role_name: Name of the agent role to use
user_input: The prompt/task for the agent
additional_context: Additional campaign data
llm_profile_override: Override the default LLM profile
recon_context: Pre-collected recon context (skips discovery if provided)
"""
logger.info(f"Starting execution for agent role: {agent_role_name}")
agent_roles_config = self.config.get('agent_roles', {})
role_config = agent_roles_config.get(agent_role_name)
# If role not in config, create a default config (allows dynamic roles from .md files)
if not role_config:
logger.info(f"Agent role '{agent_role_name}' not in config.json, using dynamic mode with prompt file.")
role_config = {
"enabled": True,
"tools_allowed": [],
"description": f"Dynamic agent role loaded from {agent_role_name}.md"
}
if not role_config.get('enabled', True):
logger.warning(f"Agent role '{agent_role_name}' is disabled in configuration.")
return {"warning": f"Agent role '{agent_role_name}' is disabled."}
llm_profile_name = llm_profile_override or role_config.get('llm_profile', self.config['llm']['default_profile'])
self._initialize_llm_manager(llm_profile_name)
if not self.llm_manager_instance:
logger.error("LLM Manager could not be initialized.")
return {"error": "LLM Manager initialization failed."}
# Get the prompts for the selected agent role
# Assuming agent_role_name directly maps to the .md filename
agent_prompts = self.llm_manager_instance.prompts.get("md_prompts", {}).get(agent_role_name)
if not agent_prompts:
logger.error(f"Prompts for agent role '{agent_role_name}' not found in MD library.")
return {"error": f"Prompts for agent role '{agent_role_name}' not found."}
# Instantiate and execute the BaseAgent
agent_instance = BaseAgent(agent_role_name, self.config, self.llm_manager_instance, agent_prompts)
# Execute with recon_context if provided (uses context-based flow)
results = agent_instance.execute(user_input, additional_context, recon_context=recon_context)
# Save results
campaign_results = {
"session_id": self.session_id,
"agent_role": agent_role_name,
"input": user_input,
"timestamp": datetime.now().isoformat(),
"results": results
}
self._save_results(campaign_results)
return campaign_results
def _save_results(self, results: Dict):
"""Save campaign results"""
output_file = f"results/campaign_{self.session_id}.json"
with open(output_file, 'w') as f:
json.dump(results, f, indent=4)
logger.info(f"Results saved to {output_file}")
# Generate report
self._generate_report(results)
def _generate_report(self, results: Dict):
"""Generate professional HTML report with charts and modern CSS"""
report_file = f"reports/report_{self.session_id}.html"
# Get data
llm_response = results.get('results', {}).get('llm_response', '')
if isinstance(llm_response, dict):
llm_response = json.dumps(llm_response, indent=2)
report_content = mistune.html(llm_response)
# Extract metrics from report
targets = results.get('results', {}).get('targets', [results.get('input', 'N/A')])
if isinstance(targets, str):
targets = [targets]
tools_executed = results.get('results', {}).get('tools_executed', 0)
# Count severities from report text
critical = len(re.findall(r'\[?Critical\]?', llm_response, re.IGNORECASE))
high = len(re.findall(r'\[?High\]?', llm_response, re.IGNORECASE))
medium = len(re.findall(r'\[?Medium\]?', llm_response, re.IGNORECASE))
low = len(re.findall(r'\[?Low\]?', llm_response, re.IGNORECASE))
info = len(re.findall(r'\[?Info\]?', llm_response, re.IGNORECASE))
total_vulns = critical + high + medium + low
# Risk score calculation
risk_score = min(100, (critical * 25) + (high * 15) + (medium * 8) + (low * 3))
risk_level = "Critical" if risk_score >= 70 else "High" if risk_score >= 50 else "Medium" if risk_score >= 25 else "Low"
risk_color = "#e74c3c" if risk_score >= 70 else "#e67e22" if risk_score >= 50 else "#f1c40f" if risk_score >= 25 else "#27ae60"
html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Security Assessment Report - {self.session_id}</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
<style>
:root {{
--bg-primary: #0a0e17;
--bg-secondary: #111827;
--bg-card: #1a1f2e;
--border-color: #2d3748;
--text-primary: #e2e8f0;
--text-secondary: #94a3b8;
--accent: #3b82f6;
--critical: #ef4444;
--high: #f97316;
--medium: #eab308;
--low: #22c55e;
--info: #6366f1;
}}
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: var(--bg-primary);
color: var(--text-primary);
line-height: 1.6;
}}
.container {{ max-width: 1400px; margin: 0 auto; padding: 2rem; }}
/* Header */
.header {{
background: linear-gradient(135deg, #1e3a5f 0%, #0f172a 100%);
padding: 3rem 2rem;
border-radius: 16px;
margin-bottom: 2rem;
border: 1px solid var(--border-color);
}}
.header-content {{ display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem; }}
.logo {{ font-size: 2rem; font-weight: 800; background: linear-gradient(90deg, #3b82f6, #8b5cf6); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }}
.report-meta {{ text-align: right; color: var(--text-secondary); font-size: 0.9rem; }}
/* Stats Grid */
.stats-grid {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1.5rem; margin-bottom: 2rem; }}
.stat-card {{
background: var(--bg-card);
border-radius: 12px;
padding: 1.5rem;
border: 1px solid var(--border-color);
transition: transform 0.2s, box-shadow 0.2s;
}}
.stat-card:hover {{ transform: translateY(-2px); box-shadow: 0 8px 25px rgba(0,0,0,0.3); }}
.stat-value {{ font-size: 2.5rem; font-weight: 700; }}
.stat-label {{ color: var(--text-secondary); font-size: 0.875rem; text-transform: uppercase; letter-spacing: 0.5px; }}
.stat-critical .stat-value {{ color: var(--critical); }}
.stat-high .stat-value {{ color: var(--high); }}
.stat-medium .stat-value {{ color: var(--medium); }}
.stat-low .stat-value {{ color: var(--low); }}
/* Risk Score */
.risk-section {{ display: grid; grid-template-columns: 1fr 1fr; gap: 2rem; margin-bottom: 2rem; }}
@media (max-width: 900px) {{ .risk-section {{ grid-template-columns: 1fr; }} }}
.risk-card {{
background: var(--bg-card);
border-radius: 16px;
padding: 2rem;
border: 1px solid var(--border-color);
}}
.risk-score-circle {{
width: 180px; height: 180px;
border-radius: 50%;
background: conic-gradient({risk_color} 0deg, {risk_color} {risk_score * 3.6}deg, #2d3748 {risk_score * 3.6}deg);
display: flex; align-items: center; justify-content: center;
margin: 0 auto 1rem;
}}
.risk-score-inner {{
width: 140px; height: 140px;
border-radius: 50%;
background: var(--bg-card);
display: flex; flex-direction: column; align-items: center; justify-content: center;
}}
.risk-score-value {{ font-size: 3rem; font-weight: 800; color: {risk_color}; }}
.risk-score-label {{ color: var(--text-secondary); font-size: 0.875rem; }}
.chart-container {{ height: 250px; }}
/* Targets */
.targets-list {{ display: flex; flex-wrap: wrap; gap: 0.5rem; margin-top: 1rem; }}
.target-tag {{
background: rgba(59, 130, 246, 0.2);
border: 1px solid var(--accent);
padding: 0.5rem 1rem;
border-radius: 20px;
font-size: 0.875rem;
font-family: monospace;
}}
/* Main Report */
.report-section {{
background: var(--bg-card);
border-radius: 16px;
padding: 2rem;
border: 1px solid var(--border-color);
margin-bottom: 2rem;
}}
.section-title {{
font-size: 1.5rem;
font-weight: 700;
margin-bottom: 1.5rem;
padding-bottom: 1rem;
border-bottom: 2px solid var(--accent);
display: flex;
align-items: center;
gap: 0.75rem;
}}
.section-title::before {{
content: '';
width: 4px;
height: 24px;
background: var(--accent);
border-radius: 2px;
}}
/* Vulnerability Cards */
.report-content h2 {{
background: linear-gradient(90deg, var(--bg-secondary), transparent);
padding: 1rem 1.5rem;
border-radius: 8px;
margin: 2rem 0 1rem;
border-left: 4px solid var(--accent);
font-size: 1.25rem;
}}
.report-content h2:has-text("Critical"), .report-content h2:contains("CRITICAL") {{ border-left-color: var(--critical); }}
.report-content h3 {{ color: var(--accent); margin: 1.5rem 0 0.75rem; font-size: 1.1rem; }}
.report-content table {{
width: 100%;
border-collapse: collapse;
margin: 1rem 0;
background: var(--bg-secondary);
border-radius: 8px;
overflow: hidden;
}}
.report-content th, .report-content td {{
padding: 0.75rem 1rem;
text-align: left;
border-bottom: 1px solid var(--border-color);
}}
.report-content th {{ background: rgba(59, 130, 246, 0.1); color: var(--accent); font-weight: 600; }}
.report-content pre {{
background: #0d1117;
border: 1px solid var(--border-color);
border-radius: 8px;
padding: 1rem;
overflow-x: auto;
margin: 1rem 0;
}}
.report-content code {{
font-family: 'JetBrains Mono', 'Fira Code', monospace;
font-size: 0.875rem;
}}
.report-content p {{ margin: 0.75rem 0; }}
.report-content hr {{ border: none; border-top: 1px solid var(--border-color); margin: 2rem 0; }}
.report-content ul, .report-content ol {{ margin: 1rem 0; padding-left: 1.5rem; }}
.report-content li {{ margin: 0.5rem 0; }}
/* Severity Badges */
.report-content h2 {{ position: relative; }}
/* Footer */
.footer {{
text-align: center;
padding: 2rem;
color: var(--text-secondary);
font-size: 0.875rem;
border-top: 1px solid var(--border-color);
margin-top: 3rem;
}}
/* OHVR Structure */
.ohvr-section {{
margin: 1rem 0;
padding: 1rem;
background: rgba(0,0,0,0.2);
border-radius: 8px;
}}
.ohvr-section h5 {{
color: var(--accent);
margin-bottom: 0.5rem;
text-transform: uppercase;
font-size: 0.8rem;
letter-spacing: 1px;
}}
.screenshot-grid {{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1rem;
margin: 1rem 0;
}}
.screenshot-card {{
border: 1px solid var(--border-color);
border-radius: 8px;
overflow: hidden;
}}
.screenshot-card img {{
width: 100%;
height: auto;
display: block;
}}
.screenshot-caption {{
padding: 0.5rem;
font-size: 0.8rem;
color: var(--text-secondary);
text-align: center;
}}
/* Print Styles */
@media print {{
body {{ background: white; color: black; }}
.stat-card, .risk-card, .report-section {{ border: 1px solid #ddd; }}
}}
</style>
</head>
<body>
<div class="container">
<div class="header">
<div class="header-content">
<div>
<div class="logo">NeuroSploit</div>
<p style="color: var(--text-secondary); margin-top: 0.5rem;">AI-Powered Security Assessment Report</p>
</div>
<div class="report-meta">
<div><strong>Report ID:</strong> {self.session_id}</div>
<div><strong>Date:</strong> {datetime.now().strftime('%Y-%m-%d %H:%M')}</div>
<div><strong>Agent:</strong> {results.get('agent_role', 'Security Analyst')}</div>
</div>
</div>
<div class="targets-list">
{''.join(f'<span class="target-tag">{t}</span>' for t in targets[:5])}
</div>
</div>
<div class="stats-grid">
<div class="stat-card stat-critical">
<div class="stat-value">{critical}</div>
<div class="stat-label">Critical</div>
</div>
<div class="stat-card stat-high">
<div class="stat-value">{high}</div>
<div class="stat-label">High</div>
</div>
<div class="stat-card stat-medium">
<div class="stat-value">{medium}</div>
<div class="stat-label">Medium</div>
</div>
<div class="stat-card stat-low">
<div class="stat-value">{low}</div>
<div class="stat-label">Low</div>
</div>
<div class="stat-card">
<div class="stat-value" style="color: var(--accent);">{tools_executed}</div>
<div class="stat-label">Tests Run</div>
</div>
</div>
<div class="risk-section">
<div class="risk-card">
<h3 style="text-align: center; margin-bottom: 1rem; color: var(--text-secondary);">Risk Score</h3>
<div class="risk-score-circle">
<div class="risk-score-inner">
<div class="risk-score-value">{risk_score}</div>
<div class="risk-score-label">{risk_level}</div>
</div>
</div>
</div>
<div class="risk-card">
<h3 style="margin-bottom: 1rem; color: var(--text-secondary);">Severity Distribution</h3>
<div class="chart-container">
<canvas id="severityChart"></canvas>
</div>
</div>
</div>
<div class="report-section">
<div class="section-title">Vulnerability Report</div>
<div class="report-content">
{report_content}
</div>
</div>
<div class="footer">
<p>Generated by <strong>NeuroSploit</strong> - AI-Powered Penetration Testing Framework</p>
<p style="margin-top: 0.5rem;">Confidential - For authorized personnel only</p>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script>
hljs.highlightAll();
// Severity Chart
const ctx = document.getElementById('severityChart').getContext('2d');
new Chart(ctx, {{
type: 'doughnut',
data: {{
labels: ['Critical', 'High', 'Medium', 'Low', 'Info'],
datasets: [{{
data: [{critical}, {high}, {medium}, {low}, {info}],
backgroundColor: ['#ef4444', '#f97316', '#eab308', '#22c55e', '#6366f1'],
borderWidth: 0,
hoverOffset: 10
}}]
}},
options: {{
responsive: true,
maintainAspectRatio: false,
plugins: {{
legend: {{
position: 'right',
labels: {{ color: '#94a3b8', padding: 15, font: {{ size: 12 }} }}
}}
}},
cutout: '60%'
}}
}});
</script>
</body>
</html>"""
with open(report_file, 'w') as f:
f.write(html)
logger.info(f"Report generated: {report_file}")
def execute_real_scan(self, target: str, scan_type: str = "full", agent_role: str = None, recon_context: Dict = None) -> Dict:
"""
Execute a real penetration test with actual tools and generate professional report.
Args:
target: The target URL or IP to scan
scan_type: "full" for comprehensive scan, "quick" for essential checks
agent_role: Optional agent role for AI analysis of results
"""
print(f"\n{'='*70}")
print(" NeuroSploitv2 - Real Penetration Test Execution")
print(f"{'='*70}")
print(f"\n[*] Target: {target}")
print(f"[*] Scan Type: {scan_type}")
print(f"[*] Session ID: {self.session_id}\n")
# Check for required tools
print("[*] Checking required tools...")
missing_tools = []
essential_tools = ["nmap", "curl"]
for tool in essential_tools:
installed, path = self.tool_installer.check_tool_installed(tool)
if not installed:
missing_tools.append(tool)
print(f" [-] {tool}: NOT INSTALLED")
else:
print(f" [+] {tool}: {path}")
if missing_tools:
print(f"\n[!] Missing required tools: {', '.join(missing_tools)}")
print("[!] Run 'install_tools' to install required tools.")
return {"error": f"Missing tools: {missing_tools}"}
# Execute the scan
executor = PentestExecutor(target, self.config, recon_context=recon_context)
if recon_context:
print(f"[+] Using recon context with {recon_context.get('attack_surface', {}).get('total_subdomains', 0)} subdomains, {recon_context.get('attack_surface', {}).get('live_hosts', 0)} live hosts")
if scan_type == "quick":
scan_result = executor.run_quick_scan()
else:
scan_result = executor.run_full_scan()
# Get results as dictionary
results_dict = executor.to_dict()
# Get AI analysis if agent role specified
llm_analysis = ""
if agent_role:
print(f"\n[*] Running AI analysis with {agent_role}...")
llm_profile = self.config.get('agent_roles', {}).get(agent_role, {}).get('llm_profile')
self._initialize_llm_manager(llm_profile)
if self.llm_manager_instance:
agent_prompts = self.llm_manager_instance.prompts.get("md_prompts", {}).get(agent_role, {})
if agent_prompts:
agent = BaseAgent(agent_role, self.config, self.llm_manager_instance, agent_prompts)
analysis_input = f"""
Analyze the following penetration test results and provide a detailed security assessment:
Target: {target}
Scan Type: {scan_type}
SCAN RESULTS:
{json.dumps(results_dict, indent=2)}
Provide:
1. Executive summary of findings
2. Risk assessment
3. Detailed analysis of each vulnerability
4. Prioritized remediation recommendations
5. Additional attack vectors to explore
"""
analysis_result = agent.execute(analysis_input, results_dict)
llm_analysis = analysis_result.get("llm_response", "")
# Generate professional report
print("\n[*] Generating professional report...")
report_gen = ReportGenerator(results_dict, llm_analysis)
html_report = report_gen.save_report("reports")
json_report = report_gen.save_json_report("results")
print(f"\n{'='*70}")
print("[+] Scan Complete!")
print(f" - Vulnerabilities Found: {len(results_dict.get('vulnerabilities', []))}")
print(f" - HTML Report: {html_report}")
print(f" - JSON Results: {json_report}")
print(f"{'='*70}\n")
return {
"session_id": self.session_id,
"target": target,
"scan_type": scan_type,
"results": results_dict,
"html_report": html_report,
"json_report": json_report
}
def run_full_recon(self, target: str, with_ai_analysis: bool = True) -> Dict:
"""
Run full advanced recon and consolidate all outputs.
This command runs all recon tools:
- Subdomain enumeration (subfinder, amass, assetfinder)
- HTTP probing (httpx, httprobe)
- URL collection (gau, waybackurls, waymore)
- Web crawling (katana, gospider)
- Port scanning (naabu, nmap)
- DNS enumeration
- Vulnerability scanning (nuclei)
All results are consolidated into a single context file
that will be used by the LLM to enhance testing.
"""
print(f"\n{'='*70}")
print(" NEUROSPLOIT - FULL ADVANCED RECON")
print(f"{'='*70}")
print(f"\n[*] Target: {target}")
print(f"[*] Session ID: {self.session_id}")
print(f"[*] With AI analysis: {with_ai_analysis}\n")
# Execute full recon
recon_runner = FullReconRunner(self.config)
# Determine target type
target_type = "url" if target.startswith(('http://', 'https://')) else "domain"
recon_results = recon_runner.run(target, target_type)
# If requested, run AI analysis
llm_analysis = ""
if with_ai_analysis and self.selected_agent_role:
print(f"\n[*] Running AI analysis with {self.selected_agent_role}...")
llm_profile = self.config.get('agent_roles', {}).get(self.selected_agent_role, {}).get('llm_profile')
self._initialize_llm_manager(llm_profile)
if self.llm_manager_instance:
agent_prompts = self.llm_manager_instance.prompts.get("md_prompts", {}).get(self.selected_agent_role, {})
if agent_prompts:
agent = BaseAgent(self.selected_agent_role, self.config, self.llm_manager_instance, agent_prompts)
analysis_prompt = f"""
Analise o seguinte contexto de reconhecimento e identifique:
1. Vetores de ataque mais promissores
2. Vulnerabilidades potenciais baseadas nas tecnologias detectadas
3. Endpoints prioritarios para teste
4. Recomendacoes de proximos passos para o pentest
CONTEXTO DE RECON:
{recon_results.get('context_text', '')}
"""
analysis_result = agent.execute(analysis_prompt, recon_results.get('context', {}))
llm_analysis = analysis_result.get("llm_response", "")
# Generate report if vulnerabilities found
context = recon_results.get('context', {})
vulns = context.get('vulnerabilities', {}).get('all', [])
if vulns or llm_analysis:
print("\n[*] Generating report...")
from core.report_generator import ReportGenerator
report_data = {
"target": target,
"scan_started": datetime.now().isoformat(),
"scan_completed": datetime.now().isoformat(),
"attack_surface": context.get('attack_surface', {}),
"vulnerabilities": vulns,
"technologies": context.get('data', {}).get('technologies', []),
"open_ports": context.get('data', {}).get('open_ports', [])
}
report_gen = ReportGenerator(report_data, llm_analysis)
html_report = report_gen.save_report("reports")
print(f"[+] HTML Report: {html_report}")
print(f"\n{'='*70}")