GuardianUnivalle-Benito-Yucra 0.1.8__py3-none-any.whl → 0.1.10__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 +90 -32
- {guardianunivalle_benito_yucra-0.1.8.dist-info → guardianunivalle_benito_yucra-0.1.10.dist-info}/METADATA +1 -1
- {guardianunivalle_benito_yucra-0.1.8.dist-info → guardianunivalle_benito_yucra-0.1.10.dist-info}/RECORD +6 -6
- {guardianunivalle_benito_yucra-0.1.8.dist-info → guardianunivalle_benito_yucra-0.1.10.dist-info}/WHEEL +0 -0
- {guardianunivalle_benito_yucra-0.1.8.dist-info → guardianunivalle_benito_yucra-0.1.10.dist-info}/licenses/LICENSE +0 -0
- {guardianunivalle_benito_yucra-0.1.8.dist-info → guardianunivalle_benito_yucra-0.1.10.dist-info}/top_level.txt +0 -0
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
# detector_sql.py
|
|
1
2
|
import re
|
|
2
3
|
import json
|
|
3
4
|
import time
|
|
@@ -5,14 +6,17 @@ import logging
|
|
|
5
6
|
from typing import Tuple
|
|
6
7
|
from django.http import JsonResponse
|
|
7
8
|
from django.utils.deprecation import MiddlewareMixin
|
|
9
|
+
from django.conf import settings
|
|
10
|
+
from django.core.signing import TimestampSigner, BadSignature, SignatureExpired
|
|
8
11
|
|
|
9
12
|
# ---------- Configuración de logging ----------
|
|
10
13
|
logger = logging.getLogger("sqlidefense")
|
|
11
14
|
logger.setLevel(logging.INFO)
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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)
|
|
16
20
|
|
|
17
21
|
# ---------- Patrones de ataques SQL ----------
|
|
18
22
|
PATTERNS = [
|
|
@@ -41,30 +45,42 @@ PATTERNS = [
|
|
|
41
45
|
|
|
42
46
|
# ---------- Bloqueo temporal por IP ----------
|
|
43
47
|
TEMP_BLOCK = {} # {ip: timestamp}
|
|
44
|
-
BLOCK_DURATION = 30 # segundos
|
|
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
|
|
45
62
|
|
|
46
63
|
|
|
47
64
|
# ---------- Helpers ----------
|
|
48
65
|
def extract_payload_text(request) -> str:
|
|
49
|
-
"""Extrae todo el contenido que podría contener inyecciones"""
|
|
50
66
|
parts = []
|
|
51
|
-
|
|
52
|
-
# Query params
|
|
53
|
-
if request.META.get("QUERY_STRING"):
|
|
54
|
-
parts.append(request.META.get("QUERY_STRING"))
|
|
55
|
-
|
|
56
|
-
# Body
|
|
67
|
+
content_type = request.META.get("CONTENT_TYPE", "")
|
|
57
68
|
try:
|
|
58
|
-
content_type = request.META.get("CONTENT_TYPE", "")
|
|
59
69
|
if "application/json" in content_type:
|
|
60
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] = "***"
|
|
61
75
|
parts.append(json.dumps(body_json))
|
|
62
76
|
else:
|
|
63
77
|
parts.append(request.body.decode("utf-8", errors="ignore"))
|
|
64
78
|
except Exception:
|
|
65
79
|
pass
|
|
66
80
|
|
|
67
|
-
|
|
81
|
+
if request.META.get("QUERY_STRING"):
|
|
82
|
+
parts.append(request.META.get("QUERY_STRING"))
|
|
83
|
+
|
|
68
84
|
parts.append(request.META.get("HTTP_USER_AGENT", ""))
|
|
69
85
|
parts.append(request.META.get("HTTP_REFERER", ""))
|
|
70
86
|
|
|
@@ -72,7 +88,6 @@ def extract_payload_text(request) -> str:
|
|
|
72
88
|
|
|
73
89
|
|
|
74
90
|
def detect_sqli_text(text: str) -> Tuple[bool, list]:
|
|
75
|
-
"""Detecta ataques SQL en el texto"""
|
|
76
91
|
matches = []
|
|
77
92
|
for patt, message in PATTERNS:
|
|
78
93
|
if patt.search(text):
|
|
@@ -81,50 +96,93 @@ def detect_sqli_text(text: str) -> Tuple[bool, list]:
|
|
|
81
96
|
|
|
82
97
|
|
|
83
98
|
def get_client_ip(request):
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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
|
|
91
139
|
|
|
92
140
|
|
|
93
141
|
# ---------- Middleware ----------
|
|
94
142
|
class SQLIDefenseStrongMiddleware(MiddlewareMixin):
|
|
95
143
|
def process_request(self, request):
|
|
144
|
+
path = request.path or ""
|
|
96
145
|
client_ip = get_client_ip(request)
|
|
146
|
+
if any(
|
|
147
|
+
request.path.startswith(p)
|
|
148
|
+
for p in getattr(settings, "SQL_DEFENSE_EXEMPT_PATHS", [])
|
|
149
|
+
):
|
|
150
|
+
return None
|
|
151
|
+
# 1) Si la ruta está exenta -> no inspeccionar
|
|
152
|
+
for p in EXEMPT_PATHS:
|
|
153
|
+
if path.startswith(p):
|
|
154
|
+
return None
|
|
97
155
|
|
|
98
|
-
#
|
|
156
|
+
# 2) Si la IP está temporalmente bloqueada
|
|
99
157
|
if client_ip in TEMP_BLOCK:
|
|
100
158
|
if time.time() - TEMP_BLOCK[client_ip] < BLOCK_DURATION:
|
|
101
159
|
logger.warning(f"IP bloqueada temporalmente: {client_ip}")
|
|
102
160
|
return JsonResponse(
|
|
103
|
-
{
|
|
104
|
-
"detail": "Acceso temporalmente bloqueado por actividad sospechosa",
|
|
105
|
-
"alerts": ["IP bloqueada temporalmente"],
|
|
106
|
-
},
|
|
107
|
-
status=403,
|
|
161
|
+
{"detail": "Acceso temporalmente bloqueado"}, status=403
|
|
108
162
|
)
|
|
109
163
|
else:
|
|
110
164
|
del TEMP_BLOCK[client_ip]
|
|
111
165
|
|
|
166
|
+
# 3) Bypass: JWT válido o token firmado corto (p. ej. inmediatamente después del login)
|
|
167
|
+
if is_valid_jwt(request):
|
|
168
|
+
return None
|
|
169
|
+
if is_valid_signed_bypass(request):
|
|
170
|
+
return None
|
|
171
|
+
|
|
172
|
+
# 4) Detectar SQLi
|
|
112
173
|
text = extract_payload_text(request)
|
|
113
174
|
if not text:
|
|
114
175
|
return None
|
|
115
176
|
|
|
116
177
|
flagged, matches = detect_sqli_text(text)
|
|
117
178
|
if flagged:
|
|
118
|
-
# Bloquea temporalmente la IP
|
|
119
179
|
TEMP_BLOCK[client_ip] = time.time()
|
|
120
|
-
# Logging profesional
|
|
121
180
|
logger.warning(
|
|
122
181
|
f"Intento de ataque detectado desde IP: {client_ip}, detalles: {matches}, payload: {text}"
|
|
123
182
|
)
|
|
124
|
-
|
|
125
183
|
return JsonResponse(
|
|
126
184
|
{
|
|
127
|
-
"detail": "Request bloqueado: posible
|
|
185
|
+
"detail": "Request bloqueado: posible inyección SQL",
|
|
128
186
|
"alerts": matches,
|
|
129
187
|
},
|
|
130
188
|
status=403,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: GuardianUnivalle-Benito-Yucra
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.10
|
|
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=meTgj5yIZNWpvaQxVL526p5d_fhmTeFsWc6_WO8N0ro,6434
|
|
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.10.dist-info/licenses/LICENSE,sha256=5e4IdL542v1E8Ft0A24GZjrxZeTsVK7XrS3mZEUhPtM,37
|
|
17
|
+
guardianunivalle_benito_yucra-0.1.10.dist-info/METADATA,sha256=xHOfMbH7ZnHOY_dSp9GlHHVnCkgsZJAdlpsq-Rh06XY,1893
|
|
18
|
+
guardianunivalle_benito_yucra-0.1.10.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
19
|
+
guardianunivalle_benito_yucra-0.1.10.dist-info/top_level.txt,sha256=HTWfZM64WAV_QYr5cnXnLuabQt92dvlxqlR3pCwpbDQ,30
|
|
20
|
+
guardianunivalle_benito_yucra-0.1.10.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|