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

@@ -62,33 +62,17 @@ class SQLIDefenseMiddleware(MiddlewareMixin):
62
62
  def process_request(self, request):
63
63
  client_ip = get_client_ip(request)
64
64
  trusted_ips = getattr(settings, "SQLI_DEFENSE_TRUSTED_IPS", [])
65
- trusted_domains = getattr(settings, "SQLI_DEFENSE_TRUSTED_DOMAINS", [])
66
65
 
67
- # ✅ Si la IP está permitida → dejar pasar
68
66
  if client_ip in trusted_ips:
69
67
  return None
70
68
 
71
- # ✅ Revisar el dominio de origen
72
- origin = request.META.get("HTTP_ORIGIN", "")
73
- referer = request.META.get("HTTP_REFERER", "")
74
-
75
- # extraemos solo el host (sin protocolo http/https)
76
- def get_domain(url):
77
- return url.replace("http://", "").replace("https://", "").split("/")[0]
78
-
79
- origin_domain = get_domain(origin) if origin else ""
80
- referer_domain = get_domain(referer) if referer else ""
81
-
82
- if origin_domain in trusted_domains or referer_domain in trusted_domains:
83
- return None # → confiable, dejamos pasar
84
-
85
- # 🔍 Analizamos payload
86
69
  text = extract_payload_text(request)
87
70
  if not text:
88
71
  return None
89
72
 
90
73
  flagged, descripcion = detect_sql_attack(text)
91
74
  if flagged:
75
+ # Solo tipo SQL, descripción con los patrones detectados
92
76
  request.sql_attack_info = {
93
77
  "ip": client_ip,
94
78
  "tipos": ["SQL"],
@@ -100,4 +84,5 @@ class SQLIDefenseMiddleware(MiddlewareMixin):
100
84
  f"Ataque SQL detectado desde IP {client_ip}: {descripcion}, payload: {text}"
101
85
  )
102
86
 
87
+ # No devolvemos JsonResponse, solo marcamos el ataque
103
88
  return None
