Repository navigation
Expand file tree
/
Copy pathcode.py
More file actions
440 lines (371 loc) · 13.3 KB
/
Copy pathcode.py
File metadata and controls
440 lines (371 loc) · 13.3 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
#!/usr/bin/env python3
# Hecho por Nocturne
import os
import re
import json
import socket
import sqlite3
import argparse
import subprocess
import sys
from pathlib import Path
from colorama import Fore, Back, Style, init
from typing import Optional, List, Dict, Any
# Inicializar colorama para Windows también
init(autoreset=True)
def list_database_entries(db_path: str = "database/scan_results.db") -> None:
try:
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("PRAGMA table_info(scans)")
columns = [column[1] for column in cursor.fetchall()]
if 'timestamp' in columns:
cursor.execute("""
SELECT id, ip,
CASE
WHEN timestamp IS NULL OR timestamp = '' THEN 'N/A'
ELSE strftime('%Y-%m-%d %H:%M:%S', timestamp)
END as formatted_date
FROM scans
ORDER BY timestamp DESC
""")
else:
cursor.execute("SELECT id, ip, 'N/A' as formatted_date FROM scans")
scans = cursor.fetchall()
if not scans:
print("No scan entries found in the database.")
return
print("\nScan history")
print("=" * 60)
for scan in scans:
print(f"ID: {scan['id']} | IP: {scan['ip']} | Date: {scan['formatted_date']}")
print("=" * 60)
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if 'conn' in locals() and conn:
conn.close()
def show_scan_details(scan_id: int, db_path: str = "database/scan_results.db") -> None:
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("""
SELECT ip, output, timestamp
FROM scans
WHERE id = ?
""", (scan_id,))
result = cursor.fetchone()
if not result:
print(f"No scan found with ID: {scan_id}")
return
ip, output, timestamp = result
print(f"\n=== Scan Details ===")
print(f"Scan ID: {scan_id}")
print(f"IP: {ip}")
print(f"Date: {timestamp}")
print("\nScan Results:")
print(output)
print("=" * 60)
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
if conn:
conn.close()
def parse_arguments():
parser = argparse.ArgumentParser(
description="Anomalisis - Network Security Scanner",
formatter_class=argparse.RawDescriptionHelpFormatter
)
scan_group = parser.add_argument_group('Scan Options')
scan_group.add_argument(
'target',
nargs='?',
help='Target IP or hostname to scan'
)
scan_group.add_argument(
'-p', '--ports',
default='1-1024',
help='Ports to scan (e.g., 80,443 or 1-1000)'
)
scan_group.add_argument(
'-o', '--output',
choices=['text', 'json'],
default='text',
help='Output format (default: text)'
)
scan_group.add_argument(
'-v', '--verbose',
action='store_true',
help='Enable verbose output'
)
db_group = parser.add_argument_group('Database Options')
db_group.add_argument(
'-d', '--database',
action='store_true',
help='List all scan history'
)
db_group.add_argument(
'--show-scan',
type=int,
metavar='SCAN_ID',
help='Show details of a specific scan by ID'
)
db_group.add_argument(
'--db-path',
default='database/scan_results.db',
help='Path to the SQLite database file'
)
compare_group = parser.add_argument_group('Comparison Options')
compare_group.add_argument(
'--compare',
nargs=2,
metavar=('SCAN_ID_1', 'SCAN_ID_2'),
help='Compare two scans by their IDs'
)
parser.add_argument(
'--version',
action='version',
version='Anomalisis 1.0'
)
return parser.parse_args()
def get_local_ip():
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect(('8.8.8.8', 80))
return s.getsockname()[0]
except Exception as e:
print(f"[!] Error al obtener la IP local: {e}")
return "127.0.0.1"
def init_db():
try:
os.makedirs("database", exist_ok=True)
db_path = os.path.abspath("database/scan_results.db")
print(f"[+] Inicializando base de datos en: {db_path}")
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS scans (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ip TEXT NOT NULL,
output TEXT NOT NULL,
ports_opened TEXT NOT NULL,
ports_closed TEXT NOT NULL,
scan_arguments TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS scan_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
scan_id INTEGER,
action TEXT NOT NULL,
details TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (scan_id) REFERENCES scans(id) ON DELETE CASCADE
)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_scans_ip ON scans(ip);
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_scans_timestamp ON scans(timestamp);
""")
conn.commit()
conn.close()
print("[+] Base de datos inicializada correctamente")
return True
except Exception as e:
print(f"[!] Error al inicializar la base de datos: {e}")
if 'conn' in locals() and conn:
conn.rollback()
conn.close()
return False
def save_scan(ip, output, scan_args=None):
print("\n[DEBUG] Iniciando save_scan")
print(f"[DEBUG] IP: {ip}")
print(f"[DEBUG] Output length: {len(output)} caracteres")
conn = None
try:
db_dir = 'database'
db_path = os.path.abspath(os.path.join(db_dir, 'scan_results.db'))
os.makedirs(db_dir, exist_ok=True)
print(f"[DEBUG] Ruta de la base de datos: {db_path}")
if not os.access(db_dir, os.W_OK):
print(f"[ERROR] No se puede escribir en el directorio: {os.path.abspath(db_dir)}")
return False
print("[DEBUG] Conectando a la base de datos...")
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
def parse_ports(output_text, state):
pattern = fr'(\d+)/tcp\s+{state}'
return [int(port) for port in re.findall(pattern, output_text)]
open_ports = parse_ports(output, 'open')
closed_ports = parse_ports(output, 'closed')
print("[DEBUG] Insertando nuevo registro...")
cursor.execute(
"""
INSERT INTO scans
(ip, output, ports_opened, ports_closed, scan_arguments)
VALUES (?, ?, ?, ?, ?)
""",
(
ip,
output,
json.dumps(open_ports),
json.dumps(closed_ports),
scan_args or ''
)
)
scan_id = cursor.lastrowid
cursor.execute(
"""
INSERT INTO scan_history
(scan_id, action, details)
VALUES (?, ?, ?)
""",
(scan_id, 'scan_completed', f'Escaneo completado para {ip} con {len(open_ports)} puertos abiertos')
)
cursor.execute("SELECT COUNT(*) FROM scans WHERE ip = ?", (ip,))
count = cursor.fetchone()[0]
print(f"[DEBUG] Total de escaneos para {ip}: {count}")
conn.commit()
print(f"[+] Escaneo guardado correctamente para IP: {ip} (ID: {scan_id})")
return True
except sqlite3.Error as e:
print(f"[!] Error de base de datos al guardar el escaneo: {e}")
if 'conn' in locals() and conn:
conn.rollback()
return False
except Exception as e:
import traceback
print(f"[!] Error inesperado al guardar el escaneo: {e}")
print(f"[DEBUG] Traceback: {traceback.format_exc()}")
if 'conn' in locals() and conn:
conn.rollback()
return False
finally:
if conn:
try:
conn.close()
except Exception as e:
print(f"[DEBUG] Error al cerrar la conexión: {e}")
def cerrar_puertos(puertos):
try:
subprocess.run(["which", "ufw"], check=True, capture_output=True)
ufw_status = subprocess.run(
["sudo", "ufw", "status"],
capture_output=True,
text=True
)
if "inactive" in ufw_status.stdout.lower():
print("[!] ufw está inactivo. Activando...")
subprocess.run(["sudo", "ufw", "enable"], check=True)
for puerto_info in puertos:
puerto = puerto_info.split('/')[0]
try:
subprocess.run(
["sudo", "ufw", "deny", f"{puerto}/tcp"],
check=True
)
print(f"[+] Regla añadida para cerrar el puerto {puerto}/tcp")
except subprocess.CalledProcessError as e:
print(f"[!] Error al cerrar el puerto {puerto}: {e}")
print("\n[+] Para ver las reglas actuales, ejecuta: sudo ufw status")
print("[!] Los cambios son permanentes. Para revertir: sudo ufw delete deny [puerto]/tcp")
except subprocess.CalledProcessError:
print("[!] ufw no está instalado. Por favor instálalo con: sudo apt install ufw")
def run_nmap(target_ip):
result = subprocess.run(
["nmap", "-sV", target_ip],
capture_output=True,
text=True
)
output_lines = result.stdout.split('\n')
open_ports = []
port_section = False
for line in output_lines:
if 'PORT' in line and 'STATE' in line and 'SERVICE' in line:
port_section = True
continue
if port_section:
if '/tcp' in line and 'open' in line:
port = line.split('/')[0].strip()
service = line.split()[-2] if len(line.split()) >= 4 else 'unknown'
port_info = f"{port}/tcp - {service}"
open_ports.append(port_info)
print(f"[+] Puerto abierto: {port_info}")
elif line.strip() == '':
port_section = False
if not open_ports:
print("[!] No se encontraron puertos abiertos")
return []
if open_ports:
print("\n" + "="*50)
cerrar = input("\n¿Desea cerrar los puertos abiertos? (s/n): ").strip().lower()
if cerrar == 's':
print("\n[!] Se requieren permisos de administrador para cerrar puertos")
print("[!] Se cerrarán los siguientes puertos:")
for puerto in open_ports:
print(f" - {puerto}")
confirmar = input("\n¿Está seguro? (s/n): ").strip().lower()
if confirmar == 's':
cerrar_puertos(open_ports)
return open_ports
def banner():
print(f'''{Fore.RED}
( (
)\ ) ) )\ ( (
((((_)( ( ( ( ( /( ((_))\ ( )\ (
)\ _ )\ )\ ) )\ )\ ' )(_)) _ ((_) )\((_) )\
(_)_\(_)_(_/( ((_) _((_)) ((_)_ | | (_)((_)(_)((_)
/ _ \ | ' \))/ _ \| ' \()/ _` || | | |(_-<| |(_-<
/_/ \_\|_||_| \___/|_|_|_| \__,_||_| |_|/__/|_|/__/
Anomalisis - Nocturne
''')
def init_scan():
local_ip = get_local_ip()
print(f"[+] IP local: {local_ip}")
init_db()
print(f"[+] Escaneando {local_ip}...\n")
open_ports = run_nmap(local_ip)
if open_ports:
save_scan(local_ip, "\n".join(open_ports))
print("[+] Resultados guardados en SQLite")
def eject():
banner()
print("\nPara detener usa ctrl + C")
init_scan()
def main():
args = parse_arguments()
try:
if args.database:
list_database_entries(args.db_path)
return 0
if args.show_scan:
show_scan_details(args.show_scan, args.db_path)
return 0
if args.compare:
scan1_id, scan2_id = args.compare
print(f"Comparing scans {scan1_id} and {scan2_id}")
# Aquí deberías implementar la función de comparación
return 0
if not args.target:
#si no hay objetivo, ejecuta el modo interactivo
os.system("clear" if os.name != 'nt' else "cls")
eject()
return 0
#si hay objetivo, ejecuta el escaneo normal
os.system("clear" if os.name != 'nt' else "cls")
print(f"Starting scan of {args.target}...")
print("Función de escaneo con argumentos aún no implementada")
except KeyboardInterrupt:
print("\nScan cancelled by user.")
return 1
except Exception as e:
print(f"An error occurred: {e}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())