GuardianUnivalle-Benito-Yucra 0.1.11__py3-none-any.whl → 0.1.13__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.

@@ -1,93 +1,117 @@
1
1
  # detector_sql.py
2
+ # =====================================================
3
+ # Importaciones de librerías
4
+ # =====================================================
5
+
6
+ # Módulo para trabajar con expresiones regulares (regex)
7
+ # Permite buscar patrones de texto dentro de cadenas.
2
8
  import re
9
+
10
+ # Módulo para trabajar con datos en formato JSON
11
+ # Permite convertir cadenas JSON a objetos Python y viceversa.
3
12
  import json
4
- import time
13
+
14
+ # Módulo para manejo de logs (registro de eventos)
15
+ # Permite registrar alertas, información o errores en la consola o en archivos.
5
16
  import logging
17
+
18
+ # Tipado estático
19
+ # Permite indicar tipos de datos de variables o valores de retorno en funciones.
6
20
  from typing import Tuple
21
+
22
+ # Clase de Django para enviar respuestas HTTP en formato JSON
23
+ # Se usa para devolver mensajes al cliente en caso de error o detección de ataques.
7
24
  from django.http import JsonResponse
25
+
26
+ # Clase base para crear middlewares en Django (compatible con versiones antiguas)
27
+ # Permite definir métodos como process_request o process_response para interceptar solicitudes y respuestas.
8
28
  from django.utils.deprecation import MiddlewareMixin
29
+
30
+ # Permite acceder a las configuraciones de Django (settings.py)
31
+ # Se usa para obtener rutas excluidas u otras configuraciones personalizadas.
9
32
  from django.conf import settings
10
- from django.core.signing import TimestampSigner, BadSignature, SignatureExpired
11
33
 
12
- # ---------- Configuración de logging ----------
13
- logger = logging.getLogger("sqlidefense")
34
+
35
+ # ==============================
36
+ # CONFIGURACIÓN DEL LOG
37
+ # ==============================
38
+ logger = logging.getLogger(
39
+ "sqlidefense"
40
+ ) # logger para registrar eventos de SQL Injection
14
41
  logger.setLevel(logging.INFO)
15
42
  if not logger.handlers:
16
- handler = logging.StreamHandler() # en prod usa FileHandler/RotatingFileHandler
43
+ # Si no tiene manejadores, agregar uno por defecto a consola
44
+ handler = logging.StreamHandler()
17
45
  formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
18
46
  handler.setFormatter(formatter)
19
47
  logger.addHandler(handler)
20
48
 
21
- # ---------- Patrones de ataques SQL ----------
49
+ # ==============================
50
+ # PATRONES DE ATAQUE SQL
51
+ # ==============================
52
+ # Cada tupla contiene (expresión regular, descripción del ataque)
22
53
  PATTERNS = [
23
- (
24
- re.compile(r"\bunion\b\s+(all\s+)?\bselect\b", re.I),
25
- "Intento de UNION SELECT detectado",
26
- ),
54
+ (re.compile(r"\bunion\b\s+(all\s+)?\bselect\b", re.I), "UNION SELECT"),
27
55
  (
28
56
  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",
57
+ "SELECT con OR/AND",
34
58
  ),
59
+ (re.compile(r"\b(or|and)\s+\d+\s*=\s*\d+", re.I), "OR/AND 1=1"),
35
60
  (
36
61
  re.compile(r"\b(drop|truncate|delete|insert|update)\b", re.I),
37
- "Intento de manipulación de tabla detectado",
62
+ "Manipulación de tabla",
38
63
  ),
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"),
64
+ (re.compile(r"(--|#|;)", re.I), "Comentario o terminador sospechoso"),
65
+ (re.compile(r"exec\s*\(", re.I), "Ejecución de procedimiento"),
44
66
  ]
45
67
 
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)
68
+ # ==============================
69
+ # FUNCIONES AUXILIARES
70
+ # ==============================
54
71
 
55
- # JWT support (optional)
56
- try:
57
- from rest_framework_simplejwt.backends import TokenBackend
58
72
 
59
- SIMPLEJWT_AVAILABLE = True
60
- except Exception:
61
- SIMPLEJWT_AVAILABLE = False
62
-
63
-
64
- # ---------- Helpers ----------
65
73
  def extract_payload_text(request) -> str:
74
+ """
75
+ Extrae texto de la solicitud que será analizado por patrones SQL Injection.
76
+ Se considera:
77
+ - Cuerpo de la solicitud (JSON o texto plano)
78
+ - Query String (parámetros GET)
79
+ - User-Agent
80
+ - Referer
81
+ """
66
82
  parts = []
67
83
  content_type = request.META.get("CONTENT_TYPE", "")
84
+
68
85
  try:
86
+ # Si es JSON, decodificarlo
69
87
  if "application/json" in content_type:
70
88
  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
89
  parts.append(json.dumps(body_json))
76
90
  else:
77
91
  parts.append(request.body.decode("utf-8", errors="ignore"))
78
92
  except Exception:
93
+ # Ignorar errores al decodificar
79
94
  pass
80
95
 
96
+ # Agregar Query String
81
97
  if request.META.get("QUERY_STRING"):
