GuardianUnivalle-Benito-Yucra 0.1.11__tar.gz → 0.1.13__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of GuardianUnivalle-Benito-Yucra might be problematic. Click here for more details.
- guardianunivalle_benito_yucra-0.1.13/GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py +169 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra.egg-info/PKG-INFO +1 -1
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/PKG-INFO +1 -1
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/pyproject.toml +1 -1
- guardianunivalle_benito_yucra-0.1.11/GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py +0 -183
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra/__init__.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra/auditoria/registro_auditoria.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra/criptografia/cifrado_aead.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra/criptografia/intercambio_claves.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra/criptografia/kdf.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra/detectores/detector_csrf.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra/detectores/detector_dos.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra/detectores/detector_keylogger.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra/detectores/detector_xss.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra/middleware_web/middleware_web.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra/mitigacion/limitador_peticion.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra/mitigacion/lista_bloqueo.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra/puntuacion/puntuacion_amenaza.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra/utilidades.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra.egg-info/SOURCES.txt +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra.egg-info/dependency_links.txt +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra.egg-info/requires.txt +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/GuardianUnivalle_Benito_Yucra.egg-info/top_level.txt +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/LICENSE +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/README.md +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/setup.cfg +0 -0
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
# detector_sql.py
|
|
2
|
+
# =====================================================
|
|
3
|
+
# Importaciones de librerías
|
|
4
|
+
# =====================================================
|
|
5
|
+
|
|
6
|
+
# Módulo para trabajar con expresiones regulares (regex)
|
|
7
|
+
# Permite buscar patrones de texto dentro de cadenas.
|
|
8
|
+
import re
|
|
9
|
+
|
|
10
|
+
# Módulo para trabajar con datos en formato JSON
|
|
11
|
+
# Permite convertir cadenas JSON a objetos Python y viceversa.
|
|
12
|
+
import json
|
|
13
|
+
|
|
14
|
+
# Módulo para manejo de logs (registro de eventos)
|
|
15
|
+
# Permite registrar alertas, información o errores en la consola o en archivos.
|
|
16
|
+
import logging
|
|
17
|
+
|
|
18
|
+
# Tipado estático
|
|
19
|
+
# Permite indicar tipos de datos de variables o valores de retorno en funciones.
|
|
20
|
+
from typing import Tuple
|
|
21
|
+
|
|
22
|
+
# Clase de Django para enviar respuestas HTTP en formato JSON
|
|
23
|
+
# Se usa para devolver mensajes al cliente en caso de error o detección de ataques.
|
|
24
|
+
from django.http import JsonResponse
|
|
25
|
+
|
|
26
|
+
# Clase base para crear middlewares en Django (compatible con versiones antiguas)
|
|
27
|
+
# Permite definir métodos como process_request o process_response para interceptar solicitudes y respuestas.
|
|
28
|
+
from django.utils.deprecation import MiddlewareMixin
|
|
29
|
+
|
|
30
|
+
# Permite acceder a las configuraciones de Django (settings.py)
|
|
31
|
+
# Se usa para obtener rutas excluidas u otras configuraciones personalizadas.
|
|
32
|
+
from django.conf import settings
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# ==============================
|
|
36
|
+
# CONFIGURACIÓN DEL LOG
|
|
37
|
+
# ==============================
|
|
38
|
+
logger = logging.getLogger(
|
|
39
|
+
"sqlidefense"
|
|
40
|
+
) # logger para registrar eventos de SQL Injection
|
|
41
|
+
logger.setLevel(logging.INFO)
|
|
42
|
+
if not logger.handlers:
|
|
43
|
+
# Si no tiene manejadores, agregar uno por defecto a consola
|
|
44
|
+
handler = logging.StreamHandler()
|
|
45
|
+
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
|
|
46
|
+
handler.setFormatter(formatter)
|
|
47
|
+
logger.addHandler(handler)
|
|
48
|
+
|
|
49
|
+
# ==============================
|
|
50
|
+
# PATRONES DE ATAQUE SQL
|
|
51
|
+
# ==============================
|
|
52
|
+
# Cada tupla contiene (expresión regular, descripción del ataque)
|
|
53
|
+
PATTERNS = [
|
|
54
|
+
(re.compile(r"\bunion\b\s+(all\s+)?\bselect\b", re.I), "UNION SELECT"),
|
|
55
|
+
(
|
|
56
|
+
re.compile(r"\bselect\b.*\bfrom\b.*\bwhere\b.*\b(or|and)\b.*=", re.I),
|
|
57
|
+
"SELECT con OR/AND",
|
|
58
|
+
),
|
|
59
|
+
(re.compile(r"\b(or|and)\s+\d+\s*=\s*\d+", re.I), "OR/AND 1=1"),
|
|
60
|
+
(
|
|
61
|
+
re.compile(r"\b(drop|truncate|delete|insert|update)\b", re.I),
|
|
62
|
+
"Manipulación de tabla",
|
|
63
|
+
),
|
|
64
|
+
(re.compile(r"(--|#|;)", re.I), "Comentario o terminador sospechoso"),
|
|
65
|
+
(re.compile(r"exec\s*\(", re.I), "Ejecución de procedimiento"),
|
|
66
|
+
]
|
|
67
|
+
|
|
68
|
+
# ==============================
|
|
69
|
+
# FUNCIONES AUXILIARES
|
|
70
|
+
# ==============================
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def extract_payload_text(request) -> str:
|
|
74
|
+
"""
|
|
75
|
+
Extrae texto de la solicitud que será analizado por patrones SQL Injection.
|
|
76
|
+
Se considera:
|
|
77
|
+
- Cuerpo de la solicitud (JSON o texto plano)
|
|
78
|
+
- Query String (parámetros GET)
|
|
79
|
+
- User-Agent
|
|
80
|
+
- Referer
|
|
81
|
+
"""
|
|
82
|
+
parts = []
|
|
83
|
+
content_type = request.META.get("CONTENT_TYPE", "")
|
|
84
|
+
|
|
85
|
+
try:
|
|
86
|
+
# Si es JSON, decodificarlo
|
|
87
|
+
if "application/json" in content_type:
|
|
88
|
+
body_json = json.loads(request.body.decode("utf-8") or "{}")
|
|
89
|
+
parts.append(json.dumps(body_json))
|
|
90
|
+
else:
|
|
91
|
+
parts.append(request.body.decode("utf-8", errors="ignore"))
|
|
92
|
+
except Exception:
|
|
93
|
+
# Ignorar errores al decodificar
|
|
94
|
+
pass
|
|
95
|
+
|
|
96
|
+
# Agregar Query String
|
|
97
|
+
if request.META.get("QUERY_STRING"):
|
|
98
|
+
parts.append(request.META.get("QUERY_STRING"))
|
|
99
|
+
|
|
100
|
+
# Agregar User-Agent y Referer
|
|
101
|
+
parts.append(request.META.get("HTTP_USER_AGENT", ""))
|
|
102
|
+
parts.append(request.META.get("HTTP_REFERER", ""))
|
|
103
|
+
|
|
104
|
+
# Retornar todo el texto concatenado
|
|
105
|
+
return " ".join([p for p in parts if p])
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def detect_sqli_text(text: str) -> Tuple[bool, list]:
|
|
109
|
+
"""
|
|
110
|
+
Detecta si un texto contiene patrones de SQL Injection.
|
|
111
|
+
Retorna:
|
|
112
|
+
- flagged (bool): True si se detecta algún patrón
|
|
113
|
+
- matches (list): lista de descripciones de patrones detectados
|
|
114
|
+
"""
|
|
115
|
+
matches = []
|
|
116
|
+
for patt, message in PATTERNS:
|
|
117
|
+
if patt.search(text):
|
|
118
|
+
matches.append(message)
|
|
119
|
+
return (len(matches) > 0, matches)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# ==============================
|
|
123
|
+
# MIDDLEWARE
|
|
124
|
+
# ==============================
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class SQLIDefenseMiddleware(MiddlewareMixin):
|
|
128
|
+
"""
|
|
129
|
+
Middleware para proteger la aplicación contra ataques de SQL Injection.
|
|
130
|
+
Analiza cada solicitud entrante y bloquea si detecta patrones maliciosos,
|
|
131
|
+
excepto en rutas definidas como confiables en settings.SQLI_DEFENSE_EXCLUDED_PATHS.
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
def process_request(self, request):
|
|
135
|
+
# Obtener rutas excluidas desde settings
|
|
136
|
+
excluded_paths = getattr(settings, "SQLI_DEFENSE_EXCLUDED_PATHS", [])
|
|
137
|
+
|
|
138
|
+
# Saltar verificación si la ruta está excluida
|
|
139
|
+
if any(request.path.startswith(p) for p in excluded_paths):
|
|
140
|
+
return None
|
|
141
|
+
|
|
142
|
+
# Extraer texto de la solicitud
|
|
143
|
+
text = extract_payload_text(request)
|
|
144
|
+
if not text:
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
# Detectar patrones SQL Injection
|
|
148
|
+
flagged, matches = detect_sqli_text(text)
|
|
149
|
+
if flagged:
|
|
150
|
+
# Registrar evento en log
|
|
151
|
+
logger.warning(f"Ataque detectado: {matches}, payload: {text}")
|
|
152
|
+
|
|
153
|
+
# Bloquear la solicitud y devolver mensaje
|
|
154
|
+
return JsonResponse(
|
|
155
|
+
{"mensaje": "Ataque detectado", "tipos": matches}, status=403
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
return None
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
"""
|
|
162
|
+
Notas adicionales:
|
|
163
|
+
- Se puede aplicar cifrado AES-256 para guardar consultas auditadas.
|
|
164
|
+
- Se puede usar hash SHA-256 para verificar integridad de registros.
|
|
165
|
+
- Índice de amenaza:
|
|
166
|
+
S_sql = w_sql * detecciones_sql
|
|
167
|
+
donde w_sql es el peso asignado a SQL Injection
|
|
168
|
+
detecciones_sql es la cantidad de patrones detectados
|
|
169
|
+
"""
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: GuardianUnivalle-Benito-Yucra
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.13
|
|
4
4
|
Summary: Middleware y detectores de seguridad (SQLi, XSS, CSRF, DoS, Keylogger) para Django/Flask
|
|
5
5
|
Author-email: Andres Benito Calle Yucra <benitoandrescalle035@gmail.com>
|
|
6
6
|
License: MIT
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: GuardianUnivalle-Benito-Yucra
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.13
|
|
4
4
|
Summary: Middleware y detectores de seguridad (SQLi, XSS, CSRF, DoS, Keylogger) para Django/Flask
|
|
5
5
|
Author-email: Andres Benito Calle Yucra <benitoandrescalle035@gmail.com>
|
|
6
6
|
License: MIT
|
{guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.13}/pyproject.toml
RENAMED
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "GuardianUnivalle-Benito-Yucra" # usar mayúsculas consistente
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.13"
|
|
8
8
|
description = "Middleware y detectores de seguridad (SQLi, XSS, CSRF, DoS, Keylogger) para Django/Flask"
|
|
9
9
|
authors = [
|
|
10
10
|
{ name = "Andres Benito Calle Yucra", email = "benitoandrescalle035@gmail.com" }
|
guardianunivalle_benito_yucra-0.1.11/GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py
DELETED
|
@@ -1,183 +0,0 @@
|
|
|
1
|
-
# detector_sql.py
|
|
2
|
-
import re
|
|
3
|
-
import json
|
|
4
|
-
import time
|
|
5
|
-
import logging
|
|
6
|
-
from typing import Tuple
|
|
7
|
-
from django.http import JsonResponse
|
|
8
|
-
from django.utils.deprecation import MiddlewareMixin
|
|
9
|
-
from django.conf import settings
|
|
10
|
-
from django.core.signing import TimestampSigner, BadSignature, SignatureExpired
|
|
11
|
-
|
|
12
|
-
# ---------- Configuración de logging ----------
|
|
13
|
-
logger = logging.getLogger("sqlidefense")
|
|
14
|
-
logger.setLevel(logging.INFO)
|
|
15
|
-
if not logger.handlers:
|
|
16
|
-
handler = logging.StreamHandler() # en prod usa FileHandler/RotatingFileHandler
|
|
17
|
-
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
|
|
18
|
-
handler.setFormatter(formatter)
|
|
19
|
-
logger.addHandler(handler)
|
|
20
|
-
|
|
21
|
-
# ---------- Patrones de ataques SQL ----------
|
|
22
|
-
PATTERNS = [
|
|
23
|
-
(
|
|
24
|
-
re.compile(r"\bunion\b\s+(all\s+)?\bselect\b", re.I),
|
|
25
|
-
"Intento de UNION SELECT detectado",
|
|
26
|
-
),
|
|
27
|
-
(
|
|
28
|
-
re.compile(r"\bselect\b.*\bfrom\b.*\bwhere\b.*\b(or|and)\b.*=", re.I),
|
|
29
|
-
"Intento de SELECT con OR/AND detectado",
|
|
30
|
-
),
|
|
31
|
-
(
|
|
32
|
-
re.compile(r"\b(or|and)\s+\d+\s*=\s*\d+", re.I),
|
|
33
|
-
"Intento de OR/AND 1=1 detectado",
|
|
34
|
-
),
|
|
35
|
-
(
|
|
36
|
-
re.compile(r"\b(drop|truncate|delete|insert|update)\b", re.I),
|
|
37
|
-
"Intento de manipulación de tabla detectado",
|
|
38
|
-
),
|
|
39
|
-
(
|
|
40
|
-
re.compile(r"(--|#|;)", re.I),
|
|
41
|
-
"Comentario o terminador de sentencia sospechoso detectado",
|
|
42
|
-
),
|
|
43
|
-
(re.compile(r"exec\s*\(", re.I), "Intento de ejecución de procedimiento detectado"),
|
|
44
|
-
]
|
|
45
|
-
|
|
46
|
-
# ---------- Bloqueo temporal por IP ----------
|
|
47
|
-
TEMP_BLOCK = {} # {ip: timestamp}
|
|
48
|
-
BLOCK_DURATION = getattr(settings, "SQL_DEFENSE_BLOCK_TTL", 30) # segundos
|
|
49
|
-
|
|
50
|
-
# ---------- Excepciones y bypass ----------
|
|
51
|
-
EXEMPT_PATHS = getattr(settings, "SQLI_EXEMPT_PATHS", ["/api/login/"])
|
|
52
|
-
BYPASS_HEADER = "HTTP_X_SQLI_BYPASS"
|
|
53
|
-
BYPASS_MAX_AGE = getattr(settings, "SQLI_BYPASS_MAX_AGE", 30) # segundos (muy corto)
|
|
54
|
-
|
|
55
|
-
# JWT support (optional)
|
|
56
|
-
try:
|
|
57
|
-
from rest_framework_simplejwt.backends import TokenBackend
|
|
58
|
-
|
|
59
|
-
SIMPLEJWT_AVAILABLE = True
|
|
60
|
-
except Exception:
|
|
61
|
-
SIMPLEJWT_AVAILABLE = False
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
# ---------- Helpers ----------
|
|
65
|
-
def extract_payload_text(request) -> str:
|
|
66
|
-
parts = []
|
|
67
|
-
content_type = request.META.get("CONTENT_TYPE", "")
|
|
68
|
-
try:
|
|
69
|
-
if "application/json" in content_type:
|
|
70
|
-
body_json = json.loads(request.body.decode("utf-8") or "{}")
|
|
71
|
-
# 🔒 quitar campos sensibles antes de loguear/analizar
|
|
72
|
-
for key in getattr(settings, "SQL_DEFENSE_SENSITIVE_KEYS", []):
|
|
73
|
-
if key in body_json:
|
|
74
|
-
body_json[key] = "***"
|
|
75
|
-
parts.append(json.dumps(body_json))
|
|
76
|
-
else:
|
|
77
|
-
parts.append(request.body.decode("utf-8", errors="ignore"))
|
|
78
|
-
except Exception:
|
|
79
|
-
pass
|
|
80
|
-
|
|
81
|
-
if request.META.get("QUERY_STRING"):
|
|
82
|
-
parts.append(request.META.get("QUERY_STRING"))
|
|
83
|
-
|
|
84
|
-
parts.append(request.META.get("HTTP_USER_AGENT", ""))
|
|
85
|
-
parts.append(request.META.get("HTTP_REFERER", ""))
|
|
86
|
-
|
|
87
|
-
return " ".join([p for p in parts if p])
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
def detect_sqli_text(text: str) -> Tuple[bool, list]:
|
|
91
|
-
matches = []
|
|
92
|
-
for patt, message in PATTERNS:
|
|
93
|
-
if patt.search(text):
|
|
94
|
-
matches.append(message)
|
|
95
|
-
return (len(matches) > 0, matches)
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
def get_client_ip(request):
|
|
99
|
-
xff = request.META.get("HTTP_X_FORWARDED_FOR")
|
|
100
|
-
if xff:
|
|
101
|
-
return xff.split(",")[0].strip()
|
|
102
|
-
return request.META.get("REMOTE_ADDR", "0.0.0.0")
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
def is_valid_jwt(request) -> bool:
|
|
106
|
-
if not SIMPLEJWT_AVAILABLE:
|
|
107
|
-
return False
|
|
108
|
-
auth = request.META.get("HTTP_AUTHORIZATION", "")
|
|
109
|
-
if not auth or not auth.startswith("Bearer "):
|
|
110
|
-
return False
|
|
111
|
-
token = auth.split(" ", 1)[1].strip()
|
|
112
|
-
try:
|
|
113
|
-
tb = TokenBackend(
|
|
114
|
-
algorithm=getattr(settings, "SIMPLE_JWT", {}).get("ALGORITHM", "HS256"),
|
|
115
|
-
signing_key=getattr(settings, "SIMPLE_JWT", {}).get(
|
|
116
|
-
"SIGNING_KEY", settings.SECRET_KEY
|
|
117
|
-
),
|
|
118
|
-
)
|
|
119
|
-
tb.decode(token, verify=True)
|
|
120
|
-
return True
|
|
121
|
-
except Exception:
|
|
122
|
-
return False
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
def is_valid_signed_bypass(request) -> bool:
|
|
126
|
-
signed = request.META.get(BYPASS_HEADER, "")
|
|
127
|
-
if not signed:
|
|
128
|
-
return False
|
|
129
|
-
signer = TimestampSigner(settings.SECRET_KEY)
|
|
130
|
-
try:
|
|
131
|
-
signer.unsign(signed, max_age=BYPASS_MAX_AGE)
|
|
132
|
-
return True
|
|
133
|
-
except SignatureExpired:
|
|
134
|
-
logger.info("Bypass token expirado")
|
|
135
|
-
return False
|
|
136
|
-
except BadSignature:
|
|
137
|
-
logger.info("Bypass token inválido")
|
|
138
|
-
return False
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
# ---------- Middleware ----------
|
|
142
|
-
class SQLIDefenseStrongMiddleware(MiddlewareMixin):
|
|
143
|
-
def process_request(self, request):
|
|
144
|
-
path = request.path or ""
|
|
145
|
-
client_ip = get_client_ip(request)
|
|
146
|
-
|
|
147
|
-
# 1) Rutas exentas
|
|
148
|
-
EXEMPT_PATHS = getattr(settings, "SQLI_EXEMPT_PATHS", [])
|
|
149
|
-
for p in EXEMPT_PATHS:
|
|
150
|
-
if path.startswith(p):
|
|
151
|
-
return None
|
|
152
|
-
|
|
153
|
-
# 2) IP bloqueada temporalmente
|
|
154
|
-
if client_ip in TEMP_BLOCK:
|
|
155
|
-
if time.time() - TEMP_BLOCK[client_ip] < BLOCK_DURATION:
|
|
156
|
-
logger.warning(f"IP bloqueada temporalmente: {client_ip}")
|
|
157
|
-
return JsonResponse(
|
|
158
|
-
{"detail": "Acceso temporalmente bloqueado"}, status=403
|
|
159
|
-
)
|
|
160
|
-
else:
|
|
161
|
-
del TEMP_BLOCK[client_ip]
|
|
162
|
-
|
|
163
|
-
# 3) Extraer payload
|
|
164
|
-
text = extract_payload_text(request)
|
|
165
|
-
if not text:
|
|
166
|
-
return None
|
|
167
|
-
|
|
168
|
-
# 4) Detectar SQLi
|
|
169
|
-
flagged, matches = detect_sqli_text(text)
|
|
170
|
-
if flagged:
|
|
171
|
-
TEMP_BLOCK[client_ip] = time.time()
|
|
172
|
-
logger.warning(
|
|
173
|
-
f"Intento de ataque detectado desde IP: {client_ip}, detalles: {matches}, payload: {text}"
|
|
174
|
-
)
|
|
175
|
-
return JsonResponse(
|
|
176
|
-
{
|
|
177
|
-
"detail": "Request bloqueado: posible inyección SQL",
|
|
178
|
-
"alerts": matches,
|
|
179
|
-
},
|
|
180
|
-
status=403,
|
|
181
|
-
)
|
|
182
|
-
|
|
183
|
-
return None
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|