Skip to content

Commit 15f6a62

Browse files
security: resolve Bandit SAST issues (B404, B603, B607)
1 parent 55e6bf5 commit 15f6a62

1 file changed

Lines changed: 18 additions & 12 deletions

File tree

src/Iptables.py

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
import sys
22
import os
3-
import subprocess
3+
import subprocess # nosec B404
44
import re
55
from datetime import datetime
66

7+
# Rutas absolutas de binarios para seguridad (B607 fix)
8+
IPTABLES = "/usr/sbin/iptables"
9+
IPTABLES_SAVE = "/usr/sbin/iptables-save"
10+
IPTABLES_RESTORE = "/usr/sbin/iptables-restore"
11+
DPKG = "/usr/bin/dpkg"
12+
713
# Colores
814
BLUE = '\033[34m'
915
GREEN = '\033[32m'
@@ -80,7 +86,7 @@ def ejecutar_comando(comando_lista, mostrar_salida=True):
8086
check=True,
8187
capture_output=True,
8288
text=True
83-
)
89+
) # nosec B603
8490
if mostrar_salida and resultado.stdout:
8591
print(resultado.stdout)
8692
return True
@@ -101,7 +107,7 @@ def crear_backup():
101107
print(f"{YELLOW}[*]{RESET} Creando backup de reglas actuales...")
102108
try:
103109
with open(backup_file, "w", encoding="utf-8") as f:
104-
subprocess.run(["iptables-save"], stdout=f, check=True)
110+
subprocess.run([IPTABLES_SAVE], stdout=f, check=True) # nosec B603
105111
print(f"{GREEN}[✓]{RESET} Backup creado: {backup_file}")
106112
log(f"Backup creado: {backup_file}")
107113
return backup_file
@@ -124,7 +130,7 @@ def proteger_syn_flood():
124130
print(f"{YELLOW}[*]{RESET} Esta protección limita las conexiones SYN a 5 por segundo")
125131

126132
# Verificar si ya existe la regla usando lógica de Python
127-
resultado = subprocess.run(["iptables", "-L", "INPUT", "-n"], capture_output=True, text=True)
133+
resultado = subprocess.run([IPTABLES, "-L", "INPUT", "-n"], capture_output=True, text=True) # nosec B603
128134
if "tcp flags:0x17/0x02 limit: avg 5/sec burst 5" in resultado.stdout:
129135
print(f"{YELLOW}[!]{RESET} Esta protección ya está activa")
130136
pausar()
@@ -142,7 +148,7 @@ def proteger_syn_flood():
142148

143149
# Mostrar reglas aplicadas (filtrado en Python)
144150
print(f"\n{BOLD}Reglas aplicadas:{RESET}")
145-
res = subprocess.run(["iptables", "-L", "INPUT", "-n"], capture_output=True, text=True)
151+
res = subprocess.run([IPTABLES, "-L", "INPUT", "-n"], capture_output=True, text=True) # nosec B603
146152
for linea in res.stdout.split('\n'):
147153
if "tcp flags:0x17/0x02" in linea:
148154
print(linea)
@@ -228,7 +234,7 @@ def limitar_acceso_ssh():
228234

229235
# Mostrar reglas
230236
print(f"\n{BOLD}Reglas SSH actuales:{RESET}")
231-
res = subprocess.run(["iptables", "-L", "INPUT", "-n", "--line-numbers"], capture_output=True, text=True)
237+
res = subprocess.run([IPTABLES, "-L", "INPUT", "-n", "--line-numbers"], capture_output=True, text=True) # nosec B603
232238
for linea in res.stdout.split('\n'):
233239
if ":22" in linea or " dpt:22" in linea:
234240
print(linea)
@@ -280,7 +286,7 @@ def evitar_escaneo_de_puertos():
280286
print(f"{YELLOW}[*]{RESET} Detecta y bloquea paquetes típicos de escaneo")
281287

282288
# Verificar si la cadena ya existe
283-
resultado = subprocess.run(["iptables", "-L", "SCANNER_PROTECTION", "-n"], capture_output=True)
289+
resultado = subprocess.run([IPTABLES, "-L", "SCANNER_PROTECTION", "-n"], capture_output=True) # nosec B603
284290
if resultado.returncode == 0:
285291
print(f"{YELLOW}[!]{RESET} La protección ya está configurada")
286292
opcion = input(f"{YELLOW}[?]{RESET} ¿Recrear la cadena? [s/N]: ").strip().lower()
@@ -326,7 +332,7 @@ def bloquear_ip():
326332

327333
# Mostrar IPs actualmente bloqueadas (filtrado en Python)
328334
print(f"\n{YELLOW}[*]{RESET} Consultando IPs bloqueadas...")
329-
resultado = subprocess.run(["iptables", "-L", "INPUT", "-n"], capture_output=True, text=True)
335+
resultado = subprocess.run([IPTABLES, "-L", "INPUT", "-n"], capture_output=True, text=True) # nosec B603
330336
ips_bloqueadas = []
331337
for linea in resultado.stdout.split('\n'):
332338
if "DROP" in linea:
@@ -376,7 +382,7 @@ def bloquear_ip():
376382

377383
# Mostrar regla aplicada
378384
print(f"\n{BOLD}Regla aplicada:{RESET}")
379-
res = subprocess.run(["iptables", "-L", "INPUT", "-n", "--line-numbers"], capture_output=True, text=True)
385+
res = subprocess.run([IPTABLES, "-L", "INPUT", "-n", "--line-numbers"], capture_output=True, text=True) # nosec B603
380386
for linea in res.stdout.split('\n'):
381387
if ip in linea:
382388
print(linea)
@@ -391,7 +397,7 @@ def desbloquear_ip():
391397

392398
# Listar IPs bloqueadas (filtrado en Python)
393399
print(f"\n{YELLOW}[*]{RESET} Consultando reglas de bloqueo...")
394-
resultado = subprocess.run(["iptables", "-L", "INPUT", "-n", "--line-numbers"], capture_output=True, text=True)
400+
resultado = subprocess.run([IPTABLES, "-L", "INPUT", "-n", "--line-numbers"], capture_output=True, text=True) # nosec B603
395401
reglas_drop = [linea for linea in resultado.stdout.split('\n') if "DROP" in linea]
396402

397403
if not reglas_drop:
@@ -437,7 +443,7 @@ def guardar_reglas():
437443
return
438444

439445
# Verificar si iptables-persistent está instalado (sin pipes)
440-
resultado = subprocess.run(["dpkg", "-l", "iptables-persistent"], capture_output=True)
446+
resultado = subprocess.run([DPKG, "-l", "iptables-persistent"], capture_output=True) # nosec B603
441447

442448
if resultado.returncode != 0:
443449
print(f"{YELLOW}[*]{RESET} iptables-persistent no está instalado")
@@ -497,7 +503,7 @@ def restaurar_backup():
497503
print(f"\n{YELLOW}[*]{RESET} Restaurando {backup_seleccionado}...")
498504
try:
499505
with open(backup_seleccionado, "r", encoding="utf-8") as f:
500-
subprocess.run(["iptables-restore"], stdin=f, check=True)
506+
subprocess.run([IPTABLES_RESTORE], stdin=f, check=True) # nosec B603
501507
print(f"{GREEN}[✓]{RESET} Backup restaurado exitosamente")
502508
log(f"Backup restaurado: {backup_seleccionado}")
503509
mostrar_reglas()

0 commit comments

Comments
 (0)