GuardianUnivalle-Benito-Yucra 0.1.12__py3-none-any.whl → 0.1.14__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,20 +1,55 @@
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
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.
4
16
  import logging
17
+
18
+ # Tipado estático
19
+ # Permite indicar tipos de datos de variables o valores de retorno en funciones.
5
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.
6
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.
7
28
  from django.utils.deprecation import MiddlewareMixin
8
29
 
9
- logger = logging.getLogger("sqlidefense")
30
+ # Permite acceder a las configuraciones de Django (settings.py)
31
+ # Se usa para obtener rutas excluidas u otras configuraciones personalizadas.
32
+ from django.conf import settings
33
+
34
+
35
+ # ==============================
36
+ # CONFIGURACIÓN DEL LOG
37
+ # ==============================
38
+ logger = logging.getLogger(
39
+ "sqlidefense"
40
+ ) # logger para registrar eventos de SQL Injection
10
41
  logger.setLevel(logging.INFO)
11
42
  if not logger.handlers:
43
+ # Si no tiene manejadores, agregar uno por defecto a consola
12
44
  handler = logging.StreamHandler()
13
45
  formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
14
46
  handler.setFormatter(formatter)
15
47
  logger.addHandler(handler)
16
48
 
17
- # ---------- Patrones de ataques SQL ----------
49
+ # ==============================
50
+ # PATRONES DE ATAQUE SQL
51
+ # ==============================
52
+ # Cada tupla contiene (expresión regular, descripción del ataque)
18
53
  PATTERNS = [
19
54
  (re.compile(r"\bunion\b\s+(all\s+)?\bselect\b", re.I), "UNION SELECT"),
20
55
  (
@@ -30,27 +65,53 @@ PATTERNS = [
30
65
  (re.compile(r"exec\s*\(", re.I), "Ejecución de procedimiento"),
31
66
  ]
32
67
 
68
+ # ==============================
69
+ # FUNCIONES AUXILIARES
70
+ # ==============================
71
+
33
72
 
34
- # ---------- Helpers ----------
35
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
+ """
36
82
  parts = []
37
83
  content_type = request.META.get("CONTENT_TYPE", "")
84
+
38
85
  try:
86
+ # Si es JSON, decodificarlo
39
87
  if "application/json" in content_type:
40
88
  body_json = json.loads(request.body.decode("utf-8") or "{}")
41
89
  parts.append(json.dumps(body_json))
42
90
  else:
43
91
  parts.append(request.body.decode("utf-8", errors="ignore"))
44
92
  except Exception:
93
+ # Ignorar errores al decodificar
45
94
  pass
95
+
96
+ # Agregar Query String
46
97
  if request.META.get("QUERY_STRING"):
47
98
  parts.append(request.META.get("QUERY_STRING"))
99
+
100
+ # Agregar User-Agent y Referer
48
101
  parts.append(request.META.get("HTTP_USER_AGENT", ""))
49
102
  parts.append(request.META.get("HTTP_REFERER", ""))
103
+
104
+ # Retornar todo el texto concatenado
50
105
  return " ".join([p for p in parts if p])
51
106
 
52
107
 
53
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
+ """
54
115
  matches = []
55
116
  for patt, message in PATTERNS:
56
117
  if patt.search(text):
@@ -58,18 +119,51 @@ def detect_sqli_text(text: str) -> Tuple[bool, list]:
58
119
  return (len(matches) > 0, matches)
59
120
 
60
121
 
61
- # ---------- Middleware ----------
122
+ def get_client_ip(request):
123
+ # Primero verifica si hay proxy inverso (X-Forwarded-For)
124
+ x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
125
+ if x_forwarded_for:
126
+ ip = x_forwarded_for.split(",")[0] # Tomar la primera IP
127
+ else:
128
+ ip = request.META.get("REMOTE_ADDR") # IP directa
129
+ return ip
130
+
131
+
132
+ # ==============================
133
+ # MIDDLEWARE
134
+ # ==============================
135
+
136
+
62
137
  class SQLIDefenseMiddleware(MiddlewareMixin):
63
138
  def process_request(self, request):
139
+ excluded_paths = getattr(settings, "SQLI_DEFENSE_EXCLUDED_PATHS", [])
140
+ if any(request.path.startswith(p) for p in excluded_paths):
141
+ return None
142
+
64
143
  text = extract_payload_text(request)
65
144
  if not text:
66
145
  return None
67
146
 
68
147
  flagged, matches = detect_sqli_text(text)
69
148
  if flagged:
70
- logger.warning(f"Ataque detectado: {matches}, payload: {text}")
71
- return JsonResponse(
72
- {"mensaje": "Ataque detectado", "tipos": matches}, status=403
149
+ client_ip = get_client_ip(request) # obtener IP del atacante
150
+ logger.warning(
151
+ f"Ataque detectado desde IP {client_ip}: {matches}, payload: {text}"
73
152
  )
74
153
 
154
+ return JsonResponse(
155
+ {"mensaje": "Ataque detectado", "tipos": matches, "ip": client_ip},
156
+ status=403,
157
+ )
75
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.12
3
+ Version: 0.1.14
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=Sr2gGAKPgOA8FUwyrMDU2q7h91lY5KWs0Xwhm0B3RKg,2536
10
+ GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py,sha256=ba413KfYR30kLQdKGPXHOvn8udQY1mRtcL5rlEEHqSY,5832
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.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,,
16
+ guardianunivalle_benito_yucra-0.1.14.dist-info/licenses/LICENSE,sha256=5e4IdL542v1E8Ft0A24GZjrxZeTsVK7XrS3mZEUhPtM,37
17
+ guardianunivalle_benito_yucra-0.1.14.dist-info/METADATA,sha256=IkoT6t0h5mzecBQ9UMsrp0_5qt5ny89AGM8ey2IHXYc,1893
18
+ guardianunivalle_benito_yucra-0.1.14.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
19
+ guardianunivalle_benito_yucra-0.1.14.dist-info/top_level.txt,sha256=HTWfZM64WAV_QYr5cnXnLuabQt92dvlxqlR3pCwpbDQ,30
20
+ guardianunivalle_benito_yucra-0.1.14.dist-info/RECORD,,