GuardianUnivalle-Benito-Yucra 0.1.11__tar.gz → 0.1.12__tar.gz
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-0.1.12/GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py +75 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra.egg-info/PKG-INFO +1 -1
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/PKG-INFO +1 -1
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/pyproject.toml +1 -1
- guardianunivalle_benito_yucra-0.1.11/GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py +0 -183
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra/__init__.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra/auditoria/registro_auditoria.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra/criptografia/cifrado_aead.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra/criptografia/intercambio_claves.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra/criptografia/kdf.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra/detectores/detector_csrf.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra/detectores/detector_dos.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra/detectores/detector_keylogger.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra/detectores/detector_xss.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra/middleware_web/middleware_web.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra/mitigacion/limitador_peticion.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra/mitigacion/lista_bloqueo.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra/puntuacion/puntuacion_amenaza.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra/utilidades.py +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra.egg-info/SOURCES.txt +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra.egg-info/dependency_links.txt +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra.egg-info/requires.txt +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/GuardianUnivalle_Benito_Yucra.egg-info/top_level.txt +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/LICENSE +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/README.md +0 -0
- {guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/setup.cfg +0 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# detector_sql.py
|
|
2
|
+
import re
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
from typing import Tuple
|
|
6
|
+
from django.http import JsonResponse
|
|
7
|
+
from django.utils.deprecation import MiddlewareMixin
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger("sqlidefense")
|
|
10
|
+
logger.setLevel(logging.INFO)
|
|
11
|
+
if not logger.handlers:
|
|
12
|
+
handler = logging.StreamHandler()
|
|
13
|
+
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
|
|
14
|
+
handler.setFormatter(formatter)
|
|
15
|
+
logger.addHandler(handler)
|
|
16
|
+
|
|
17
|
+
# ---------- Patrones de ataques SQL ----------
|
|
18
|
+
PATTERNS = [
|
|
19
|
+
(re.compile(r"\bunion\b\s+(all\s+)?\bselect\b", re.I), "UNION SELECT"),
|
|
20
|
+
(
|
|
21
|
+
re.compile(r"\bselect\b.*\bfrom\b.*\bwhere\b.*\b(or|and)\b.*=", re.I),
|
|
22
|
+
"SELECT con OR/AND",
|
|
23
|
+
),
|
|
24
|
+
(re.compile(r"\b(or|and)\s+\d+\s*=\s*\d+", re.I), "OR/AND 1=1"),
|
|
25
|
+
(
|
|
26
|
+
re.compile(r"\b(drop|truncate|delete|insert|update)\b", re.I),
|
|
27
|
+
"Manipulación de tabla",
|
|
28
|
+
),
|
|
29
|
+
(re.compile(r"(--|#|;)", re.I), "Comentario o terminador sospechoso"),
|
|
30
|
+
(re.compile(r"exec\s*\(", re.I), "Ejecución de procedimiento"),
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# ---------- Helpers ----------
|
|
35
|
+
def extract_payload_text(request) -> str:
|
|
36
|
+
parts = []
|
|
37
|
+
content_type = request.META.get("CONTENT_TYPE", "")
|
|
38
|
+
try:
|
|
39
|
+
if "application/json" in content_type:
|
|
40
|
+
body_json = json.loads(request.body.decode("utf-8") or "{}")
|
|
41
|
+
parts.append(json.dumps(body_json))
|
|
42
|
+
else:
|
|
43
|
+
parts.append(request.body.decode("utf-8", errors="ignore"))
|
|
44
|
+
except Exception:
|
|
45
|
+
pass
|
|
46
|
+
if request.META.get("QUERY_STRING"):
|
|
47
|
+
parts.append(request.META.get("QUERY_STRING"))
|
|
48
|
+
parts.append(request.META.get("HTTP_USER_AGENT", ""))
|
|
49
|
+
parts.append(request.META.get("HTTP_REFERER", ""))
|
|
50
|
+
return " ".join([p for p in parts if p])
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def detect_sqli_text(text: str) -> Tuple[bool, list]:
|
|
54
|
+
matches = []
|
|
55
|
+
for patt, message in PATTERNS:
|
|
56
|
+
if patt.search(text):
|
|
57
|
+
matches.append(message)
|
|
58
|
+
return (len(matches) > 0, matches)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ---------- Middleware ----------
|
|
62
|
+
class SQLIDefenseMiddleware(MiddlewareMixin):
|
|
63
|
+
def process_request(self, request):
|
|
64
|
+
text = extract_payload_text(request)
|
|
65
|
+
if not text:
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
flagged, matches = detect_sqli_text(text)
|
|
69
|
+
if flagged:
|
|
70
|
+
logger.warning(f"Ataque detectado: {matches}, payload: {text}")
|
|
71
|
+
return JsonResponse(
|
|
72
|
+
{"mensaje": "Ataque detectado", "tipos": matches}, status=403
|
|
73
|
+
)
|
|
74
|
+
|
|
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
|
|
@@ -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
|
{guardianunivalle_benito_yucra-0.1.11 → guardianunivalle_benito_yucra-0.1.12}/pyproject.toml
RENAMED
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "GuardianUnivalle-Benito-Yucra" # usar mayúsculas consistente
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.12"
|
|
8
8
|
description = "Middleware y detectores de seguridad (SQLi, XSS, CSRF, DoS, Keylogger) para Django/Flask"
|
|
9
9
|
authors = [
|
|
10
10
|
{ name = "Andres Benito Calle Yucra", email = "benitoandrescalle035@gmail.com" }
|
guardianunivalle_benito_yucra-0.1.11/GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py
DELETED
|
@@ -1,183 +0,0 @@
|
|
|
1
|
-
# detector_sql.py
|
|
2
|
-
import re
|
|
3
|
-
import json
|
|
4
|
-
import time
|
|
5
|
-
import logging
|
|
6
|
-
from typing import Tuple
|
|
7
|
-
from django.http import JsonResponse
|
|
8
|
-
from django.utils.deprecation import MiddlewareMixin
|
|
9
|
-
from django.conf import settings
|
|
10
|
-
from django.core.signing import TimestampSigner, BadSignature, SignatureExpired
|
|
11
|
-
|
|
12
|
-
# ---------- Configuración de logging ----------
|
|
13
|
-
logger = logging.getLogger("sqlidefense")
|
|
14
|
-
logger.setLevel(logging.INFO)
|
|
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)
|
|
20
|
-
|
|
21
|
-
# ---------- Patrones de ataques SQL ----------
|
|
22
|
-
PATTERNS = [
|
|
23
|
-
(
|
|
24
|
-
re.compile(r"\bunion\b\s+(all\s+)?\bselect\b", re.I),
|
|
25
|
-
"Intento de UNION SELECT detectado",
|
|
26
|
-
),
|
|
27
|
-
(
|
|
28
|
-
re.compile(r"\bselect\b.*\bfrom\b.*\bwhere\b.*\b(or|and)\b.*=", re.I),
|
|
29
|
-
"Intento de SELECT con OR/AND detectado",
|
|
30
|
-
),
|
|
31
|
-
(
|
|
32
|
-
re.compile(r"\b(or|and)\s+\d+\s*=\s*\d+", re.I),
|
|
33
|
-
"Intento de OR/AND 1=1 detectado",
|
|
34
|
-
),
|
|
35
|
-
(
|
|
36
|
-
re.compile(r"\b(drop|truncate|delete|insert|update)\b", re.I),
|
|
37
|
-
"Intento de manipulación de tabla detectado",
|
|
38
|
-
),
|
|
39
|
-
(
|
|
40
|
-
re.compile(r"(--|#|;)", re.I),
|
|
41
|
-
"Comentario o terminador de sentencia sospechoso detectado",
|
|
42
|
-
),
|
|
43
|
-
(re.compile(r"exec\s*\(", re.I), "Intento de ejecución de procedimiento detectado"),
|
|
44
|
-
]
|
|
45
|
-
|
|
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
|
-
|
|
64
|
-
# ---------- Helpers ----------
|
|
65
|
-
def extract_payload_text(request) -> str:
|
|
66
|
-
parts = []
|
|
67
|
-
content_type = request.META.get("CONTENT_TYPE", "")
|
|
68
|
-
try:
|
|
69
|
-
if "application/json" in content_type:
|
|
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] = "***"
|
|
75
|
-
parts.append(json.dumps(body_json))
|
|
76
|
-
else:
|
|
77
|
-
parts.append(request.body.decode("utf-8", errors="ignore"))
|
|
78
|
-
except Exception:
|
|
79
|
-
pass
|
|
80
|
-
|
|
81
|
-
if request.META.get("QUERY_STRING"):
|
|
82
|
-
parts.append(request.META.get("QUERY_STRING"))
|
|
83
|
-
|
|
84
|
-
parts.append(request.META.get("HTTP_USER_AGENT", ""))
|
|
85
|
-
parts.append(request.META.get("HTTP_REFERER", ""))
|
|
86
|
-
|
|
87
|
-
return " ".join([p for p in parts if p])
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
def detect_sqli_text(text: str) -> Tuple[bool, list]:
|
|
91
|
-
matches = []
|
|
92
|
-
for patt, message in PATTERNS:
|
|
93
|
-
if patt.search(text):
|
|
94
|
-
matches.append(message)
|
|
95
|
-
return (len(matches) > 0, matches)
|
|
96
|
-
|
|
97
|
-
|
|
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
|
-
# ---------- Middleware ----------
|
|
142
|
-
class SQLIDefenseStrongMiddleware(MiddlewareMixin):
|
|
143
|
-
def process_request(self, request):
|
|
144
|
-
path = request.path or ""
|
|
145
|
-
client_ip = get_client_ip(request)
|
|
146
|
-
|
|
147
|
-
# 1) Rutas exentas
|
|
148
|
-
EXEMPT_PATHS = getattr(settings, "SQLI_EXEMPT_PATHS", [])
|
|
149
|
-
for p in EXEMPT_PATHS:
|
|
150
|
-
if path.startswith(p):
|
|
151
|
-
return None
|
|
152
|
-
|
|
153
|
-
# 2) IP bloqueada temporalmente
|
|
154
|
-
if client_ip in TEMP_BLOCK:
|
|
155
|
-
if time.time() - TEMP_BLOCK[client_ip] < BLOCK_DURATION:
|
|
156
|
-
logger.warning(f"IP bloqueada temporalmente: {client_ip}")
|
|
157
|
-
return JsonResponse(
|
|
158
|
-
{"detail": "Acceso temporalmente bloqueado"}, status=403
|
|
159
|
-
)
|
|
160
|
-
else:
|
|
161
|
-
del TEMP_BLOCK[client_ip]
|
|
162
|
-
|
|
163
|
-
# 3) Extraer payload
|
|
164
|
-
text = extract_payload_text(request)
|
|
165
|
-
if not text:
|
|
166
|
-
return None
|
|
167
|
-
|
|
168
|
-
# 4) Detectar SQLi
|
|
169
|
-
flagged, matches = detect_sqli_text(text)
|
|
170
|
-
if flagged:
|
|
171
|
-
TEMP_BLOCK[client_ip] = time.time()
|
|
172
|
-
logger.warning(
|
|
173
|
-
f"Intento de ataque detectado desde IP: {client_ip}, detalles: {matches}, payload: {text}"
|
|
174
|
-
)
|
|
175
|
-
return JsonResponse(
|
|
176
|
-
{
|
|
177
|
-
"detail": "Request bloqueado: posible inyección SQL",
|
|
178
|
-
"alerts": matches,
|
|
179
|
-
},
|
|
180
|
-
status=403,
|
|
181
|
-
)
|
|
182
|
-
|
|
183
|
-
return None
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|