GuardianUnivalle-Benito-Yucra 0.1.2__py3-none-any.whl → 0.1.4__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 +12 -115
- {guardianunivalle_benito_yucra-0.1.2.dist-info → guardianunivalle_benito_yucra-0.1.4.dist-info}/METADATA +1 -1
- {guardianunivalle_benito_yucra-0.1.2.dist-info → guardianunivalle_benito_yucra-0.1.4.dist-info}/RECORD +6 -6
- {guardianunivalle_benito_yucra-0.1.2.dist-info → guardianunivalle_benito_yucra-0.1.4.dist-info}/WHEEL +0 -0
- {guardianunivalle_benito_yucra-0.1.2.dist-info → guardianunivalle_benito_yucra-0.1.4.dist-info}/licenses/LICENSE +0 -0
- {guardianunivalle_benito_yucra-0.1.2.dist-info → guardianunivalle_benito_yucra-0.1.4.dist-info}/top_level.txt +0 -0
|
@@ -1,26 +1,9 @@
|
|
|
1
1
|
# middleware_sql_defense.py
|
|
2
2
|
import re
|
|
3
3
|
import json
|
|
4
|
-
import time
|
|
5
4
|
from typing import Tuple
|
|
6
|
-
from django.conf import settings
|
|
7
5
|
from django.http import JsonResponse
|
|
8
6
|
from django.utils.deprecation import MiddlewareMixin
|
|
9
|
-
import redis
|
|
10
|
-
|
|
11
|
-
# ---------- CONFIGURABLES (poner en settings.py preferiblemente) ----------
|
|
12
|
-
W_SQL = getattr(settings, "SQL_DEFENSE_W_SQL", 1.0)
|
|
13
|
-
THRESHOLD = getattr(settings, "SQL_DEFENSE_THRESHOLD", 0.8) # score normalizado 0..1
|
|
14
|
-
WINDOW_SEC = getattr(
|
|
15
|
-
settings, "SQL_DEFENSE_WINDOW_SEC", 300
|
|
16
|
-
) # ventana para conteo (ej. 5min)
|
|
17
|
-
MAX_EXPECTED_DETECTIONS = getattr(settings, "SQL_DEFENSE_MAX_EXPECTED_DETECTIONS", 10)
|
|
18
|
-
BLOCK_TTL = getattr(
|
|
19
|
-
settings, "SQL_DEFENSE_BLOCK_TTL", 600
|
|
20
|
-
) # bloqueo por IP en segundos (ej. 10min)
|
|
21
|
-
|
|
22
|
-
REDIS_URL = getattr(settings, "SQL_DEFENSE_REDIS_URL", "redis://localhost:6379/0")
|
|
23
|
-
redis_client = redis.from_url(REDIS_URL, decode_responses=True)
|
|
24
7
|
|
|
25
8
|
# ---------- Patrones y normalización ----------
|
|
26
9
|
_literal_single = re.compile(r"'([^'\\]|\\.)*'")
|
|
@@ -37,16 +20,6 @@ PATTERNS = [
|
|
|
37
20
|
|
|
38
21
|
|
|
39
22
|
# ---------- Helpers ----------
|
|
40
|
-
def get_client_ip(request) -> str:
|
|
41
|
-
"""Obtiene la IP real (si hay proxies, usa X-Forwarded-For)"""
|
|
42
|
-
xff = request.META.get("HTTP_X_FORWARDED_FOR")
|
|
43
|
-
if xff:
|
|
44
|
-
# X-Forwarded-For puede contener lista de IPs
|
|
45
|
-
ip = xff.split(",")[0].strip()
|
|
46
|
-
return ip
|
|
47
|
-
return request.META.get("REMOTE_ADDR", "")
|
|
48
|
-
|
|
49
|
-
|
|
50
23
|
def normalize_text(s: str) -> str:
|
|
51
24
|
"""Quita literales y comentarios para reducir falsos positivos"""
|
|
52
25
|
if not s:
|
|
@@ -59,18 +32,13 @@ def normalize_text(s: str) -> str:
|
|
|
59
32
|
|
|
60
33
|
|
|
61
34
|
def extract_payload_text(request) -> str:
|
|
62
|
-
"""
|
|
63
|
-
Extrae texto potencialmente peligroso del request:
|
|
64
|
-
- query string
|
|
65
|
-
- body (JSON o form)
|
|
66
|
-
- headers sospechosos (User-Agent, Referer)
|
|
67
|
-
"""
|
|
35
|
+
"""Extrae texto potencialmente peligroso del request"""
|
|
68
36
|
parts = []
|
|
69
37
|
try:
|
|
70
38
|
# query params
|
|
71
39
|
if request.META.get("QUERY_STRING"):
|
|
72
40
|
parts.append(request.META.get("QUERY_STRING"))
|
|
73
|
-
# body
|
|
41
|
+
# body
|
|
74
42
|
content_type = request.META.get("CONTENT_TYPE", "")
|
|
75
43
|
if "application/json" in content_type:
|
|
76
44
|
try:
|
|
@@ -79,12 +47,11 @@ def extract_payload_text(request) -> str:
|
|
|
79
47
|
except Exception:
|
|
80
48
|
parts.append((request.body or b"").decode("utf-8", errors="ignore"))
|
|
81
49
|
else:
|
|
82
|
-
# form-encoded or other text
|
|
83
50
|
try:
|
|
84
51
|
parts.append(request.body.decode("utf-8", errors="ignore"))
|
|
85
52
|
except Exception:
|
|
86
53
|
pass
|
|
87
|
-
# headers
|
|
54
|
+
# headers sospechosos
|
|
88
55
|
parts.append(request.META.get("HTTP_USER_AGENT", ""))
|
|
89
56
|
parts.append(request.META.get("HTTP_REFERER", ""))
|
|
90
57
|
except Exception:
|
|
@@ -93,7 +60,7 @@ def extract_payload_text(request) -> str:
|
|
|
93
60
|
|
|
94
61
|
|
|
95
62
|
def detect_sqli_text(text: str) -> Tuple[bool, list]:
|
|
96
|
-
"""Detecta patrones en un texto normalizado
|
|
63
|
+
"""Detecta patrones en un texto normalizado"""
|
|
97
64
|
q = normalize_text(text)
|
|
98
65
|
matches = []
|
|
99
66
|
for patt, sev in PATTERNS:
|
|
@@ -102,91 +69,21 @@ def detect_sqli_text(text: str) -> Tuple[bool, list]:
|
|
|
102
69
|
return (len(matches) > 0, matches)
|
|
103
70
|
|
|
104
71
|
|
|
105
|
-
# ---------- Redis keys ----------
|
|
106
|
-
def redis_count_key(ip: str) -> str:
|
|
107
|
-
return f"sqli:count:{ip}"
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
def redis_block_key(ip: str) -> str:
|
|
111
|
-
return f"sqli:block:{ip}"
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
# ---------- Cálculo de score S_sql/ip ----------
|
|
115
|
-
def compute_s_sql_ip(detections_count: int) -> float:
|
|
116
|
-
"""
|
|
117
|
-
Convertir conteo a una puntuación normalizada 0..1.
|
|
118
|
-
Usamos saturación en MAX_EXPECTED_DETECTIONS.
|
|
119
|
-
"""
|
|
120
|
-
norm = min(float(detections_count) / float(MAX_EXPECTED_DETECTIONS), 1.0)
|
|
121
|
-
score = float(W_SQL) * norm
|
|
122
|
-
# Normalizamos a 0..1 si W_SQL puede ser mayor que 1
|
|
123
|
-
return min(score, 1.0)
|
|
124
|
-
|
|
125
|
-
|
|
126
72
|
# ---------- Middleware ----------
|
|
127
73
|
class SQLIDefenseMiddleware(MiddlewareMixin):
|
|
128
74
|
def process_request(self, request):
|
|
129
|
-
# 1) obtener IP y comprobar si está bloqueada
|
|
130
|
-
ip = get_client_ip(request)
|
|
131
|
-
if not ip:
|
|
132
|
-
return None # no podemos hacer mucho sin IP
|
|
133
|
-
|
|
134
|
-
# comprobar bloqueo en Redis
|
|
135
|
-
block_key = redis_block_key(ip)
|
|
136
|
-
if redis_client.exists(block_key):
|
|
137
|
-
ttl = redis_client.ttl(block_key)
|
|
138
|
-
return JsonResponse(
|
|
139
|
-
{
|
|
140
|
-
"detail": "Acceso denegado (bloqueado por actividad sospechosa)",
|
|
141
|
-
"block_ttl_s": ttl,
|
|
142
|
-
},
|
|
143
|
-
status=403,
|
|
144
|
-
)
|
|
145
|
-
|
|
146
|
-
# 2) extraer texto y detectar patrones
|
|
147
75
|
text = extract_payload_text(request)
|
|
148
76
|
if not text:
|
|
149
77
|
return None
|
|
150
78
|
|
|
151
79
|
flagged, matches = detect_sqli_text(text)
|
|
152
80
|
if flagged:
|
|
153
|
-
#
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
# calcular score
|
|
162
|
-
current_count = int(new_count)
|
|
163
|
-
s_sql_ip = compute_s_sql_ip(current_count)
|
|
164
|
-
|
|
165
|
-
# registrar evento (puedes ampliar con logging o envío a SIEM)
|
|
166
|
-
# guardamos metadata mínima
|
|
167
|
-
event = {
|
|
168
|
-
"time": int(time.time()),
|
|
169
|
-
"ip": ip,
|
|
170
|
-
"count": current_count,
|
|
171
|
-
"score": s_sql_ip,
|
|
172
|
-
"matches": matches,
|
|
173
|
-
}
|
|
174
|
-
# Puedes push a lista en Redis o a un logger
|
|
175
|
-
redis_client.lpush("sqli:events", json.dumps(event))
|
|
176
|
-
redis_client.ltrim("sqli:events", 0, 999) # mantener últimos 1000 eventos
|
|
177
|
-
|
|
178
|
-
# Si supera THRESHOLD -> bloquear ip
|
|
179
|
-
if s_sql_ip >= float(THRESHOLD):
|
|
180
|
-
redis_client.set(redis_block_key(ip), "1", ex=BLOCK_TTL)
|
|
181
|
-
# opcional: publicar alerta en canal pubsub o webhook
|
|
182
|
-
return JsonResponse(
|
|
183
|
-
{"detail": "IP bloqueada por actividad sospechosa", "ip": ip},
|
|
184
|
-
status=403,
|
|
185
|
-
)
|
|
186
|
-
else:
|
|
187
|
-
# no bloqueo todavía: permitir continuar pero devolver alerta en header (opcional)
|
|
188
|
-
# Puedes añadir header para que la vista/log lo capture
|
|
189
|
-
request.META["X-SQLI-ALERT"] = json.dumps(event)
|
|
190
|
-
return None
|
|
191
|
-
|
|
81
|
+
# Bloqueo inmediato solo para pruebas
|
|
82
|
+
return JsonResponse(
|
|
83
|
+
{
|
|
84
|
+
"detail": "Request bloqueado: posible inyección SQL detectada",
|
|
85
|
+
"matches": matches,
|
|
86
|
+
},
|
|
87
|
+
status=403,
|
|
88
|
+
)
|
|
192
89
|
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.4
|
|
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=5p4ZvBIDzU6Ak0PneM0jm75RKddncAI5NUhGipdsqlU,3049
|
|
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.4.dist-info/licenses/LICENSE,sha256=5e4IdL542v1E8Ft0A24GZjrxZeTsVK7XrS3mZEUhPtM,37
|
|
17
|
+
guardianunivalle_benito_yucra-0.1.4.dist-info/METADATA,sha256=Ogc6eE6ffX5Ggrer7ZSgQfPdIV6kv_ofhhxxosxbYp4,1892
|
|
18
|
+
guardianunivalle_benito_yucra-0.1.4.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
19
|
+
guardianunivalle_benito_yucra-0.1.4.dist-info/top_level.txt,sha256=HTWfZM64WAV_QYr5cnXnLuabQt92dvlxqlR3pCwpbDQ,30
|
|
20
|
+
guardianunivalle_benito_yucra-0.1.4.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|