- panel/: app FastAPI server-rendered (Jinja2), SOLO escucha en 127.0.0.1 - Seguridad v1: bcrypt (min 12 chars, sin credenciales default), sesión server-side con expiración y cookie HttpOnly+Secure+SameSite=Strict, rate-limit de login con bloqueo (5 fallos → 15 min), fichas de clientes cifradas en reposo con Fernet + PANEL_MASTER_KEY (env del VPS) - CLI: generar-llave (con advertencia de irrecuperabilidad y respaldo), crear-admin, servir - Estampar/desplegar reusan generador.nucleo tal cual (ficha descifrada solo en tmp 0600 durante el estampado); estado desde registry.json - panel/ y requirements-panel.txt excluidos de los paquetes de réplicas - 26 tests nuevos (auth en todas las rutas, bloqueo, cifrado en reposo, estampado real a tmp): 190 verdes en total
138 lines
4.6 KiB
Python
138 lines
4.6 KiB
Python
"""Seguridad del panel: bcrypt, cifrado Fernet de fichas, sesiones y
|
|
rate-limit del login con bloqueo tras intentos fallidos.
|
|
|
|
La llave maestra (PANEL_MASTER_KEY) vive SOLO en el entorno del VPS.
|
|
⚠️ Si se pierde, las fichas cifradas son IRRECUPERABLES: respáldala.
|
|
"""
|
|
|
|
import hashlib
|
|
import os
|
|
import secrets
|
|
import time
|
|
|
|
import bcrypt
|
|
from cryptography.fernet import Fernet, InvalidToken
|
|
|
|
from panel import db
|
|
|
|
SESSION_HORAS = int(os.getenv("PANEL_SESSION_HORAS", "8"))
|
|
|
|
# Rate-limit del login: tras MAX_FALLOS fallidos en VENTANA_S, la IP queda
|
|
# bloqueada BLOQUEO_S segundos. En memoria (el panel es un solo proceso).
|
|
MAX_FALLOS = 5
|
|
VENTANA_S = 300
|
|
BLOQUEO_S = 900
|
|
|
|
|
|
class ErrorLlaveMaestra(Exception):
|
|
pass
|
|
|
|
|
|
# ── contraseñas ─────────────────────────────────────────────────────
|
|
|
|
def hash_password(password: str) -> bytes:
|
|
return bcrypt.hashpw(password.encode(), bcrypt.gensalt())
|
|
|
|
|
|
def verificar_password(password: str, password_hash: bytes) -> bool:
|
|
try:
|
|
return bcrypt.checkpw(password.encode(), password_hash)
|
|
except (ValueError, TypeError):
|
|
return False
|
|
|
|
|
|
# ── cifrado de fichas ───────────────────────────────────────────────
|
|
|
|
def _fernet() -> Fernet:
|
|
llave = os.getenv("PANEL_MASTER_KEY", "")
|
|
if not llave:
|
|
raise ErrorLlaveMaestra(
|
|
"Falta PANEL_MASTER_KEY en el entorno. Génerala UNA sola vez con "
|
|
"`python -m panel generar-llave` y respáldala: sin ella, las "
|
|
"fichas cifradas son irrecuperables."
|
|
)
|
|
try:
|
|
return Fernet(llave.encode())
|
|
except (ValueError, TypeError) as e:
|
|
raise ErrorLlaveMaestra(f"PANEL_MASTER_KEY inválida: {e}") from e
|
|
|
|
|
|
def cifrar_ficha(ficha_yaml: str) -> bytes:
|
|
return _fernet().encrypt(ficha_yaml.encode())
|
|
|
|
|
|
def descifrar_ficha(blob: bytes) -> str:
|
|
try:
|
|
return _fernet().decrypt(blob).decode()
|
|
except InvalidToken as e:
|
|
raise ErrorLlaveMaestra(
|
|
"No se pudo descifrar la ficha: PANEL_MASTER_KEY no corresponde "
|
|
"a la llave con la que se cifró (¿llave rotada o equivocada?)."
|
|
) from e
|
|
|
|
|
|
# ── sesiones ────────────────────────────────────────────────────────
|
|
|
|
def _hash_token(token: str) -> str:
|
|
return hashlib.sha256(token.encode()).hexdigest()
|
|
|
|
|
|
def crear_sesion(usuario_id: int) -> str:
|
|
token = secrets.token_urlsafe(32)
|
|
db.guardar_sesion(_hash_token(token), usuario_id, SESSION_HORAS)
|
|
return token
|
|
|
|
|
|
def validar_sesion(token: str | None):
|
|
"""Devuelve la fila de sesión (con username) o None."""
|
|
if not token:
|
|
return None
|
|
return db.obtener_sesion(_hash_token(token))
|
|
|
|
|
|
def cerrar_sesion(token: str | None) -> None:
|
|
if token:
|
|
db.borrar_sesion(_hash_token(token))
|
|
|
|
|
|
# ── rate-limit del login ────────────────────────────────────────────
|
|
|
|
class RateLimiter:
|
|
"""Bloqueo por IP tras varios intentos fallidos.
|
|
|
|
- permitido(ip) → (True, 0) o (False, segundos_para_reintentar)
|
|
- registrar_fallo(ip): cuenta el fallo; al llegar a MAX_FALLOS bloquea.
|
|
- registrar_exito(ip): limpia el historial de esa IP.
|
|
"""
|
|
|
|
def __init__(self, max_fallos=MAX_FALLOS, ventana_s=VENTANA_S,
|
|
bloqueo_s=BLOQUEO_S, reloj=time.monotonic):
|
|
self.max_fallos = max_fallos
|
|
self.ventana_s = ventana_s
|
|
self.bloqueo_s = bloqueo_s
|
|
self._reloj = reloj
|
|
self._fallos: dict[str, list[float]] = {}
|
|
self._bloqueadas: dict[str, float] = {}
|
|
|
|
def permitido(self, ip: str) -> tuple[bool, int]:
|
|
ahora = self._reloj()
|
|
hasta = self._bloqueadas.get(ip)
|
|
if hasta is not None:
|
|
if ahora < hasta:
|
|
return False, int(hasta - ahora) + 1
|
|
del self._bloqueadas[ip]
|
|
self._fallos.pop(ip, None)
|
|
return True, 0
|
|
|
|
def registrar_fallo(self, ip: str) -> None:
|
|
ahora = self._reloj()
|
|
historial = [t for t in self._fallos.get(ip, []) if ahora - t < self.ventana_s]
|
|
historial.append(ahora)
|
|
self._fallos[ip] = historial
|
|
if len(historial) >= self.max_fallos:
|
|
self._bloqueadas[ip] = ahora + self.bloqueo_s
|
|
|
|
def registrar_exito(self, ip: str) -> None:
|
|
self._fallos.pop(ip, None)
|
|
self._bloqueadas.pop(ip, None)
|