@@ -1,15 +1,163 @@
1
- import html
2
- from ..auditoria.registro_auditoria import registrar_evento
3
-
4
- def sanitizar_xss(entrada: str) -> str:
5
- return html.escape(entrada)
6
-
7
- def detectar_xss(entrada: str) -> bool:
8
- patrones = ["<script", "javascript:", "onerror", "onload"]
9
- if any(p in entrada.lower() for p in patrones):
10
- registrar_evento("XSS", f"Ataque detectado: {entrada}")
11
- return True
12
- return False
1
+ """
2
+ detector_xss.py (version separada con IPs confiables independientes)
3
+ """
4
+
5
+ from __future__ import annotations
6
+ import json
7
+ import logging
8
+ import re
9
+ from typing import List, Tuple
10
+
11
+ from django.conf import settings
12
+ from django.http import JsonResponse
13
+ from django.utils.deprecation import MiddlewareMixin
14
+
15
+ # Logger
16
+ logger = logging.getLogger("xssdefense")
17
+ logger.setLevel(logging.INFO)
18
+ if not logger.handlers:
19
+ handler = logging.StreamHandler()
20
+ handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
21
+ logger.addHandler(handler)
22
+
23
+ # Intentar usar bleach si está disponible
24
+ try:
25
+ import bleach
26
+
27
+ _BLEACH_AVAILABLE = True
28
+ except Exception:
29
+ _BLEACH_AVAILABLE = False
30
+
31
+ # Patrones de detección XSS
32
+ XSS_PATTERNS: List[Tuple[re.Pattern, str]] = [
33
+ (re.compile(r"<\s*script\b", re.I), "Etiqueta <script>"),
34
+ (re.compile(r"on\w+\s*=", re.I), "Atributo evento (on*)"),
35
+ (re.compile(r"javascript:\s*", re.I), "URI javascript:"),
36
+ (re.compile(r"<\s*iframe\b", re.I), "Etiqueta <iframe>"),
37
+ (re.compile(r"<\s*embed\b", re.I), "Etiqueta <embed>"),
38
+ ]
39
+
40
+
41
+ # Funciones auxiliares
42
+ def detect_xss_text(text: str) -> Tuple[bool, List[str]]:
43
+ matches: List[str] = []
44
+ if not text:
45
+ return False, matches
46
+ for patt, message in XSS_PATTERNS:
47
+ if patt.search(text):
48
+ matches.append(message)
49
+ return len(matches) > 0, matches
50
+
51
+
52
+ def sanitize_input_basic(text: str) -> str:
53
+ if text is None:
54
+ return text
55
+ if _BLEACH_AVAILABLE:
56
+ return bleach.clean(text, tags=[], attributes={}, protocols=[], strip=True)
57
+ replacements = [
58
+ ("&", "&amp;"),
59
+ ("<", "&lt;"),
60
+ (">", "&gt;"),
61
+ ('"', "&quot;"),
62
+ ("'", "&#x27;"),
63
+ ("/", "&#x2F;"),
64
+ ]
65
+ result = text
66
+ for old, new in replacements:
67
+ result = result.replace(old, new)
68
+ return result
69
+
70
+
71
+ def extract_payload_text(request) -> str:
72
+ parts: List[str] = []
73
+ try:
74
+ ct = request.META.get("CONTENT_TYPE", "")
75
+ if "application/json" in ct:
76
+ parts.append(
77
+ json.dumps(
78
+ json.loads(request.body.decode("utf-8") or "{}"), ensure_ascii=False
79
+ )
80
+ )
81
+ else:
82
+ parts.append(request.body.decode("utf-8", errors="ignore"))
83
+ except Exception:
84
+ pass
85
+ qs = request.META.get("QUERY_STRING", "")
86
+ if qs:
87
+ parts.append(qs)
88
+ parts.append(request.META.get("HTTP_USER_AGENT", ""))
89
+ parts.append(request.META.get("HTTP_REFERER", ""))
90
+ return " ".join([p for p in parts if p])
91
+
92
+
93
+ # Middleware XSS
94
+ class XSSDefenseMiddleware(MiddlewareMixin):
95
+ """
96
+ Middleware Django que detecta XSS en IPs no confiables.
97
+ """
98
+
99
+ def process_request(self, request):
100
+ # 1) Obtener IP confiable específica para XSS
101
+ trusted_ips: List[str] = getattr(settings, "XSS_DEFENSE_TRUSTED_IPS", [])
102
+ ip = request.META.get("REMOTE_ADDR", "")
103
+ if ip in trusted_ips:
104
+ return None # IP confiable → no analizar
105
+
106
+ # 2) Verificar rutas excluidas
107
+ excluded_paths: List[str] = getattr(settings, "XSS_DEFENSE_EXCLUDED_PATHS", [])
108
+ if any(request.path.startswith(p) for p in excluded_paths):
109
+ return None
110
+
111
+ # 3) Extraer payload
112
+ payload = extract_payload_text(request)
113
+ if not payload:
114
+ return None
115
+
116
+ # 4) Detectar XSS
117
+ flagged, matches = detect_xss_text(payload)
118
+ if not flagged:
119
+ return None
120
+
121
+ logger.warning(
122
+ "XSS detectado desde IP %s: %s ; payload truncated: %.200s",
123
+ ip,
124
+ matches,
125
+ payload,
126
+ )
127
+
128
+ # 5) Sanitizar si está configurado
129
+ if getattr(settings, "XSS_DEFENSE_SANITIZE_INPUT", False):
130
+ try:
131
+ if hasattr(request, "POST"):
132
+ mutable_post = request.POST.copy()
133
+ for k in mutable_post.keys():
134
+ mutable_post[k] = sanitize_input_basic(mutable_post.get(k))
135
+ request.POST = mutable_post
136
+ if hasattr(request, "GET"):
137
+ mutable_get = request.GET.copy()
138
+ for k in mutable_get.keys():
139
+ mutable_get[k] = sanitize_input_basic(mutable_get.get(k))
140
+ request.GET = mutable_get
141
+ except Exception:
142
+ logger.debug("Error sanitizando inputs; continuar")
143
+
144
+ # 6) Registrar ataque en AuditoriaMiddleware
145
+ request.sql_attack_info = {
146
+ "ip": ip,
147
+ "tipos": ["XSS"],
148
+ "descripcion": matches,
149
+ "payload": payload,
150
+ }
151
+
152
+ # 7) Bloquear petición si está configurado
153
+ if getattr(settings, "XSS_DEFENSE_BLOCK", True):
154
+ return JsonResponse(
155
+ {"mensaje": "Ataque detectado (XSS)", "tipos": matches}, status=403
156
+ )
157
+
158
+ return None
159
+
160
+
13
161
  """
14
162
  Algoritmos relacionados:
15
163
  *Guardar entradas sospechosas con AES-GCM para confidencialidad y autenticidad.
@@ -18,4 +166,4 @@ S_xss = w_xss * detecciones_xss
18
166
  S_xss = 0.3 * 2
19
167
  donde w_xss es peso asignado a XSS y detecciones_xss es la cantidad de patrones detectados.
20
168
 
21
- """
169
+ """
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: GuardianUnivalle-Benito-Yucra
3
- Version: 0.1.26
3
+ Version: 0.1.28
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=kOX-tVCSexUf4jvxM3jLl_jYBP_9YuF9-SQwLaLpAGg,3621
11
- GuardianUnivalle_Benito_Yucra/detectores/detector_xss.py,sha256=66V_xuxNOZEwluvWOT4-6pk5MJ3zWE1IwcVkBl7MZSg,719
10
+ GuardianUnivalle_Benito_Yucra/detectores/detector_sql.py,sha256=b7pd4-CTH0FqW5-dwA6RA38Dls0bSBXKSLlmnKbLnbA,2982
11
+ GuardianUnivalle_Benito_Yucra/detectores/detector_xss.py,sha256=S0E8myh4uKxYjXMDvG6i1nc66XgB0iKIRa-9gDJErdA,5411
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.26.dist-info/licenses/LICENSE,sha256=5e4IdL542v1E8Ft0A24GZjrxZeTsVK7XrS3mZEUhPtM,37
17
- guardianunivalle_benito_yucra-0.1.26.dist-info/METADATA,sha256=eTW0T-eW72Ycx5XPNt2VAWy0WgBV9bpY2FiSfPGzwKI,1893
18
- guardianunivalle_benito_yucra-0.1.26.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
19
- guardianunivalle_benito_yucra-0.1.26.dist-info/top_level.txt,sha256=HTWfZM64WAV_QYr5cnXnLuabQt92dvlxqlR3pCwpbDQ,30
20
- guardianunivalle_benito_yucra-0.1.26.dist-info/RECORD,,
16
+ guardianunivalle_benito_yucra-0.1.28.dist-info/licenses/LICENSE,sha256=5e4IdL542v1E8Ft0A24GZjrxZeTsVK7XrS3mZEUhPtM,37
17
+ guardianunivalle_benito_yucra-0.1.28.dist-info/METADATA,sha256=ljR3reAfOBK8g2jaAp6pbsG7BpTMcjNFoLK26q4v7PM,1893
18
+ guardianunivalle_benito_yucra-0.1.28.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
19
+ guardianunivalle_benito_yucra-0.1.28.dist-info/top_level.txt,sha256=HTWfZM64WAV_QYr5cnXnLuabQt92dvlxqlR3pCwpbDQ,30
20
+ guardianunivalle_benito_yucra-0.1.28.dist-info/RECORD,,