-
Notifications
You must be signed in to change notification settings - Fork 811
Expand file tree
/
Copy pathdb.py
More file actions
351 lines (288 loc) · 11.4 KB
/
Copy pathdb.py
File metadata and controls
351 lines (288 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#!/usr/bin/env python3
"""
METATRON - db.py
MariaDB connection + all read/write/edit/delete operations
Database: metatron
"""
import mysql.connector
from datetime import datetime
# ─────────────────────────────────────────────
# CONNECTION
# ─────────────────────────────────────────────
def get_connection():
"""Returns a MariaDB connection. No password (local setup)."""
return mysql.connector.connect(
host="localhost",
user="metatron",
password="123",
database="metatron"
)
# ─────────────────────────────────────────────
# WRITE FUNCTIONS
# ─────────────────────────────────────────────
def create_session(target: str) -> int:
"""Insert new row into history. Returns sl_no."""
conn = get_connection()
c = conn.cursor()
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
c.execute(
"INSERT INTO history (target, scan_date, status) VALUES (%s, %s, %s)",
(target, now, "active")
)
conn.commit()
sl_no = c.lastrowid
conn.close()
return sl_no
def save_vulnerability(sl_no: int, vuln_name: str, severity: str,
port: str, service: str, description: str) -> int:
"""Insert a vulnerability. Returns its id."""
conn = get_connection()
c = conn.cursor()
c.execute("""
INSERT INTO vulnerabilities (sl_no, vuln_name, severity, port, service, description)
VALUES (%s, %s, %s, %s, %s, %s)
""", (sl_no, vuln_name, severity, port, service, description))
conn.commit()
vuln_id = c.lastrowid
conn.close()
return vuln_id
def save_fix(sl_no: int, vuln_id: int, fix_text: str, source: str = "ai"):
"""Insert a fix linked to a vulnerability."""
conn = get_connection()
c = conn.cursor()
c.execute("""
INSERT INTO fixes (sl_no, vuln_id, fix_text, source)
VALUES (%s, %s, %s, %s)
""", (sl_no, vuln_id, fix_text, source))
conn.commit()
conn.close()
def save_exploit(sl_no, exploit_name, tool_used, payload, result, notes):
conn = get_connection()
c = conn.cursor()
c.execute("""
INSERT INTO exploits_attempted
(sl_no, exploit_name, tool_used, payload, result, notes)
VALUES (%s, %s, %s, %s, %s, %s)
""", (
sl_no,
str(exploit_name or "")[:1000],
str(tool_used or "")[:500],
str(payload or ""),
str(result or "")[:2000],
str(notes or "")
))
conn.commit()
conn.close()
def save_summary(sl_no: int, raw_scan: str, ai_analysis: str, risk_level: str):
"""Insert the full session summary."""
conn = get_connection()
c = conn.cursor()
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
c.execute("""
INSERT INTO summary (sl_no, raw_scan, ai_analysis, risk_level, generated_at)
VALUES (%s, %s, %s, %s, %s)
""", (sl_no, raw_scan, ai_analysis, risk_level, now))
conn.commit()
conn.close()
# ─────────────────────────────────────────────
# READ FUNCTIONS
# ─────────────────────────────────────────────
def get_all_history():
"""Return all rows from history ordered by newest first."""
conn = get_connection()
c = conn.cursor()
c.execute("SELECT sl_no, target, scan_date, status FROM history ORDER BY sl_no DESC")
rows = c.fetchall()
conn.close()
return rows
def get_session(sl_no: int) -> dict:
"""Return everything linked to a sl_no across all tables."""
conn = get_connection()
c = conn.cursor()
c.execute("SELECT * FROM history WHERE sl_no = %s", (sl_no,))
history = c.fetchone()
c.execute("SELECT * FROM vulnerabilities WHERE sl_no = %s", (sl_no,))
vulns = c.fetchall()
c.execute("SELECT * FROM fixes WHERE sl_no = %s", (sl_no,))
fixes = c.fetchall()
c.execute("SELECT * FROM exploits_attempted WHERE sl_no = %s", (sl_no,))
exploits = c.fetchall()
c.execute("SELECT * FROM summary WHERE sl_no = %s", (sl_no,))
summary = c.fetchone()
conn.close()
return {
"history": history,
"vulns": vulns,
"fixes": fixes,
"exploits": exploits,
"summary": summary
}
def get_vulnerabilities(sl_no: int):
conn = get_connection()
c = conn.cursor()
c.execute("SELECT * FROM vulnerabilities WHERE sl_no = %s", (sl_no,))
rows = c.fetchall()
conn.close()
return rows
def get_fixes(sl_no: int):
conn = get_connection()
c = conn.cursor()
c.execute("SELECT * FROM fixes WHERE sl_no = %s", (sl_no,))
rows = c.fetchall()
conn.close()
return rows
def get_exploits(sl_no: int):
conn = get_connection()
c = conn.cursor()
c.execute("SELECT * FROM exploits_attempted WHERE sl_no = %s", (sl_no,))
rows = c.fetchall()
conn.close()
return rows
# ─────────────────────────────────────────────
# EDIT FUNCTIONS
# ─────────────────────────────────────────────
def edit_vulnerability(vuln_id: int, field: str, value: str):
"""Edit a single field in vulnerabilities by id."""
allowed = {"vuln_name", "severity", "port", "service", "description"}
if field not in allowed:
print(f"[!] Invalid field: {field}. Allowed: {allowed}")
return
conn = get_connection()
c = conn.cursor()
c.execute(
f"UPDATE vulnerabilities SET {field} = %s WHERE id = %s",
(value, vuln_id)
)
conn.commit()
conn.close()
print(f"[+] vulnerabilities.{field} updated for id={vuln_id}")
def edit_fix(fix_id: int, fix_text: str):
"""Edit the fix_text of a fix by id."""
conn = get_connection()
c = conn.cursor()
c.execute("UPDATE fixes SET fix_text = %s WHERE id = %s", (fix_text, fix_id))
conn.commit()
conn.close()
print(f"[+] fix id={fix_id} updated.")
def edit_exploit(exploit_id: int, field: str, value: str):
"""Edit a single field in exploits_attempted by id."""
allowed = {"exploit_name", "tool_used", "payload", "result", "notes"}
if field not in allowed:
print(f"[!] Invalid field: {field}. Allowed: {allowed}")
return
conn = get_connection()
c = conn.cursor()
c.execute(
f"UPDATE exploits_attempted SET {field} = %s WHERE id = %s",
(value, exploit_id)
)
conn.commit()
conn.close()
print(f"[+] exploits_attempted.{field} updated for id={exploit_id}")
def edit_summary_risk(sl_no: int, risk_level: str):
"""Update the risk level on a summary."""
conn = get_connection()
c = conn.cursor()
c.execute("UPDATE summary SET risk_level = %s WHERE sl_no = %s", (risk_level, sl_no))
conn.commit()
conn.close()
print(f"[+] Summary risk_level updated for SL#{sl_no}")
# ─────────────────────────────────────────────
# DELETE FUNCTIONS
# ─────────────────────────────────────────────
def delete_vulnerability(vuln_id: int):
"""Delete a single vulnerability and its linked fixes."""
conn = get_connection()
c = conn.cursor()
c.execute("DELETE FROM fixes WHERE vuln_id = %s", (vuln_id,))
c.execute("DELETE FROM vulnerabilities WHERE id = %s", (vuln_id,))
conn.commit()
conn.close()
print(f"[+] Vulnerability id={vuln_id} and its fixes deleted.")
def delete_exploit(exploit_id: int):
"""Delete a single exploit attempt."""
conn = get_connection()
c = conn.cursor()
c.execute("DELETE FROM exploits_attempted WHERE id = %s", (exploit_id,))
conn.commit()
conn.close()
print(f"[+] Exploit id={exploit_id} deleted.")
def delete_fix(fix_id: int):
"""Delete a single fix."""
conn = get_connection()
c = conn.cursor()
c.execute("DELETE FROM fixes WHERE id = %s", (fix_id,))
conn.commit()
conn.close()
print(f"[+] Fix id={fix_id} deleted.")
def delete_full_session(sl_no: int):
"""
Wipe everything linked to a sl_no across all 5 tables.
Order matters — delete children before parent (FK constraints).
"""
conn = get_connection()
c = conn.cursor()
c.execute("DELETE FROM fixes WHERE sl_no = %s", (sl_no,))
c.execute("DELETE FROM exploits_attempted WHERE sl_no = %s", (sl_no,))
c.execute("DELETE FROM vulnerabilities WHERE sl_no = %s", (sl_no,))
c.execute("DELETE FROM summary WHERE sl_no = %s", (sl_no,))
c.execute("DELETE FROM history WHERE sl_no = %s", (sl_no,))
conn.commit()
conn.close()
print(f"[+] Full session SL#{sl_no} deleted from all tables.")
# ─────────────────────────────────────────────
# DISPLAY HELPERS
# ─────────────────────────────────────────────
def print_history(rows):
print("\n" + "─"*65)
print(f"{'SL#':<6} {'TARGET':<28} {'DATE':<22} {'STATUS'}")
print("─"*65)
for row in rows:
print(f"{row[0]:<6} {row[1]:<28} {str(row[2]):<22} {row[3]}")
print()
def print_session(data: dict):
h = data["history"]
print(f"\n{'═'*60}")
print(f" SL# {h[0]} | Target: {h[1]} | {h[2]} | {h[3]}")
print(f"{'═'*60}")
print("\n[ VULNERABILITIES ]")
if data["vulns"]:
for v in data["vulns"]:
print(f" id={v[0]} | {v[2]} | Severity: {v[3]} | Port: {v[4]} | Service: {v[5]}")
print(f" {v[6]}")
else:
print(" None recorded.")
print("\n[ FIXES ]")
if data["fixes"]:
for f in data["fixes"]:
print(f" id={f[0]} | vuln_id={f[2]} | [{f[4]}] {f[3]}")
else:
print(" None recorded.")
print("\n[ EXPLOITS ATTEMPTED ]")
if data["exploits"]:
for e in data["exploits"]:
print(f" id={e[0]} | {e[2]} | Tool: {e[3]} | Result: {e[5]}")
print(f" Payload: {e[4]}")
print(f" Notes: {e[6]}")
else:
print(" None recorded.")
print("\n[ SUMMARY ]")
if data["summary"]:
s = data["summary"]
print(f" Risk Level : {s[4]}")
print(f" Generated : {s[5]}")
print(f"\n AI Analysis:\n {s[3][:500]}{'...' if len(str(s[3])) > 500 else ''}")
else:
print(" None recorded.")
print()
# ─────────────────────────────────────────────
# QUICK CONNECTION TEST
# ─────────────────────────────────────────────
if __name__ == "__main__":
try:
conn = get_connection()
print("[+] MariaDB connection successful.")
print("[+] Database: metatron")
conn.close()
except Exception as e:
print(f"[!] Connection failed: {e}")