GuardianUnivalle-Benito-Yucra 0.1.17__py3-none-any.whl → 0.1.19__py3-none-any.whl
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/detectores/detector_sql.py +19 -115
- {guardianunivalle_benito_yucra-0.1.17.dist-info → guardianunivalle_benito_yucra-0.1.19.dist-info}/METADATA +1 -1
- {guardianunivalle_benito_yucra-0.1.17.dist-info → guardianunivalle_benito_yucra-0.1.19.dist-info}/RECORD +6 -6
- {guardianunivalle_benito_yucra-0.1.17.dist-info → guardianunivalle_benito_yucra-0.1.19.dist-info}/WHEEL +0 -0
- {guardianunivalle_benito_yucra-0.1.17.dist-info → guardianunivalle_benito_yucra-0.1.19.dist-info}/licenses/LICENSE +0 -0
- {guardianunivalle_benito_yucra-0.1.17.dist-info → guardianunivalle_benito_yucra-0.1.19.dist-info}/top_level.txt +0 -0
|
@@ -1,55 +1,16 @@
|
|
|
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
1
|
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
2
|
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
3
|
from django.conf import settings
|
|
4
|
+
import logging, re, json
|
|
33
5
|
|
|
34
|
-
|
|
35
|
-
# ==============================
|
|
36
|
-
# CONFIGURACIÓN DEL LOG
|
|
37
|
-
# ==============================
|
|
38
|
-
logger = logging.getLogger(
|
|
39
|
-
"sqlidefense"
|
|
40
|
-
) # logger para registrar eventos de SQL Injection
|
|
6
|
+
logger = logging.getLogger("sqlidefense")
|
|
41
7
|
logger.setLevel(logging.INFO)
|
|
42
8
|
if not logger.handlers:
|
|
43
|
-
# Si no tiene manejadores, agregar uno por defecto a consola
|
|
44
9
|
handler = logging.StreamHandler()
|
|
45
|
-
|
|
46
|
-
handler.setFormatter(formatter)
|
|
10
|
+
handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
|
|
47
11
|
logger.addHandler(handler)
|
|
48
12
|
|
|
49
|
-
#
|
|
50
|
-
# PATRONES DE ATAQUE SQL
|
|
51
|
-
# ==============================
|
|
52
|
-
# Cada tupla contiene (expresión regular, descripción del ataque)
|
|
13
|
+
# Patrones de ataque SQL
|
|
53
14
|
PATTERNS = [
|
|
54
15
|
(re.compile(r"\bunion\b\s+(all\s+)?\bselect\b", re.I), "UNION SELECT"),
|
|
55
16
|
(
|
|
@@ -65,53 +26,25 @@ PATTERNS = [
|
|
|
65
26
|
(re.compile(r"exec\s*\(", re.I), "Ejecución de procedimiento"),
|
|
66
27
|
]
|
|
67
28
|
|
|
68
|
-
# ==============================
|
|
69
|
-
# FUNCIONES AUXILIARES
|
|
70
|
-
# ==============================
|
|
71
|
-
|
|
72
29
|
|
|
73
|
-
def extract_payload_text(request)
|
|
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
|
-
"""
|
|
30
|
+
def extract_payload_text(request):
|
|
82
31
|
parts = []
|
|
83
|
-
content_type = request.META.get("CONTENT_TYPE", "")
|
|
84
|
-
|
|
85
32
|
try:
|
|
86
|
-
|
|
87
|
-
if "application/json" in content_type:
|
|
33
|
+
if "application/json" in request.META.get("CONTENT_TYPE", ""):
|
|
88
34
|
body_json = json.loads(request.body.decode("utf-8") or "{}")
|
|
89
35
|
parts.append(json.dumps(body_json))
|
|
90
36
|
else:
|
|
91
37
|
parts.append(request.body.decode("utf-8", errors="ignore"))
|
|
92
|
-
except
|
|
93
|
-
# Ignorar errores al decodificar
|
|
38
|
+
except:
|
|
94
39
|
pass
|
|
95
|
-
|
|
96
|
-
# Agregar Query String
|
|
97
40
|
if request.META.get("QUERY_STRING"):
|
|
98
41
|
parts.append(request.META.get("QUERY_STRING"))
|
|
99
|
-
|
|
100
|
-
# Agregar User-Agent y Referer
|
|
101
42
|
parts.append(request.META.get("HTTP_USER_AGENT", ""))
|
|
102
43
|
parts.append(request.META.get("HTTP_REFERER", ""))
|
|
103
|
-
|
|
104
|
-
# Retornar todo el texto concatenado
|
|
105
44
|
return " ".join([p for p in parts if p])
|
|
106
45
|
|
|
107
46
|
|
|
108
|
-
def detect_sqli_text(text
|
|
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
|
-
"""
|
|
47
|
+
def detect_sqli_text(text):
|
|
115
48
|
matches = []
|
|
116
49
|
for patt, message in PATTERNS:
|
|
117
50
|
if patt.search(text):
|
|
@@ -120,65 +53,36 @@ def detect_sqli_text(text: str) -> Tuple[bool, list]:
|
|
|
120
53
|
|
|
121
54
|
|
|
122
55
|
def get_client_ip(request):
|
|
123
|
-
"""
|
|
124
|
-
Retorna la IP del cliente, manejando proxies.
|
|
125
|
-
"""
|
|
126
56
|
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
|
|
127
57
|
if x_forwarded_for:
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
else:
|
|
131
|
-
ip = request.META.get("REMOTE_ADDR")
|
|
132
|
-
return ip
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
# ==============================
|
|
136
|
-
# MIDDLEWARE
|
|
137
|
-
# ==============================
|
|
58
|
+
return x_forwarded_for.split(",")[0].strip()
|
|
59
|
+
return request.META.get("REMOTE_ADDR")
|
|
138
60
|
|
|
139
61
|
|
|
140
62
|
class SQLIDefenseMiddleware(MiddlewareMixin):
|
|
141
63
|
def process_request(self, request):
|
|
142
|
-
# Obtener la IP del cliente
|
|
143
64
|
client_ip = get_client_ip(request)
|
|
144
|
-
|
|
145
|
-
# Obtener lista de IPs confiables desde settings
|
|
146
65
|
trusted_ips = getattr(settings, "SQLI_DEFENSE_TRUSTED_IPS", [])
|
|
147
66
|
|
|
148
|
-
# Si la IP está en la lista confiable, no hacemos nada
|
|
149
67
|
if client_ip in trusted_ips:
|
|
150
68
|
return None
|
|
151
69
|
|
|
152
|
-
# Extraemos el texto de la petición
|
|
153
70
|
text = extract_payload_text(request)
|
|
154
71
|
if not text:
|
|
155
72
|
return None
|
|
156
73
|
|
|
157
|
-
# Detectamos SQL Injection
|
|
158
74
|
flagged, matches = detect_sqli_text(text)
|
|
159
75
|
if flagged:
|
|
76
|
+
# Guardamos los datos del ataque en el request
|
|
77
|
+
request.sql_attack_info = {
|
|
78
|
+
"ip": client_ip,
|
|
79
|
+
"tipos": matches,
|
|
80
|
+
"payload": text,
|
|
81
|
+
}
|
|
82
|
+
|
|
160
83
|
logger.warning(
|
|
161
84
|
f"Ataque SQL detectado desde IP {client_ip}: {matches}, payload: {text}"
|
|
162
85
|
)
|
|
163
|
-
return JsonResponse(
|
|
164
|
-
{
|
|
165
|
-
"mensaje": "Ataque detectado",
|
|
166
|
-
"tipos": matches,
|
|
167
|
-
"ip": client_ip,
|
|
168
|
-
"payload": text,
|
|
169
|
-
},
|
|
170
|
-
status=403,
|
|
171
|
-
)
|
|
172
|
-
|
|
173
|
-
return None
|
|
174
86
|
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
Notas adicionales:
|
|
178
|
-
- Se puede aplicar cifrado AES-256 para guardar consultas auditadas.
|
|
179
|
-
- Se puede usar hash SHA-256 para verificar integridad de registros.
|
|
180
|
-
- Índice de amenaza:
|
|
181
|
-
S_sql = w_sql * detecciones_sql
|
|
182
|
-
donde w_sql es el peso asignado a SQL Injection
|
|
183
|
-
detecciones_sql es la cantidad de patrones detectados
|
|
184
|
-
"""
|
|
87
|
+
# 👉 Aquí ya NO devolvemos JsonResponse
|
|
88
|
+
return None
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: GuardianUnivalle-Benito-Yucra
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.19
|
|
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
|
|
@@ -7,14 +7,14 @@ GuardianUnivalle_Benito_Yucra/criptografia/kdf.py,sha256=_sbepEY1qHEKga0ExrX2WRg
|
|
|
7
7
|
GuardianUnivalle_Benito_Yucra/detectores/detector_csrf.py,sha256=EAYfLkHuxGC5rXSu4mZJ4yZDCbwBpTX8xZWGKz7i5wA,692
|
|
8
8
|
GuardianUnivalle_Benito_Yucra/detectores/detector_dos.py,sha256=lMWmCw6nccCEnek53nVjpoBCeiBqLdrSXxqRuI7VP2I,696
|
|
9
9
|
GuardianUnivalle_Benito_Yucra/detectores/detector_keylogger.py,sha256=rEDG-Q_R56OsG2ypfHVBK7erolYjdvATnAxB3yvPXts,729
|
|
10
|
-
GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py,sha256=
|
|
10
|
+
GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py,sha256=qbYOc-Y1i_wmuYSY_skTa4j6nFaLAjEJ-p_AdIEjtf4,2930
|
|
11
11
|
GuardianUnivalle_Benito_Yucra/detectores/detector_xss.py,sha256=66V_xuxNOZEwluvWOT4-6pk5MJ3zWE1IwcVkBl7MZSg,719
|
|
12
12
|
GuardianUnivalle_Benito_Yucra/middleware_web/middleware_web.py,sha256=23pLLYqliUoMrIC6ZEwz3hKXeDjWfHSm9vYPWGmDDik,495
|
|
13
13
|
GuardianUnivalle_Benito_Yucra/mitigacion/limitador_peticion.py,sha256=ipMOebYhql-6mSyHs0ddYXOcXq9w8P_IXLlpiIqGncw,246
|
|
14
14
|
GuardianUnivalle_Benito_Yucra/mitigacion/lista_bloqueo.py,sha256=6AYWII4mrmwCLHCvGTyoBxR4Oasr4raSHpFbVjqn7d8,193
|
|
15
15
|
GuardianUnivalle_Benito_Yucra/puntuacion/puntuacion_amenaza.py,sha256=Wx5XfcII4oweLvZsTBEJ7kUc9pMpP5-36RfI5C5KJXo,561
|
|
16
|
-
guardianunivalle_benito_yucra-0.1.
|
|
17
|
-
guardianunivalle_benito_yucra-0.1.
|
|
18
|
-
guardianunivalle_benito_yucra-0.1.
|
|
19
|
-
guardianunivalle_benito_yucra-0.1.
|
|
20
|
-
guardianunivalle_benito_yucra-0.1.
|
|
16
|
+
guardianunivalle_benito_yucra-0.1.19.dist-info/licenses/LICENSE,sha256=5e4IdL542v1E8Ft0A24GZjrxZeTsVK7XrS3mZEUhPtM,37
|
|
17
|
+
guardianunivalle_benito_yucra-0.1.19.dist-info/METADATA,sha256=0yp93hYVTOMtAMMzYRideNMkcCmu0yPsKD8J9uxQdh4,1893
|
|
18
|
+
guardianunivalle_benito_yucra-0.1.19.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
19
|
+
guardianunivalle_benito_yucra-0.1.19.dist-info/top_level.txt,sha256=HTWfZM64WAV_QYr5cnXnLuabQt92dvlxqlR3pCwpbDQ,30
|
|
20
|
+
guardianunivalle_benito_yucra-0.1.19.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|