GuardianUnivalle-Benito-Yucra 0.1.10__py3-none-any.whl → 0.1.12__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 +10 -126
- {guardianunivalle_benito_yucra-0.1.10.dist-info → guardianunivalle_benito_yucra-0.1.12.dist-info}/METADATA +1 -1
- {guardianunivalle_benito_yucra-0.1.10.dist-info → guardianunivalle_benito_yucra-0.1.12.dist-info}/RECORD +6 -6
- {guardianunivalle_benito_yucra-0.1.10.dist-info → guardianunivalle_benito_yucra-0.1.12.dist-info}/WHEEL +0 -0
- {guardianunivalle_benito_yucra-0.1.10.dist-info → guardianunivalle_benito_yucra-0.1.12.dist-info}/licenses/LICENSE +0 -0
- {guardianunivalle_benito_yucra-0.1.10.dist-info → guardianunivalle_benito_yucra-0.1.12.dist-info}/top_level.txt +0 -0
|
@@ -1,65 +1,35 @@
|
|
|
1
1
|
# detector_sql.py
|
|
2
2
|
import re
|
|
3
3
|
import json
|
|
4
|
-
import time
|
|
5
4
|
import logging
|
|
6
5
|
from typing import Tuple
|
|
7
6
|
from django.http import JsonResponse
|
|
8
7
|
from django.utils.deprecation import MiddlewareMixin
|
|
9
|
-
from django.conf import settings
|
|
10
|
-
from django.core.signing import TimestampSigner, BadSignature, SignatureExpired
|
|
11
8
|
|
|
12
|
-
# ---------- Configuración de logging ----------
|
|
13
9
|
logger = logging.getLogger("sqlidefense")
|
|
14
10
|
logger.setLevel(logging.INFO)
|
|
15
11
|
if not logger.handlers:
|
|
16
|
-
handler = logging.StreamHandler()
|
|
12
|
+
handler = logging.StreamHandler()
|
|
17
13
|
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
|
|
18
14
|
handler.setFormatter(formatter)
|
|
19
15
|
logger.addHandler(handler)
|
|
20
16
|
|
|
21
17
|
# ---------- Patrones de ataques SQL ----------
|
|
22
18
|
PATTERNS = [
|
|
23
|
-
(
|
|
24
|
-
re.compile(r"\bunion\b\s+(all\s+)?\bselect\b", re.I),
|
|
25
|
-
"Intento de UNION SELECT detectado",
|
|
26
|
-
),
|
|
19
|
+
(re.compile(r"\bunion\b\s+(all\s+)?\bselect\b", re.I), "UNION SELECT"),
|
|
27
20
|
(
|
|
28
21
|
re.compile(r"\bselect\b.*\bfrom\b.*\bwhere\b.*\b(or|and)\b.*=", re.I),
|
|
29
|
-
"
|
|
30
|
-
),
|
|
31
|
-
(
|
|
32
|
-
re.compile(r"\b(or|and)\s+\d+\s*=\s*\d+", re.I),
|
|
33
|
-
"Intento de OR/AND 1=1 detectado",
|
|
22
|
+
"SELECT con OR/AND",
|
|
34
23
|
),
|
|
24
|
+
(re.compile(r"\b(or|and)\s+\d+\s*=\s*\d+", re.I), "OR/AND 1=1"),
|
|
35
25
|
(
|
|
36
26
|
re.compile(r"\b(drop|truncate|delete|insert|update)\b", re.I),
|
|
37
|
-
"
|
|
27
|
+
"Manipulación de tabla",
|
|
38
28
|
),
|
|
39
|
-
(
|
|
40
|
-
|
|
41
|
-
"Comentario o terminador de sentencia sospechoso detectado",
|
|
42
|
-
),
|
|
43
|
-
(re.compile(r"exec\s*\(", re.I), "Intento de ejecución de procedimiento detectado"),
|
|
29
|
+
(re.compile(r"(--|#|;)", re.I), "Comentario o terminador sospechoso"),
|
|
30
|
+
(re.compile(r"exec\s*\(", re.I), "Ejecución de procedimiento"),
|
|
44
31
|
]
|
|
45
32
|
|
|
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
33
|
|
|
64
34
|
# ---------- Helpers ----------
|
|
65
35
|
def extract_payload_text(request) -> str:
|
|
@@ -68,22 +38,15 @@ def extract_payload_text(request) -> str:
|
|
|
68
38
|
try:
|
|
69
39
|
if "application/json" in content_type:
|
|
70
40
|
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
41
|
parts.append(json.dumps(body_json))
|
|
76
42
|
else:
|
|
77
43
|
parts.append(request.body.decode("utf-8", errors="ignore"))
|
|
78
44
|
except Exception:
|
|
79
45
|
pass
|
|
80
|
-
|
|
81
46
|
if request.META.get("QUERY_STRING"):
|
|
82
47
|
parts.append(request.META.get("QUERY_STRING"))
|
|
83
|
-
|
|
84
48
|
parts.append(request.META.get("HTTP_USER_AGENT", ""))
|
|
85
49
|
parts.append(request.META.get("HTTP_REFERER", ""))
|
|
86
|
-
|
|
87
50
|
return " ".join([p for p in parts if p])
|
|
88
51
|
|
|
89
52
|
|
|
@@ -95,97 +58,18 @@ def detect_sqli_text(text: str) -> Tuple[bool, list]:
|
|
|
95
58
|
return (len(matches) > 0, matches)
|
|
96
59
|
|
|
97
60
|
|
|
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
61
|
# ---------- Middleware ----------
|
|
142
|
-
class
|
|
62
|
+
class SQLIDefenseMiddleware(MiddlewareMixin):
|
|
143
63
|
def process_request(self, request):
|
|
144
|
-
path = request.path or ""
|
|
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
|
|
155
|
-
|
|
156
|
-
# 2) Si la IP está temporalmente bloqueada
|
|
157
|
-
if client_ip in TEMP_BLOCK:
|
|
158
|
-
if time.time() - TEMP_BLOCK[client_ip] < BLOCK_DURATION:
|
|
159
|
-
logger.warning(f"IP bloqueada temporalmente: {client_ip}")
|
|
160
|
-
return JsonResponse(
|
|
161
|
-
{"detail": "Acceso temporalmente bloqueado"}, status=403
|
|
162
|
-
)
|
|
163
|
-
else:
|
|
164
|
-
del TEMP_BLOCK[client_ip]
|
|
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
|
|
173
64
|
text = extract_payload_text(request)
|
|
174
65
|
if not text:
|
|
175
66
|
return None
|
|
176
67
|
|
|
177
68
|
flagged, matches = detect_sqli_text(text)
|
|
178
69
|
if flagged:
|
|
179
|
-
|
|
180
|
-
logger.warning(
|
|
181
|
-
f"Intento de ataque detectado desde IP: {client_ip}, detalles: {matches}, payload: {text}"
|
|
182
|
-
)
|
|
70
|
+
logger.warning(f"Ataque detectado: {matches}, payload: {text}")
|
|
183
71
|
return JsonResponse(
|
|
184
|
-
{
|
|
185
|
-
"detail": "Request bloqueado: posible inyección SQL",
|
|
186
|
-
"alerts": matches,
|
|
187
|
-
},
|
|
188
|
-
status=403,
|
|
72
|
+
{"mensaje": "Ataque detectado", "tipos": matches}, status=403
|
|
189
73
|
)
|
|
190
74
|
|
|
191
75
|
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.12
|
|
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=Sr2gGAKPgOA8FUwyrMDU2q7h91lY5KWs0Xwhm0B3RKg,2536
|
|
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.12.dist-info/licenses/LICENSE,sha256=5e4IdL542v1E8Ft0A24GZjrxZeTsVK7XrS3mZEUhPtM,37
|
|
17
|
+
guardianunivalle_benito_yucra-0.1.12.dist-info/METADATA,sha256=wUUpR44XgfP7gLoBeBQoSxZ72f_gJuZ1EGDT6NJriRs,1893
|
|
18
|
+
guardianunivalle_benito_yucra-0.1.12.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
19
|
+
guardianunivalle_benito_yucra-0.1.12.dist-info/top_level.txt,sha256=HTWfZM64WAV_QYr5cnXnLuabQt92dvlxqlR3pCwpbDQ,30
|
|
20
|
+
guardianunivalle_benito_yucra-0.1.12.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|