GuardianUnivalle-Benito-Yucra 0.1.47__py3-none-any.whl → 0.1.48__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,72 @@
1
+ # E:\EcuacionPotosi\GuardianUnivalle-Benito-Yucra\GuardianUnivalle_Benito_Yucra\auditoria\registro_auditoria.py
2
+
1
3
  import os
2
4
  import datetime
3
5
  import json
4
6
  import platform
5
- from django.utils import timezone
7
+ import requests
8
+ from django.utils.timezone import now
9
+ from user_agents import parse
6
10
 
7
11
  LOG_FILE = "auditoria_guardian.log"
8
12
 
9
13
  # =====================================================
10
14
  # === FUNCIONES DE CAPTURA Y ANÁLISIS DE CLIENTE ===
11
15
  # =====================================================
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
+
17
+ def obtener_datos_maquina(request) -> dict:
18
+ """Obtiene información detallada del cliente desde la petición"""
19
+ try:
20
+ # --- IP real ---
21
+ ip = (
22
+ request.META.get("HTTP_X_FORWARDED_FOR")
23
+ or request.META.get("REMOTE_ADDR")
24
+ or "0.0.0.0"
25
+ )
16
26
  ip = ip.split(",")[0].strip()
17
- else:
18
- ip = request.META.get("REMOTE_ADDR", "Desconocida")
19
-
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
- }
27
+
28
+ # --- User Agent ---
29
+ user_agent_str = request.META.get("HTTP_USER_AGENT", "Desconocido")
30
+ user_agent = parse(user_agent_str)
31
+ navegador = f"{user_agent.browser.family} {user_agent.browser.version_string}"
32
+ sistema = f"{user_agent.os.family} {user_agent.os.version_string}"
33
+
34
+ # --- Geolocalización (ipinfo.io gratuita) ---
35
+ geo_data = {}
36
+ try:
37
+ r = requests.get(f"https://ipinfo.io/{ip}/json", timeout=2)
38
+ if r.status_code == 200:
39
+ geo_data = r.json()
40
+ except Exception:
41
+ pass
42
+
43
+ pais = geo_data.get("country", "Desconocido")
44
+ ciudad = geo_data.get("city", "Desconocida")
45
+ isp = geo_data.get("org", "Desconocido")
46
+
47
+ # --- Usuario autenticado ---
48
+ usuario = "Anónimo"
49
+ if hasattr(request, "user") and request.user.is_authenticated:
50
+ usuario = getattr(request.user, "username", "Desconocido")
51
+
52
+ # --- Construir estructura ---
53
+ datos = {
54
+ "fecha": now().strftime("%Y-%m-%d %H:%M:%S"),
55
+ "ip": ip,
56
+ "pais": pais,
57
+ "ciudad": ciudad,
58
+ "isp": isp,
59
+ "usuario": usuario,
60
+ "user_agent": user_agent_str,
61
+ "navegador": navegador,
62
+ "sistema_operativo": sistema,
63
+ "url": request.path,
64
+ "metodo": request.method,
65
+ }
66
+
67
+ return datos
68
+ except Exception as e:
69
+ return {"error": str(e)}
35
70
 
36
71
 
37
72
  def analizar_comportamiento_cliente(datos_cliente: dict) -> tuple[str, str]:
@@ -45,9 +80,9 @@ def analizar_comportamiento_cliente(datos_cliente: dict) -> tuple[str, str]:
45
80
  descripcion = []
46
81
  riesgo = "BAJO"
47
82
 
48
- ip = datos_cliente.get("ip_cliente", "")
49
- user_agent = datos_cliente.get("navegador", "").lower()
50
- ruta = datos_cliente.get("ruta", "")
83
+ ip = datos_cliente.get("ip", "")
84
+ user_agent = datos_cliente.get("user_agent", "").lower()
85
+ ruta = datos_cliente.get("url", "")
51
86
 
52
87
  # === Reglas simples ===
53
88
  if not user_agent or "curl" in user_agent or "python" in user_agent:
@@ -62,8 +97,7 @@ def analizar_comportamiento_cliente(datos_cliente: dict) -> tuple[str, str]:
62
97
  descripcion.append(f"IP externa detectada: {ip}")
63
98
  riesgo = "MEDIO"
64
99
 
65
- # Comportamiento sin parámetros ni cabeceras
66
- if not datos_cliente.get("parametros"):
100
+ if not datos_cliente.get("url"):
67
101
  descripcion.append("Petición sin parámetros ni cabeceras útiles.")
68
102
  riesgo = "BAJO"
69
103
 
@@ -77,9 +111,12 @@ def analizar_comportamiento_cliente(datos_cliente: dict) -> tuple[str, str]:
77
111
  # === FUNCIÓN PRINCIPAL DE REGISTRO ===
