GuardianUnivalle-Benito-Yucra 0.1.46__py3-none-any.whl → 0.1.47__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,37 +1,115 @@
1
1
  import os
2
2
  import datetime
3
3
  import json
4
+ import platform
5
+ from django.utils import timezone
4
6
 
5
7
  LOG_FILE = "auditoria_guardian.log"
6
8
 
9
+ # =====================================================
10
+ # === FUNCIONES DE CAPTURA Y ANÁLISIS DE CLIENTE ===
11
+ # =====================================================
12
+ def capturar_datos_cliente(request) -> dict:
13
+ """Extrae información útil del cliente que accede al sistema."""
14
+ ip = request.META.get("HTTP_X_FORWARDED_FOR")
15
+ if ip:
16
+ ip = ip.split(",")[0].strip()
17
+ else:
18
+ ip = request.META.get("REMOTE_ADDR", "Desconocida")
7
19
 
8
- def registrar_evento(
9
- tipo: str,
10
- descripcion: str = "",
11
- severidad: str = "MEDIA",
12
- extra: dict | None = None,
13
- ):
20
+ user_agent = request.META.get("HTTP_USER_AGENT", "Desconocido")
21
+ metodo = request.method
22
+ ruta = request.path
23
+ parametros = request.GET.dict() if metodo == "GET" else request.POST.dict()
24
+ so_servidor = platform.system()
25
+
26
+ return {
27
+ "ip_cliente": ip,
28
+ "navegador": user_agent,
29
+ "metodo": metodo,
30
+ "ruta": ruta,
31
+ "parametros": parametros,
32
+ "servidor_os": so_servidor,
33
+ "hora_servidor": timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
34
+ }
35
+
36
+
37
+ def analizar_comportamiento_cliente(datos_cliente: dict) -> tuple[str, str]:
38
+ """
39
+ Aplica reglas básicas de detección:
40
+ - IP sospechosa o repetitiva
41
+ - Agente extraño o vacío
42
+ - Peticiones sospechosas (ej: /admin, /etc/passwd)
43
+ Devuelve: (nivel_riesgo, descripcion)
44
+ """
45
+ descripcion = []
46
+ riesgo = "BAJO"
47
+
48
+ ip = datos_cliente.get("ip_cliente", "")
49
+ user_agent = datos_cliente.get("navegador", "").lower()
50
+ ruta = datos_cliente.get("ruta", "")
51
+
52
+ # === Reglas simples ===
53
+ if not user_agent or "curl" in user_agent or "python" in user_agent:
54
+ descripcion.append("Agente de usuario anómalo (posible bot o script).")
55
+ riesgo = "MEDIO"
56
+
57
+ if "admin" in ruta or "etc/passwd" in ruta or "../" in ruta:
58
+ descripcion.append("Ruta sospechosa accedida.")
59
+ riesgo = "ALTO"
60
+
61
+ if "Desconocida" in ip or ip.startswith("192.168.") is False:
62
+ descripcion.append(f"IP externa detectada: {ip}")
63
+ riesgo = "MEDIO"
64
+
65
+ # Comportamiento sin parámetros ni cabeceras
66
+ if not datos_cliente.get("parametros"):
67
+ descripcion.append("Petición sin parámetros ni cabeceras útiles.")
68
+ riesgo = "BAJO"
69
+
70
+ if not descripcion:
71
+ descripcion.append("Acceso normal detectado.")
72
+
73
+ return riesgo, " | ".join(descripcion)
74
+
75
+
76
+ # =====================================================
77
+ # === FUNCIÓN PRINCIPAL DE REGISTRO ===
78
+ # =====================================================
79
+ def registrar_evento(request, tipo: str = "ACCESO", extra: dict | None = None):
80
+ """Registra un evento de auditoría detallado del cliente."""
14
81
  try:
82
+ datos_cliente = capturar_datos_cliente(request)
83
+ severidad, descripcion = analizar_comportamiento_cliente(datos_cliente)
84
+
15
85
  evento = {
16
86
  "fecha": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
17
87
  "tipo": tipo,
18
88
  "descripcion": descripcion,
19
89
  "severidad": severidad,
90
+ "cliente": datos_cliente,
20
91
  "extra": extra or {},
21
92
  }
22
93
 
23
- # Crear carpeta solo si hay directorio en la ruta
94
+ # Crear carpeta solo si hay directorio en la ruta
24
95
  log_dir = os.path.dirname(LOG_FILE)
25
96
  if log_dir:
26
97
  os.makedirs(log_dir, exist_ok=True)
27
98
 
99
+ # Registrar en archivo
28
100
  with open(LOG_FILE, "a", encoding="utf-8") as f:
29
101
  f.write(json.dumps(evento, ensure_ascii=False) + "\n")
30
102
 
103
+ # (Opcional) Log en consola
104
+ print(f"[AUDITORÍA] Evento registrado: {evento['descripcion']} (nivel {severidad})")
105
+
31
106
  except Exception as e:
32
107
  print(f"[Auditoría] Error al registrar evento: {e}")
33
108
 
34
109
 
110
+ # =====================================================
111
+ # === CONSULTA DE REGISTROS ===
112
+ # =====================================================
35
113
  def generar_reporte() -> str:
36
114
  """Devuelve todo el contenido del archivo de auditoría."""
37
115
  if not os.path.exists(LOG_FILE):
@@ -0,0 +1,57 @@
1
+ import requests
2
+ from django.utils.timezone import now
3
+ from user_agents import parse
4
+
5
+ def obtener_datos_maquina(request):
6
+ """Obtiene información detallada del cliente desde la petición"""
7
+ try:
8
+ # --- IP real ---
9
+ ip = (
10
+ request.META.get("HTTP_X_FORWARDED_FOR")
11
+ or request.META.get("REMOTE_ADDR")
12
+ or "0.0.0.0"
13
+ )
14
+ ip = ip.split(",")[0].strip()
15
+
16
+ # --- User Agent ---
17
+ user_agent_str = request.META.get("HTTP_USER_AGENT", "Desconocido")
18
+ user_agent = parse(user_agent_str)
19
+ navegador = f"{user_agent.browser.family} {user_agent.browser.version_string}"
20
+ sistema = f"{user_agent.os.family} {user_agent.os.version_string}"
21
+
22
+ # --- Geolocalización (usando ipinfo.io gratuita) ---
23
+ geo_data = {}
24
+ try:
25
+ r = requests.get(f"https://ipinfo.io/{ip}/json", timeout=2)
26
+ if r.status_code == 200:
27
+ geo_data = r.json()
28
+ except Exception:
29
+ pass
30
+
31
+ pais = geo_data.get("country", "Desconocido")
32
+ ciudad = geo_data.get("city", "Desconocida")
33
+ isp = geo_data.get("org", "Desconocido")
34
+
35
+ # --- Usuario autenticado ---
36
+ usuario = "Anónimo"
37
+ if request.user and request.user.is_authenticated:
38
+ usuario = request.user.username
39
+
40
+ # --- Construir estructura ---
41
+ datos = {
42
+ "fecha": now().strftime("%Y-%m-%d %H:%M:%S"),
43
+ "ip": ip,
44
+ "pais": pais,
45
+ "ciudad": ciudad,
46
+ "isp": isp,
47
+ "usuario": usuario,
48
+ "user_agent": user_agent_str,
49
+ "navegador": navegador,
50
+ "sistema_operativo": sistema,
51
+ "url": request.path,
52
+ "metodo": request.method,
53
+ }
54
+
55
+ return datos
56
+ except Exception as e:
57
+ return {"error": str(e)}
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: GuardianUnivalle-Benito-Yucra
3
- Version: 0.1.46
3
+ Version: 0.1.47
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,7 @@
1
1
  GuardianUnivalle_Benito_Yucra/__init__.py,sha256=lbIRb8fCFYfAdyJV6NsYVZJ5pKYSJZKhhK-En9g_1M8,762