82
98
  parts.append(request.META.get("QUERY_STRING"))
83
99
 
100
+ # Agregar User-Agent y Referer
84
101
  parts.append(request.META.get("HTTP_USER_AGENT", ""))
85
102
  parts.append(request.META.get("HTTP_REFERER", ""))
86
103
 
104
+ # Retornar todo el texto concatenado
87
105
  return " ".join([p for p in parts if p])
88
106
 
89
107
 
90
108
  def detect_sqli_text(text: str) -> Tuple[bool, list]:
109
+ """
110
+ Detecta si un texto contiene patrones de SQL Injection.
111
+ Retorna:
112
+ - flagged (bool): True si se detecta algún patrón
113
+ - matches (list): lista de descripciones de patrones detectados
114
+ """
91
115
  matches = []
92
116
  for patt, message in PATTERNS:
93
117
  if patt.search(text):
@@ -95,89 +119,51 @@ def detect_sqli_text(text: str) -> Tuple[bool, list]:
95
119
  return (len(matches) > 0, matches)
96
120
 
97
121
 
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")
122
+ # ==============================
123
+ # MIDDLEWARE
124
+ # ==============================
103
125
 
104
126
 
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
-
127
+ class SQLIDefenseMiddleware(MiddlewareMixin):
128
+ """
129
+ Middleware para proteger la aplicación contra ataques de SQL Injection.
130
+ Analiza cada solicitud entrante y bloquea si detecta patrones maliciosos,
131
+ excepto en rutas definidas como confiables en settings.SQLI_DEFENSE_EXCLUDED_PATHS.
132
+ """
124
133
 
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
134
  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
135
+ # Obtener rutas excluidas desde settings
136
+ excluded_paths = getattr(settings, "SQLI_DEFENSE_EXCLUDED_PATHS", [])
137
+
138
+ # Saltar verificación si la ruta está excluida
139
+ if any(request.path.startswith(p) for p in excluded_paths):
140
+ return None
141
+
142
+ # Extraer texto de la solicitud
164
143
  text = extract_payload_text(request)
165
144
  if not text:
166
145
  return None
167
146
 
168
- # 4) Detectar SQLi
147
+ # Detectar patrones SQL Injection
169
148
  flagged, matches = detect_sqli_text(text)
170
149
  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
- )
150
+ # Registrar evento en log
151
+ logger.warning(f"Ataque detectado: {matches}, payload: {text}")
152
+
153
+ # Bloquear la solicitud y devolver mensaje
175
154
  return JsonResponse(
176
- {
177
- "detail": "Request bloqueado: posible inyección SQL",
178
- "alerts": matches,
179
- },
180
- status=403,
155
+ {"mensaje": "Ataque detectado", "tipos": matches}, status=403
181
156
  )
182
157
 
183
158
  return None
159
+
160
+
161
+ """
162
+ Notas adicionales:
163
+ - Se puede aplicar cifrado AES-256 para guardar consultas auditadas.
164
+ - Se puede usar hash SHA-256 para verificar integridad de registros.
165
+ - Índice de amenaza:
166
+ S_sql = w_sql * detecciones_sql
167
+ donde w_sql es el peso asignado a SQL Injection
168
+ detecciones_sql es la cantidad de patrones detectados
169
+ """
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: GuardianUnivalle-Benito-Yucra
3
- Version: 0.1.11
3
+ Version: 0.1.13
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=jyFZYi_VjEF6jvDuUmDOGo5D5IgTzDtprfyaAO-jypU,6095
10
+ GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py,sha256=6fUm0ecbfaYnv_3PKyAPRf88jodqpBQ7glDAjIo17F0,5888
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.11.dist-info/licenses/LICENSE,sha256=5e4IdL542v1E8Ft0A24GZjrxZeTsVK7XrS3mZEUhPtM,37
17
- guardianunivalle_benito_yucra-0.1.11.dist-info/METADATA,sha256=yvOtVZ2eIA8Ztxo2_FjVU97mGetiT8KEr1QQ1iDHExA,1893
18
- guardianunivalle_benito_yucra-0.1.11.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
19
- guardianunivalle_benito_yucra-0.1.11.dist-info/top_level.txt,sha256=HTWfZM64WAV_QYr5cnXnLuabQt92dvlxqlR3pCwpbDQ,30
20
- guardianunivalle_benito_yucra-0.1.11.dist-info/RECORD,,
16
+ guardianunivalle_benito_yucra-0.1.13.dist-info/licenses/LICENSE,sha256=5e4IdL542v1E8Ft0A24GZjrxZeTsVK7XrS3mZEUhPtM,37
17
+ guardianunivalle_benito_yucra-0.1.13.dist-info/METADATA,sha256=tiFV5DaY10YDhl93panqR-ZXQ9XNCVsN6ckOGavSZm0,1893
18
+ guardianunivalle_benito_yucra-0.1.13.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
19
+ guardianunivalle_benito_yucra-0.1.13.dist-info/top_level.txt,sha256=HTWfZM64WAV_QYr5cnXnLuabQt92dvlxqlR3pCwpbDQ,30
20
+ guardianunivalle_benito_yucra-0.1.13.dist-info/RECORD,,