78
112
  # =====================================================
79
113
  def registrar_evento(request, tipo: str = "ACCESO", extra: dict | None = None):
80
- """Registra un evento de auditoría detallado del cliente."""
114
+ """
115
+ Registra un evento de auditoría detallado del cliente.
116
+ Incluye login exitoso, acceso normal y detección de ataques.
117
+ """
81
118
  try:
82
- datos_cliente = capturar_datos_cliente(request)
119
+ datos_cliente = obtener_datos_maquina(request)
83
120
  severidad, descripcion = analizar_comportamiento_cliente(datos_cliente)
84
121
 
85
122
  evento = {
@@ -100,15 +137,15 @@ def registrar_evento(request, tipo: str = "ACCESO", extra: dict | None = None):
100
137
  with open(LOG_FILE, "a", encoding="utf-8") as f:
101
138
  f.write(json.dumps(evento, ensure_ascii=False) + "\n")
102
139
 
103
- # (Opcional) Log en consola
140
+ # Log en consola para depuración local
104
141
  print(f"[AUDITORÍA] Evento registrado: {evento['descripcion']} (nivel {severidad})")
105
142
 
106
143
  except Exception as e:
107
- print(f"[Auditoría] Error al registrar evento: {e}")
144
+ print(f"[AUDITORÍA] Error al registrar evento: {e}")
108
145
 
109
146
 
110
147
  # =====================================================
111
- # === CONSULTA DE REGISTROS ===
148
+ # === CONSULTA DE REGISTROS (opcional) ===
112
149
  # =====================================================
113
150
  def generar_reporte() -> str:
114
151
  """Devuelve todo el contenido del archivo de auditoría."""
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: GuardianUnivalle-Benito-Yucra
3
- Version: 0.1.47
3
+ Version: 0.1.48
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,7 +1,6 @@
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=SCNoMVsFkLwwAWWQoOhR_mQZO3idN0acIO8ltsh-cqk,4186
4
- GuardianUnivalle_Benito_Yucra/auditoria/utils_auditoria.py,sha256=HW-eBkwpanei4yeNOzzM54XdCtSQcjRdgsfBqLCrSnc,1932
3
+ GuardianUnivalle_Benito_Yucra/auditoria/registro_auditoria.py,sha256=eRCFhhon-eqeZvonc0xyfTolDP8QMM70Gl7smrYzvUQ,5460
5
4
  GuardianUnivalle_Benito_Yucra/criptografia/cifrado_aead.py,sha256=wfoRpaKvOqPbollNQsDNUNWClYJlXYTKTYvv0qcR6aI,962
6
5
  GuardianUnivalle_Benito_Yucra/criptografia/intercambio_claves.py,sha256=9djnlzb022hUhrDbQyWz7lWLbkn_vQZ4K7qar1FXYmo,829
7
6
  GuardianUnivalle_Benito_Yucra/criptografia/kdf.py,sha256=_sbepEY1qHEKga0ExrX2WRg1HeCPY5MC5CfXZWYyl-A,709
@@ -14,8 +13,8 @@ GuardianUnivalle_Benito_Yucra/middleware_web/middleware_web.py,sha256=23pLLYqliU
14
13
  GuardianUnivalle_Benito_Yucra/mitigacion/limitador_peticion.py,sha256=ipMOebYhql-6mSyHs0ddYXOcXq9w8P_IXLlpiIqGncw,246
15
14
  GuardianUnivalle_Benito_Yucra/mitigacion/lista_bloqueo.py,sha256=6AYWII4mrmwCLHCvGTyoBxR4Oasr4raSHpFbVjqn7d8,193
16
15
  GuardianUnivalle_Benito_Yucra/puntuacion/puntuacion_amenaza.py,sha256=Wx5XfcII4oweLvZsTBEJ7kUc9pMpP5-36RfI5C5KJXo,561
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,,
16
+ guardianunivalle_benito_yucra-0.1.48.dist-info/licenses/LICENSE,sha256=5e4IdL542v1E8Ft0A24GZjrxZeTsVK7XrS3mZEUhPtM,37
17
+ guardianunivalle_benito_yucra-0.1.48.dist-info/METADATA,sha256=7YzXLILaM6pcc97C0SYjCX7yhgvYtTucQQNNy72oQyg,1893
18
+ guardianunivalle_benito_yucra-0.1.48.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
19
+ guardianunivalle_benito_yucra-0.1.48.dist-info/top_level.txt,sha256=HTWfZM64WAV_QYr5cnXnLuabQt92dvlxqlR3pCwpbDQ,30
20
+ guardianunivalle_benito_yucra-0.1.48.dist-info/RECORD,,
@@ -1,57 +0,0 @@
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)}