GuardianUnivalle-Benito-Yucra 0.1.61__py3-none-any.whl → 0.1.62__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 +26 -63
- {guardianunivalle_benito_yucra-0.1.61.dist-info → guardianunivalle_benito_yucra-0.1.62.dist-info}/METADATA +1 -1
- {guardianunivalle_benito_yucra-0.1.61.dist-info → guardianunivalle_benito_yucra-0.1.62.dist-info}/RECORD +6 -6
- {guardianunivalle_benito_yucra-0.1.61.dist-info → guardianunivalle_benito_yucra-0.1.62.dist-info}/WHEEL +0 -0
- {guardianunivalle_benito_yucra-0.1.61.dist-info → guardianunivalle_benito_yucra-0.1.62.dist-info}/licenses/LICENSE +0 -0
- {guardianunivalle_benito_yucra-0.1.61.dist-info → guardianunivalle_benito_yucra-0.1.62.dist-info}/top_level.txt +0 -0
|
@@ -10,6 +10,9 @@ import urllib.parse
|
|
|
10
10
|
import html
|
|
11
11
|
from typing import List, Tuple, Dict
|
|
12
12
|
|
|
13
|
+
# ----------------------------
|
|
14
|
+
# Configuración del logger
|
|
15
|
+
# ----------------------------
|
|
13
16
|
logger = logging.getLogger("sqlidefense")
|
|
14
17
|
logger.setLevel(logging.INFO)
|
|
15
18
|
if not logger.handlers:
|
|
@@ -18,7 +21,7 @@ if not logger.handlers:
|
|
|
18
21
|
logger.addHandler(handler)
|
|
19
22
|
|
|
20
23
|
# =====================================================
|
|
21
|
-
# ===
|
|
24
|
+
# === PATRONES DE ATAQUE SQL DEFINIDOS ===
|
|
22
25
|
# =====================================================
|
|
23
26
|
SQL_PATTERNS: List[Tuple[re.Pattern, str, float]] = [
|
|
24
27
|
# ------------------ In‑Band / Exfiltration (muy alto) ------------------
|
|
@@ -50,7 +53,7 @@ SQL_PATTERNS: List[Tuple[re.Pattern, str, float]] = [
|
|
|
50
53
|
# ------------------ Metadata / Recon (alto) ------------------
|
|
51
54
|
(re.compile(r"\binformation_schema\b", re.I), "INFORMATION_SCHEMA (recon meta‑datos)", 0.92),
|
|
52
55
|
(re.compile(r"\b(information_schema\.tables|information_schema\.columns)\b", re.I), "INFORMATION_SCHEMA.tables/columns", 0.92),
|
|
53
|
-
(re.compile(r"\b(sys\.tables|sys\.objects|sys\.databases|pg_catalog|pg_tables|pg_user)\b", re.I), "
|
|
56
|
+
(re.compile(r"\b(sys\.tables|sys\.objects|sys\.databases|pg_catalog|pg_tables|pg_user)\b", re.I), "Catálogos del sistema (MSSQL/Postgres)", 0.9),
|
|
54
57
|
|
|
55
58
|
# ------------------ DML/DDL Destructivo (alto) ------------------
|
|
56
59
|
(re.compile(r"\b(drop\s+table|truncate\s+table|drop\s+database|drop\s+schema)\b", re.I), "DROP/TRUNCATE (DDL destructivo)", 0.95),
|
|
@@ -107,27 +110,23 @@ SQL_PATTERNS: List[Tuple[re.Pattern, str, float]] = [
|
|
|
107
110
|
(re.compile(r"\b(or)\b\s+1\s*=\s*1\b", re.I), "OR 1=1 tautology", 0.85),
|
|
108
111
|
]
|
|
109
112
|
|
|
110
|
-
|
|
111
113
|
IGNORED_FIELDS = ["password", "csrfmiddlewaretoken", "token", "auth"]
|
|
112
114
|
|
|
115
|
+
# ----------------------------
|
|
116
|
+
# Obtener IP real del cliente
|
|
117
|
+
# ----------------------------
|
|
113
118
|
def get_client_ip(request):
|
|
114
|
-
"""
|
|
115
|
-
Obtiene la IP real del cliente.
|
|
116
|
-
Primero revisa 'X-Forwarded-For', luego 'REMOTE_ADDR'.
|
|
117
|
-
"""
|
|
118
119
|
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
|
|
119
120
|
if x_forwarded_for:
|
|
120
|
-
# Render y otros proxies envían múltiples IPs separados por coma
|
|
121
121
|
ips = [ip.strip() for ip in x_forwarded_for.split(",") if ip.strip()]
|
|
122
122
|
if ips:
|
|
123
|
-
return ips[0]
|
|
124
|
-
# Si no hay X-Forwarded-For, tomar REMOTE_ADDR
|
|
123
|
+
return ips[0]
|
|
125
124
|
return request.META.get("REMOTE_ADDR", "")
|
|
126
125
|
|
|
127
|
-
|
|
128
|
-
|
|
126
|
+
# ----------------------------
|
|
127
|
+
# Extraer payload de la solicitud
|
|
128
|
+
# ----------------------------
|
|
129
129
|
def extract_payload(request):
|
|
130
|
-
"""Extrae datos útiles de la solicitud para análisis."""
|
|
131
130
|
parts = []
|
|
132
131
|
try:
|
|
133
132
|
if "application/json" in request.META.get("CONTENT_TYPE", ""):
|
|
@@ -146,50 +145,29 @@ def extract_payload(request):
|
|
|
146
145
|
|
|
147
146
|
return " ".join(parts)
|
|
148
147
|
|
|
149
|
-
|
|
150
148
|
# ----------------------------
|
|
151
149
|
# Normalización / preprocesamiento
|
|
152
150
|
# ----------------------------
|
|
153
151
|
def normalize_input(s: str) -> str:
|
|
154
|
-
"""
|
|
155
|
-
Normaliza la entrada:
|
|
156
|
-
- decode URL encoding
|
|
157
|
-
- unescape HTML entities
|
|
158
|
-
- sustituye escapes de hex (\xNN) por su literal
|
|
159
|
-
- colapsa múltiples espacios y newlines
|
|
160
|
-
- lower() opcional (NO se hace porque algunos patrones usan case-insensitive)
|
|
161
|
-
"""
|
|
162
152
|
if not s:
|
|
163
153
|
return ""
|
|
164
154
|
try:
|
|
165
|
-
# URL decode
|
|
166
155
|
s_dec = urllib.parse.unquote_plus(s)
|
|
167
156
|
except Exception:
|
|
168
157
|
s_dec = s
|
|
169
158
|
try:
|
|
170
|
-
# Unescape HTML entities
|
|
171
159
|
s_dec = html.unescape(s_dec)
|
|
172
160
|
except Exception:
|
|
173
161
|
pass
|
|
174
|
-
#
|
|
175
|
-
s_dec = re.sub(r"\\x([0-9a-fA-F]{2})", r"\\x\1", s_dec)
|
|
176
|
-
# Collapse whitespace
|
|
162
|
+
# Reemplazo seguro de secuencias \xNN
|
|
163
|
+
s_dec = re.sub(r"\\x([0-9a-fA-F]{2})", r"\\x\g<1>", s_dec)
|
|
177
164
|
s_dec = re.sub(r"\s+", " ", s_dec)
|
|
178
165
|
return s_dec.strip()
|
|
166
|
+
|
|
179
167
|
# ----------------------------
|
|
180
|
-
# Detector
|
|
168
|
+
# Detector SQLi
|
|
181
169
|
# ----------------------------
|
|
182
170
|
def detect_sql_injection(text: str) -> Dict:
|
|
183
|
-
"""
|
|
184
|
-
Detecta coincidencias con SQL_PATTERNS en el texto normalizado.
|
|
185
|
-
Devuelve:
|
|
186
|
-
{
|
|
187
|
-
"score": float,
|
|
188
|
-
"matches": [("Etiqueta", "regex pattern string", weight), ...],
|
|
189
|
-
"descriptions": [ "Etiqueta", ... ],
|
|
190
|
-
"sample": excerpt (primeros 1200 chars)
|
|
191
|
-
}
|
|
192
|
-
"""
|
|
193
171
|
norm = normalize_input(text or "")
|
|
194
172
|
score = 0.0
|
|
195
173
|
matches = []
|
|
@@ -203,17 +181,10 @@ def detect_sql_injection(text: str) -> Dict:
|
|
|
203
181
|
return {
|
|
204
182
|
"score": round(score, 3),
|
|
205
183
|
"matches": matches,
|
|
206
|
-
"descriptions": list(dict.fromkeys(descriptions)),
|
|
184
|
+
"descriptions": list(dict.fromkeys(descriptions)),
|
|
207
185
|
"sample": norm[:1200],
|
|
208
186
|
}
|
|
209
187
|
|
|
210
|
-
# ----------------------------
|
|
211
|
-
# Umbrales sugeridos
|
|
212
|
-
# ----------------------------
|
|
213
|
-
# - >= 1.8 : ALTA (bloquear + registrar)
|
|
214
|
-
# - 1.0 - <1.8 : MEDIA (registrar, desafío/2FA, throttling)
|
|
215
|
-
# - 0.5 - <1.0 : BAJA (registrar, monitorear)
|
|
216
|
-
# - <0.5 : INFORMATIVO (log heurístico)
|
|
217
188
|
DEFAULT_THRESHOLDS = {
|
|
218
189
|
"HIGH": 1.8,
|
|
219
190
|
"MEDIUM": 1.0,
|
|
@@ -221,17 +192,9 @@ DEFAULT_THRESHOLDS = {
|
|
|
221
192
|
}
|
|
222
193
|
|
|
223
194
|
# ----------------------------
|
|
224
|
-
#
|
|
195
|
+
# Middleware SQLi
|
|
225
196
|
# ----------------------------
|
|
226
|
-
# payload = extract_payload(request) # tu función actual
|
|
227
|
-
# result = detect_sql_injection(payload)
|
|
228
|
-
# if result["score"] >= DEFAULT_THRESHOLDS["HIGH"]:
|
|
229
|
-
# bloquear_y_registrar()
|
|
230
|
-
# else:
|
|
231
|
-
# registrar_solo()
|
|
232
197
|
class SQLIDefenseMiddleware(MiddlewareMixin):
|
|
233
|
-
"""Middleware de detección SQL Injection."""
|
|
234
|
-
|
|
235
198
|
def process_request(self, request):
|
|
236
199
|
client_ip = get_client_ip(request)
|
|
237
200
|
trusted_ips = getattr(settings, "SQLI_DEFENSE_TRUSTED_IPS", [])
|
|
@@ -246,35 +209,35 @@ class SQLIDefenseMiddleware(MiddlewareMixin):
|
|
|
246
209
|
return None
|
|
247
210
|
|
|
248
211
|
payload = extract_payload(request)
|
|
249
|
-
|
|
212
|
+
result = detect_sql_injection(payload)
|
|
213
|
+
score = result["score"]
|
|
214
|
+
descripciones = result["descriptions"]
|
|
250
215
|
|
|
251
216
|
if score == 0:
|
|
252
217
|
return None
|
|
253
218
|
|
|
254
|
-
# Registrar ataque
|
|
219
|
+
# Registrar ataque
|
|
255
220
|
logger.warning(
|
|
256
221
|
f"[SQLiDetect] IP={client_ip} Host={host} Referer={referer} "
|
|
257
222
|
f"Score={score:.2f} Desc={descripciones} Payload={payload[:500]}"
|
|
258
223
|
)
|
|
259
224
|
|
|
260
|
-
# Guardar
|
|
225
|
+
# Guardar info en request
|
|
261
226
|
request.sql_attack_info = {
|
|
262
227
|
"ip": client_ip,
|
|
263
228
|
"tipos": ["SQLi"],
|
|
264
229
|
"descripcion": descripciones,
|
|
265
|
-
"payload": payload[:1000],
|
|
230
|
+
"payload": payload[:1000],
|
|
266
231
|
"score": round(score, 2),
|
|
267
|
-
"url": request.build_absolute_uri(),
|
|
232
|
+
"url": request.build_absolute_uri(),
|
|
268
233
|
}
|
|
269
234
|
|
|
270
235
|
return None
|
|
271
236
|
|
|
272
|
-
|
|
273
|
-
|
|
274
237
|
# =====================================================
|
|
275
238
|
# === INFORMACIÓN EXTRA ===
|
|
276
239
|
# =====================================================
|
|
277
|
-
"""
|
|
240
|
+
r"""
|
|
278
241
|
Algoritmos relacionados:
|
|
279
242
|
- Se recomienda almacenar logs SQLi cifrados (AES-GCM)
|
|
280
243
|
para proteger evidencia de intentos maliciosos.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: GuardianUnivalle-Benito-Yucra
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.62
|
|
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=q7-UsVseTtIYZz4bbpx2X0kzpDmu2Cetm7eYPJtsruA,7608
|
|
8
8
|
GuardianUnivalle_Benito_Yucra/detectores/detector_dos.py,sha256=Jy4fhI-6n9wQR0quzpondcUyCA2447lDq4fmOFeM1jA,14989
|
|
9
9
|
GuardianUnivalle_Benito_Yucra/detectores/detector_keylogger.py,sha256=L5RQ0Sdgg7hTU1qkZYwt7AcDqtAzT6u-jwBGo7YWfsw,8078
|
|
10
|
-
GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py,sha256=
|
|
10
|
+
GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py,sha256=toYXgxLo1Wy_QCnqcboD7_qYbgudPtP4kEzci7GoDkA,12089
|
|
11
11
|
GuardianUnivalle_Benito_Yucra/detectores/detector_xss.py,sha256=Cirjf1fo0j-wOO2baG8GFehAvjPy5JUF9krUg5AtofU,14452
|
|
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.62.dist-info/licenses/LICENSE,sha256=5e4IdL542v1E8Ft0A24GZjrxZeTsVK7XrS3mZEUhPtM,37
|
|
17
|
+
guardianunivalle_benito_yucra-0.1.62.dist-info/METADATA,sha256=AqWlHPn2dsr38Y7CJkFFtreVNtHMpsR9JBuNlqJ2qaY,1893
|
|
18
|
+
guardianunivalle_benito_yucra-0.1.62.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
19
|
+
guardianunivalle_benito_yucra-0.1.62.dist-info/top_level.txt,sha256=HTWfZM64WAV_QYr5cnXnLuabQt92dvlxqlR3pCwpbDQ,30
|
|
20
|
+
guardianunivalle_benito_yucra-0.1.62.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|