2
2
  GuardianUnivalle_Benito_Yucra/utilidades.py,sha256=lFNVnlyTSYmQ1CqtmHx6aefK5uNw0wsMdHRQyxAIZy0,120
3
- GuardianUnivalle_Benito_Yucra/auditoria/registro_auditoria.py,sha256=NnKBOeRWkXVGaMBeQRYU528rWlaBDBPmTAzfji9n8fw,1135
3
+ GuardianUnivalle_Benito_Yucra/auditoria/registro_auditoria.py,sha256=SCNoMVsFkLwwAWWQoOhR_mQZO3idN0acIO8ltsh-cqk,4186
4
+ GuardianUnivalle_Benito_Yucra/auditoria/utils_auditoria.py,sha256=HW-eBkwpanei4yeNOzzM54XdCtSQcjRdgsfBqLCrSnc,1932
4
5
  GuardianUnivalle_Benito_Yucra/criptografia/cifrado_aead.py,sha256=wfoRpaKvOqPbollNQsDNUNWClYJlXYTKTYvv0qcR6aI,962
5
6
  GuardianUnivalle_Benito_Yucra/criptografia/intercambio_claves.py,sha256=9djnlzb022hUhrDbQyWz7lWLbkn_vQZ4K7qar1FXYmo,829
6
7
  GuardianUnivalle_Benito_Yucra/criptografia/kdf.py,sha256=_sbepEY1qHEKga0ExrX2WRg1HeCPY5MC5CfXZWYyl-A,709
@@ -13,8 +14,8 @@ GuardianUnivalle_Benito_Yucra/middleware_web/middleware_web.py,sha256=23pLLYqliU
13
14
  GuardianUnivalle_Benito_Yucra/mitigacion/limitador_peticion.py,sha256=ipMOebYhql-6mSyHs0ddYXOcXq9w8P_IXLlpiIqGncw,246
14
15
  GuardianUnivalle_Benito_Yucra/mitigacion/lista_bloqueo.py,sha256=6AYWII4mrmwCLHCvGTyoBxR4Oasr4raSHpFbVjqn7d8,193
15
16
  GuardianUnivalle_Benito_Yucra/puntuacion/puntuacion_amenaza.py,sha256=Wx5XfcII4oweLvZsTBEJ7kUc9pMpP5-36RfI5C5KJXo,561
16
- guardianunivalle_benito_yucra-0.1.46.dist-info/licenses/LICENSE,sha256=5e4IdL542v1E8Ft0A24GZjrxZeTsVK7XrS3mZEUhPtM,37
17
- guardianunivalle_benito_yucra-0.1.46.dist-info/METADATA,sha256=aIfr2HSuO_Tvo3Tvpt3NvLsUA-WG7bBssHew8xnpaXY,1893
18
- guardianunivalle_benito_yucra-0.1.46.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
19
- guardianunivalle_benito_yucra-0.1.46.dist-info/top_level.txt,sha256=HTWfZM64WAV_QYr5cnXnLuabQt92dvlxqlR3pCwpbDQ,30
20
- guardianunivalle_benito_yucra-0.1.46.dist-info/RECORD,,
17
+ guardianunivalle_benito_yucra-0.1.47.dist-info/licenses/LICENSE,sha256=5e4IdL542v1E8Ft0A24GZjrxZeTsVK7XrS3mZEUhPtM,37
18
+ guardianunivalle_benito_yucra-0.1.47.dist-info/METADATA,sha256=TRIUZSV5Hpy1gjyiK67nL6krzW_qEZfrnAvQ8kAsNl0,1893
19
+ guardianunivalle_benito_yucra-0.1.47.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
20
+ guardianunivalle_benito_yucra-0.1.47.dist-info/top_level.txt,sha256=HTWfZM64WAV_QYr5cnXnLuabQt92dvlxqlR3pCwpbDQ,30
21
+ guardianunivalle_benito_yucra-0.1.47.dist-info/RECORD,,