GuardianUnivalle-Benito-Yucra 0.1.46__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,152 @@
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
6
+ import platform
7
+ import requests
8
+ from django.utils.timezone import now
9
+ from user_agents import parse
4
10
 
5
11
  LOG_FILE = "auditoria_guardian.log"
6
12
 
13
+ # =====================================================
14
+ # === FUNCIONES DE CAPTURA Y ANÁLISIS DE CLIENTE ===
15
+ # =====================================================
7
16
 
8
- def registrar_evento(
9
- tipo: str,
10
- descripcion: str = "",
11
- severidad: str = "MEDIA",
12
- extra: dict | None = None,
13
- ):
17
+ def obtener_datos_maquina(request) -> dict:
18
+ """Obtiene información detallada del cliente desde la petición"""
14
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
+ )
26
+ ip = ip.split(",")[0].strip()
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)}
70
+
71
+
72
+ def analizar_comportamiento_cliente(datos_cliente: dict) -> tuple[str, str]:
73
+ """
74
+ Aplica reglas básicas de detección:
75
+ - IP sospechosa o repetitiva
76
+ - Agente extraño o vacío
77
+ - Peticiones sospechosas (ej: /admin, /etc/passwd)
78
+ Devuelve: (nivel_riesgo, descripcion)
79
+ """
80
+ descripcion = []
81
+ riesgo = "BAJO"
82
+
83
+ ip = datos_cliente.get("ip", "")
84
+ user_agent = datos_cliente.get("user_agent", "").lower()
85
+ ruta = datos_cliente.get("url", "")
86
+
87
+ # === Reglas simples ===
88
+ if not user_agent or "curl" in user_agent or "python" in user_agent:
89
+ descripcion.append("Agente de usuario anómalo (posible bot o script).")
90
+ riesgo = "MEDIO"
91
+
92
+ if "admin" in ruta or "etc/passwd" in ruta or "../" in ruta:
93
+ descripcion.append("Ruta sospechosa accedida.")
94
+ riesgo = "ALTO"
95
+
96
+ if "Desconocida" in ip or ip.startswith("192.168.") is False:
97
+ descripcion.append(f"IP externa detectada: {ip}")
98
+ riesgo = "MEDIO"
99
+
100
+ if not datos_cliente.get("url"):
101
+ descripcion.append("Petición sin parámetros ni cabeceras útiles.")
102
+ riesgo = "BAJO"
103
+
104
+ if not descripcion:
105
+ descripcion.append("Acceso normal detectado.")
106
+
107
+ return riesgo, " | ".join(descripcion)
108
+
109
+
110
+ # =====================================================
111
+ # === FUNCIÓN PRINCIPAL DE REGISTRO ===
112
+ # =====================================================
113
+ def registrar_evento(request, tipo: str = "ACCESO", extra: dict | None = None):
114
+ """
115
+ Registra un evento de auditoría detallado del cliente.
116
+ Incluye login exitoso, acceso normal y detección de ataques.
117
+ """
118
+ try:
119
+ datos_cliente = obtener_datos_maquina(request)
120
+ severidad, descripcion = analizar_comportamiento_cliente(datos_cliente)
121
+
15
122
  evento = {
16
123
  "fecha": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
17
124
  "tipo": tipo,
18
125
  "descripcion": descripcion,
19
126
  "severidad": severidad,
127
+ "cliente": datos_cliente,
20
128
  "extra": extra or {},
21
129
  }
22
130
 
23
- # Crear carpeta solo si hay directorio en la ruta
131
+ # Crear carpeta solo si hay directorio en la ruta
24
132
  log_dir = os.path.dirname(LOG_FILE)
25
133
  if log_dir:
26
134
  os.makedirs(log_dir, exist_ok=True)
27
135
 
136
+ # Registrar en archivo
28
137
  with open(LOG_FILE, "a", encoding="utf-8") as f:
29
138
  f.write(json.dumps(evento, ensure_ascii=False) + "\n")
30
139
 
140
+ # Log en consola para depuración local
141
+ print(f"[AUDITORÍA] Evento registrado: {evento['descripcion']} (nivel {severidad})")
142
+
31
143
  except Exception as e:
32
- print(f"[Auditoría] Error al registrar evento: {e}")
144
+ print(f"[AUDITORÍA] Error al registrar evento: {e}")
33
145
 
34
146
 
147
+ # =====================================================
148
+ # === CONSULTA DE REGISTROS (opcional) ===
149
+ # =====================================================
35
150
  def generar_reporte() -> str:
36
151
  """Devuelve todo el contenido del archivo de auditoría."""
37
152
  if not os.path.exists(LOG_FILE):
@@ -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.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,6 +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=NnKBOeRWkXVGaMBeQRYU528rWlaBDBPmTAzfji9n8fw,1135
3
+ GuardianUnivalle_Benito_Yucra/auditoria/registro_auditoria.py,sha256=eRCFhhon-eqeZvonc0xyfTolDP8QMM70Gl7smrYzvUQ,5460
4
4
  GuardianUnivalle_Benito_Yucra/criptografia/cifrado_aead.py,sha256=wfoRpaKvOqPbollNQsDNUNWClYJlXYTKTYvv0qcR6aI,962
5
5
  GuardianUnivalle_Benito_Yucra/criptografia/intercambio_claves.py,sha256=9djnlzb022hUhrDbQyWz7lWLbkn_vQZ4K7qar1FXYmo,829
6
6
  GuardianUnivalle_Benito_Yucra/criptografia/kdf.py,sha256=_sbepEY1qHEKga0ExrX2WRg1HeCPY5MC5CfXZWYyl-A,709
@@ -13,8 +13,8 @@ GuardianUnivalle_Benito_Yucra/middleware_web/middleware_web.py,sha256=23pLLYqliU
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.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,,
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,,