GuardianUnivalle-Benito-Yucra 0.1.8__tar.gz → 0.1.10__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.

Files changed (26) hide show
  1. guardianunivalle_benito_yucra-0.1.10/GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py +191 -0
  2. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra.egg-info/PKG-INFO +1 -1
  3. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/PKG-INFO +1 -1
  4. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/pyproject.toml +1 -1
  5. guardianunivalle_benito_yucra-0.1.8/GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py +0 -133
  6. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra/__init__.py +0 -0
  7. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra/auditoria/registro_auditoria.py +0 -0
  8. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra/criptografia/cifrado_aead.py +0 -0
  9. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra/criptografia/intercambio_claves.py +0 -0
  10. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra/criptografia/kdf.py +0 -0
  11. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra/detectores/detector_csrf.py +0 -0
  12. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra/detectores/detector_dos.py +0 -0
  13. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra/detectores/detector_keylogger.py +0 -0
  14. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra/detectores/detector_xss.py +0 -0
  15. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra/middleware_web/middleware_web.py +0 -0
  16. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra/mitigacion/limitador_peticion.py +0 -0
  17. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra/mitigacion/lista_bloqueo.py +0 -0
  18. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra/puntuacion/puntuacion_amenaza.py +0 -0
  19. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra/utilidades.py +0 -0
  20. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra.egg-info/SOURCES.txt +0 -0
  21. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra.egg-info/dependency_links.txt +0 -0
  22. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra.egg-info/requires.txt +0 -0
  23. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/GuardianUnivalle_Benito_Yucra.egg-info/top_level.txt +0 -0
  24. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/LICENSE +0 -0
  25. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/README.md +0 -0
  26. {guardianunivalle_benito_yucra-0.1.8 → guardianunivalle_benito_yucra-0.1.10}/setup.cfg +0 -0
@@ -0,0 +1,191 @@
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
+ 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
+ text = extract_payload_text(request)
174
+ if not text:
175
+ return None
176
+
177
+ flagged, matches = detect_sqli_text(text)
178
+ if flagged:
179
+ TEMP_BLOCK[client_ip] = time.time()
180
+ logger.warning(
181
+ f"Intento de ataque detectado desde IP: {client_ip}, detalles: {matches}, payload: {text}"
182
+ )
183
+ return JsonResponse(
184
+ {
185
+ "detail": "Request bloqueado: posible inyección SQL",
186
+ "alerts": matches,
187
+ },
188
+ status=403,
189
+ )
190
+
191
+ return None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: GuardianUnivalle-Benito-Yucra
3
- Version: 0.1.8
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
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: GuardianUnivalle-Benito-Yucra
3
- Version: 0.1.8
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
@@ -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.8"
7
+ version = "0.1.10"
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" }
@@ -1,133 +0,0 @@
1
- import re
2
- import json
3
- import time
4
- import logging
5
- from typing import Tuple
6
- from django.http import JsonResponse
7
- from django.utils.deprecation import MiddlewareMixin
8
-
9
- # ---------- Configuración de logging ----------
10
- logger = logging.getLogger("sqlidefense")
11
- logger.setLevel(logging.INFO)
12
- handler = logging.StreamHandler() # Por consola; en producción puede ser FileHandler
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
- (
20
- re.compile(r"\bunion\b\s+(all\s+)?\bselect\b", re.I),
21
- "Intento de UNION SELECT detectado",
22
- ),
23
- (
24
- re.compile(r"\bselect\b.*\bfrom\b.*\bwhere\b.*\b(or|and)\b.*=", re.I),
25
- "Intento de SELECT con OR/AND detectado",
26
- ),
27
- (
28
- re.compile(r"\b(or|and)\s+\d+\s*=\s*\d+", re.I),
29
- "Intento de OR/AND 1=1 detectado",
30
- ),
31
- (
32
- re.compile(r"\b(drop|truncate|delete|insert|update)\b", re.I),
33
- "Intento de manipulación de tabla detectado",
34
- ),
35
- (
36
- re.compile(r"(--|#|;)", re.I),
37
- "Comentario o terminador de sentencia sospechoso detectado",
38
- ),
39
- (re.compile(r"exec\s*\(", re.I), "Intento de ejecución de procedimiento detectado"),
40
- ]
41
-
42
- # ---------- Bloqueo temporal por IP ----------
43
- TEMP_BLOCK = {} # {ip: timestamp}
44
- BLOCK_DURATION = 30 # segundos
45
-
46
-
47
- # ---------- Helpers ----------
48
- def extract_payload_text(request) -> str:
49
- """Extrae todo el contenido que podría contener inyecciones"""
50
- parts = []
51
-
52
- # Query params
53
- if request.META.get("QUERY_STRING"):
54
- parts.append(request.META.get("QUERY_STRING"))
55
-
56
- # Body
57
- try:
58
- content_type = request.META.get("CONTENT_TYPE", "")
59
- if "application/json" in content_type:
60
- body_json = json.loads(request.body.decode("utf-8") or "{}")
61
- parts.append(json.dumps(body_json))
62
- else:
63
- parts.append(request.body.decode("utf-8", errors="ignore"))
64
- except Exception:
65
- pass
66
-
67
- # Headers
68
- parts.append(request.META.get("HTTP_USER_AGENT", ""))
69
- parts.append(request.META.get("HTTP_REFERER", ""))
70
-
71
- return " ".join([p for p in parts if p])
72
-
73
-
74
- def detect_sqli_text(text: str) -> Tuple[bool, list]:
75
- """Detecta ataques SQL en el texto"""
76
- matches = []
77
- for patt, message in PATTERNS:
78
- if patt.search(text):
79
- matches.append(message)
80
- return (len(matches) > 0, matches)
81
-
82
-
83
- def get_client_ip(request):
84
- """Obtiene la IP del cliente"""
85
- x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
86
- if x_forwarded_for:
87
- ip = x_forwarded_for.split(",")[0].strip()
88
- else:
89
- ip = request.META.get("REMOTE_ADDR", "0.0.0.0")
90
- return ip
91
-
92
-
93
- # ---------- Middleware ----------
94
- class SQLIDefenseStrongMiddleware(MiddlewareMixin):
95
- def process_request(self, request):
96
- client_ip = get_client_ip(request)
97
-
98
- # Revisa si la IP está temporalmente bloqueada
99
- if client_ip in TEMP_BLOCK:
100
- if time.time() - TEMP_BLOCK[client_ip] < BLOCK_DURATION:
101
- logger.warning(f"IP bloqueada temporalmente: {client_ip}")
102
- return JsonResponse(
103
- {
104
- "detail": "Acceso temporalmente bloqueado por actividad sospechosa",
105
- "alerts": ["IP bloqueada temporalmente"],
106
- },
107
- status=403,
108
- )
109
- else:
110
- del TEMP_BLOCK[client_ip]
111
-
112
- text = extract_payload_text(request)
113
- if not text:
114
- return None
115
-
116
- flagged, matches = detect_sqli_text(text)
117
- if flagged:
118
- # Bloquea temporalmente la IP
119
- TEMP_BLOCK[client_ip] = time.time()
120
- # Logging profesional
121
- logger.warning(
122
- f"Intento de ataque detectado desde IP: {client_ip}, detalles: {matches}, payload: {text}"
123
- )
124
-
125
- return JsonResponse(
126
- {
127
- "detail": "Request bloqueado: posible intento de inyección SQL detectado",
128
- "alerts": matches,
129
- },
130
- status=403,
131
- )
132
-
133
- return None