winlog-hunter 0.2.0__tar.gz
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.
- winlog_hunter-0.2.0/LICENSE +21 -0
- winlog_hunter-0.2.0/PKG-INFO +215 -0
- winlog_hunter-0.2.0/README.md +187 -0
- winlog_hunter-0.2.0/pyproject.toml +41 -0
- winlog_hunter-0.2.0/setup.cfg +4 -0
- winlog_hunter-0.2.0/src/winlog_hunter/__init__.py +3 -0
- winlog_hunter-0.2.0/src/winlog_hunter/__main__.py +3 -0
- winlog_hunter-0.2.0/src/winlog_hunter/cli.py +153 -0
- winlog_hunter-0.2.0/src/winlog_hunter/models.py +64 -0
- winlog_hunter-0.2.0/src/winlog_hunter/parsers.py +374 -0
- winlog_hunter-0.2.0/src/winlog_hunter/report.py +284 -0
- winlog_hunter-0.2.0/src/winlog_hunter/rules.py +1111 -0
- winlog_hunter-0.2.0/src/winlog_hunter.egg-info/PKG-INFO +215 -0
- winlog_hunter-0.2.0/src/winlog_hunter.egg-info/SOURCES.txt +20 -0
- winlog_hunter-0.2.0/src/winlog_hunter.egg-info/dependency_links.txt +1 -0
- winlog_hunter-0.2.0/src/winlog_hunter.egg-info/entry_points.txt +2 -0
- winlog_hunter-0.2.0/src/winlog_hunter.egg-info/requires.txt +3 -0
- winlog_hunter-0.2.0/src/winlog_hunter.egg-info/top_level.txt +1 -0
- winlog_hunter-0.2.0/tests/test_parsers.py +135 -0
- winlog_hunter-0.2.0/tests/test_report_cli.py +84 -0
- winlog_hunter-0.2.0/tests/test_rules.py +246 -0
- winlog_hunter-0.2.0/tests/test_sigma.py +28 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bryan Valenzuela
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: winlog-hunter
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Detección de amenazas en logs de Windows (Security, System, Sysmon, PowerShell) mapeada a MITRE ATT&CK
|
|
5
|
+
Author: Bryan Valenzuela
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/BV-cs0/winlog-hunter
|
|
8
|
+
Project-URL: Source, https://github.com/BV-cs0/winlog-hunter
|
|
9
|
+
Project-URL: Issues, https://github.com/BV-cs0/winlog-hunter/issues
|
|
10
|
+
Keywords: blue-team,soc,dfir,windows,sysmon,mitre-attack,threat-hunting
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Topic :: Security
|
|
17
|
+
Classifier: Topic :: System :: Logging
|
|
18
|
+
Classifier: Environment :: Console
|
|
19
|
+
Classifier: Intended Audience :: Information Technology
|
|
20
|
+
Classifier: Intended Audience :: System Administrators
|
|
21
|
+
Classifier: Natural Language :: Spanish
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Provides-Extra: evtx
|
|
26
|
+
Requires-Dist: python-evtx>=0.7; extra == "evtx"
|
|
27
|
+
Dynamic: license-file
|
|
28
|
+
|
|
29
|
+
# winlog-hunter
|
|
30
|
+
|
|
31
|
+
Analizador de logs de Windows para blue team. Lee eventos de **Security**, **System**, **Sysmon** y **PowerShell**, detecta actividad sospechosa con 21 reglas y genera un informe con cada hallazgo mapeado a **MITRE ATT&CK**. Las reglas también están en formato **Sigma** para usarlas en cualquier SIEM.
|
|
32
|
+
|
|
33
|
+

|
|
34
|
+
|
|
35
|
+
## Instalación
|
|
36
|
+
|
|
37
|
+
Necesitas Python 3.9 o superior y git.
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
git clone https://github.com/BV-cs0/winlog-hunter.git
|
|
41
|
+
cd winlog-hunter
|
|
42
|
+
python -m pip install .
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Uso
|
|
46
|
+
|
|
47
|
+
**1. Abre PowerShell como administrador** y entra en la carpeta del proyecto:
|
|
48
|
+
|
|
49
|
+
```powershell
|
|
50
|
+
cd winlog-hunter
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
**2. Genera el informe** con los logs de las últimas 24 horas de tu equipo:
|
|
54
|
+
|
|
55
|
+
```powershell
|
|
56
|
+
powershell -ExecutionPolicy Bypass -File .\scripts\analisis-diario.ps1
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
**3. Abre el informe.** Se guarda en `Documentos\winlog-hunter` con la fecha en el nombre:
|
|
60
|
+
|
|
61
|
+
```powershell
|
|
62
|
+
start $HOME\Documents\winlog-hunter
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
> Para analizar más tiempo añade `-Horas 72`. Sin administrador también funciona, pero se omite el log Security.
|
|
66
|
+
|
|
67
|
+
## Detecciones
|
|
68
|
+
|
|
69
|
+
| ID | Detección | Eventos | MITRE ATT&CK |
|
|
70
|
+
|---|---|---|---|
|
|
71
|
+
| WLH-001 | Fuerza bruta (muchos fallos, misma cuenta y origen) | 4625 | T1110.001 |
|
|
72
|
+
| WLH-002 | Password spraying (un origen, muchas cuentas) | 4625 | T1110.003 |
|
|
73
|
+
| WLH-003 | Inicio de sesión correcto justo después de una fuerza bruta | 4625 → 4624 | T1110, T1078 |
|
|
74
|
+
| WLH-004 | Movimiento lateral (misma cuenta en varios equipos) | 4624 tipo 3/10 | T1021 |
|
|
75
|
+
| WLH-005 | Registro de eventos borrado | 1102, 104 | T1685.005 |
|
|
76
|
+
| WLH-006 | Servicio nuevo; alta si es PsExec o ejecuta algo sospechoso | 7045 | T1543.003, T1569.002 |
|
|
77
|
+
| WLH-007 | Tarea programada; alta si lanza PowerShell, scripts o rutas raras | 4698 | T1053.005 |
|
|
78
|
+
| WLH-008 | Cuenta de usuario creada | 4720 | T1136 |
|
|
79
|
+
| WLH-009 | Alta en grupo privilegiado (por SID, vale en cualquier idioma) | 4728, 4732, 4756 | T1098 |
|
|
80
|
+
| WLH-010 | PowerShell sospechoso; decodifica `-EncodedCommand` | Sysmon 1, 4688 | T1059.001 |
|
|
81
|
+
| WLH-011 | LOLBins: certutil, mshta, rundll32, regsvr32, bitsadmin, wmic | Sysmon 1, 4688 | T1218, T1105, T1197, T1047 |
|
|
82
|
+
| WLH-012 | Office (Word, Excel, Outlook...) lanzando una shell | Sysmon 1, 4688 | T1566.001, T1204.002 |
|
|
83
|
+
| WLH-013 | Acceso a la memoria de LSASS (Mimikatz, procdump...) | Sysmon 10 | T1003.001 |
|
|
84
|
+
| WLH-014 | Comandos de volcado: comsvcs MiniDump, ntdsutil, reg save SAM | Sysmon 1, 4688 | T1003.001-.003 |
|
|
85
|
+
| WLH-015 | DCSync: replicación de AD pedida por un usuario | 4662 | T1003.006 |
|
|
86
|
+
| WLH-016 | Kerberoasting: tickets de servicio RC4 | 4769 | T1558.003 |
|
|
87
|
+
| WLH-017 | Ejecución remota por SMB: PsExec, svcctl, atsvc, copia a ADMIN$ | 5145 | T1021.002, T1569.002 |
|
|
88
|
+
| WLH-018 | Shell lanzada por WMI o WinRM (wmiexec, Invoke-Command) | Sysmon 1, 4688 | T1047, T1021.006 |
|
|
89
|
+
| WLH-019 | Persistencia en el registro: Run, Winlogon, IFEO, COM, LSA, SAM | Sysmon 13 | T1547, T1546 |
|
|
90
|
+
| WLH-020 | Persistencia con suscripciones WMI | Sysmon 19-21 | T1546.003 |
|
|
91
|
+
| WLH-021 | Script de PowerShell malicioso: volcado de LSASS, AMSI, inyección | 4104 | T1059.001, T1003.001 |
|
|
92
|
+
|
|
93
|
+
Para reducir falsos positivos, la severidad depende del contexto: un servicio o una tarea normales salen como *baja*, y uno que ejecuta `powershell -enc` sale como *alta*. Los ataques en ráfaga (500 intentos de contraseña) se agrupan en un único hallazgo.
|
|
94
|
+
|
|
95
|
+
## Resultados con ataques reales
|
|
96
|
+
|
|
97
|
+
winlog-hunter se ha probado con [EVTX-ATTACK-SAMPLES](https://github.com/sbousseaden/EVTX-ATTACK-SAMPLES): 278 ficheros `.evtx` grabados en laboratorio mientras se ejecutaban ataques reales, organizados por táctica.
|
|
98
|
+
|
|
99
|
+
| Táctica | Ficheros | Detectados |
|
|
100
|
+
|---|---|---|
|
|
101
|
+
| Credential Access | 39 | 14 |
|
|
102
|
+
| Lateral Movement | 47 | 13 |
|
|
103
|
+
| Persistence | 22 | 12 |
|
|
104
|
+
| Execution | 34 | 7 |
|
|
105
|
+
| Herramientas de pruebas automatizadas | 8 | 5 |
|
|
106
|
+
| Privilege Escalation | 66 | 3 |
|
|
107
|
+
| Defense Evasion | 36 | 2 |
|
|
108
|
+
| Discovery | 11 | 1 |
|
|
109
|
+
| Command and Control | 6 | 0 |
|
|
110
|
+
| Otros | 9 | 1 |
|
|
111
|
+
| **Total** | **278** | **58** |
|
|
112
|
+
|
|
113
|
+
No se cuentan los ficheros en los que solo salta *registro borrado*, porque el autor vació los logs antes de grabar cada ataque.
|
|
114
|
+
|
|
115
|
+
Los puntos débiles son claros: la **escalada de privilegios** (bypass de UAC, tokens, servicios vulnerables) y la **evasión de defensas**. Casi todos esos ataques necesitan reglas de Sysmon 7 (carga de DLL), 8 (hilos remotos) y 11 (ficheros creados), que aún no están implementadas.
|
|
116
|
+
|
|
117
|
+
## Activar Sysmon (recomendado)
|
|
118
|
+
|
|
119
|
+
Sin Sysmon, Windows no registra los procesos que se ejecutan, los accesos a LSASS ni los cambios en el registro, así que 9 de las 21 reglas no tienen datos. Sysmon es gratuito y de Microsoft. En PowerShell como administrador:
|
|
120
|
+
|
|
121
|
+
```powershell
|
|
122
|
+
# 1. Descargar Sysmon y una configuración probada (la de SwiftOnSecurity)
|
|
123
|
+
Invoke-WebRequest https://download.sysinternals.com/files/Sysmon.zip -OutFile $env:TEMP\Sysmon.zip
|
|
124
|
+
Expand-Archive $env:TEMP\Sysmon.zip $env:TEMP\Sysmon -Force
|
|
125
|
+
Invoke-WebRequest https://raw.githubusercontent.com/SwiftOnSecurity/sysmon-config/master/sysmonconfig-export.xml -OutFile $env:TEMP\sysmon.xml
|
|
126
|
+
|
|
127
|
+
# 2. Instalarlo
|
|
128
|
+
& $env:TEMP\Sysmon\Sysmon64.exe -accepteula -i $env:TEMP\sysmon.xml
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
Para la regla WLH-021, activa también el registro de bloques de script de PowerShell:
|
|
132
|
+
|
|
133
|
+
```powershell
|
|
134
|
+
New-Item -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging -Force |
|
|
135
|
+
New-ItemProperty -Name EnableScriptBlockLogging -Value 1 -PropertyType DWord -Force
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
El análisis diario incluye Sysmon y PowerShell en cuanto existen.
|
|
139
|
+
|
|
140
|
+
## Cómo sacar los logs de un equipo Windows manualmente
|
|
141
|
+
|
|
142
|
+
Para analizar otro equipo, o un log concreto, expórtalo y pásaselo a winlog-hunter:
|
|
143
|
+
|
|
144
|
+
```powershell
|
|
145
|
+
# 1. Exportar los logs (Security requiere administrador)
|
|
146
|
+
wevtutil epl Security C:\temp\Security.evtx
|
|
147
|
+
wevtutil epl System C:\temp\System.evtx
|
|
148
|
+
|
|
149
|
+
# 2. Analizarlos y guardar el informe
|
|
150
|
+
winlog-hunter analyze C:\temp\Security.evtx C:\temp\System.evtx -o informe.html
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
El formato del informe se elige por la extensión: `.html`, `.md` o `.json`. También acepta `.xml` de `wevtutil qe` y JSON de Winlogbeat o de un SIEM. En Linux/macOS, para leer `.evtx` instala antes `python3 -m pip install ".[evtx]"`.
|
|
154
|
+
|
|
155
|
+
## Análisis automático diario del propio equipo (Windows)
|
|
156
|
+
|
|
157
|
+
Para que el informe se genere solo cada día, en PowerShell **como administrador**:
|
|
158
|
+
|
|
159
|
+
```powershell
|
|
160
|
+
# Programarlo cada día a las 09:00
|
|
161
|
+
powershell -ExecutionPolicy Bypass -File .\scripts\instalar-tarea.ps1
|
|
162
|
+
|
|
163
|
+
# A otra hora
|
|
164
|
+
powershell -ExecutionPolicy Bypass -File .\scripts\instalar-tarea.ps1 -Hora 21:30
|
|
165
|
+
|
|
166
|
+
# Lanzarlo ahora sin esperar
|
|
167
|
+
Start-ScheduledTask -TaskName 'winlog-hunter diario'
|
|
168
|
+
|
|
169
|
+
# Quitarlo
|
|
170
|
+
powershell -ExecutionPolicy Bypass -File .\scripts\instalar-tarea.ps1 -Desinstalar
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
- Si hay algún hallazgo **crítico**, aparece un aviso en pantalla con el resumen y la ruta del informe.
|
|
174
|
+
- Los informes se guardan en `Documentos\winlog-hunter` y los de más de 30 días se borran solos.
|
|
175
|
+
- `ejecuciones.log`, en la misma carpeta, guarda un resumen de cada ejecución.
|
|
176
|
+
- Si el equipo está apagado a la hora programada, se ejecuta al encenderlo.
|
|
177
|
+
- Si mueves la carpeta del proyecto, vuelve a ejecutar el instalador.
|
|
178
|
+
|
|
179
|
+
## Reglas Sigma
|
|
180
|
+
|
|
181
|
+
La carpeta [`sigma/`](sigma/) tiene las 21 detecciones en formato Sigma, validadas con `sigma check`. Se convierten a la consulta de tu SIEM (Splunk, Elastic, Microsoft Sentinel, QRadar...):
|
|
182
|
+
|
|
183
|
+
```bash
|
|
184
|
+
python -m pip install sigma-cli
|
|
185
|
+
sigma plugin install splunk
|
|
186
|
+
sigma convert -t splunk -p windows-audit -p splunk_windows sigma/
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
## Seguridad del propio analizador
|
|
190
|
+
|
|
191
|
+
Los logs pueden contener datos controlados por un atacante (nombres de usuario, líneas de comandos, nombres de tareas), así que la herramienta los trata como entrada hostil:
|
|
192
|
+
|
|
193
|
+
- **HTML.** Todo el contenido se escapa y el informe lleva una **Content-Security-Policy** que bloquea cualquier script.
|
|
194
|
+
- **Consola.** Se eliminan los caracteres de control, para que una secuencia ANSI dentro de un log no pueda manipular la terminal.
|
|
195
|
+
- **XML.** Se rechazan los documentos con `DOCTYPE` (protección frente a XXE y billion laughs).
|
|
196
|
+
- **Markdown.** Se escapan los caracteres especiales.
|
|
197
|
+
|
|
198
|
+
## Estructura
|
|
199
|
+
|
|
200
|
+
```text
|
|
201
|
+
src/winlog_hunter/
|
|
202
|
+
parsers.py lectura de EVTX / XML / JSON y normalización de eventos
|
|
203
|
+
rules.py las 21 reglas de detección mapeadas a MITRE ATT&CK
|
|
204
|
+
report.py informe en consola, HTML, Markdown y JSON
|
|
205
|
+
cli.py comando winlog-hunter
|
|
206
|
+
scripts/
|
|
207
|
+
analisis-diario.ps1 exporta los logs del equipo, genera el informe y avisa
|
|
208
|
+
instalar-tarea.ps1 programa el análisis diario
|
|
209
|
+
sigma/ las reglas en formato Sigma
|
|
210
|
+
docs/ captura del informe
|
|
211
|
+
samples/ datos sintéticos que usan los tests
|
|
212
|
+
tests/ tests automáticos
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
Úsalo solo con logs de equipos que tengas autorización para analizar. Licencia MIT.
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# winlog-hunter
|
|
2
|
+
|
|
3
|
+
Analizador de logs de Windows para blue team. Lee eventos de **Security**, **System**, **Sysmon** y **PowerShell**, detecta actividad sospechosa con 21 reglas y genera un informe con cada hallazgo mapeado a **MITRE ATT&CK**. Las reglas también están en formato **Sigma** para usarlas en cualquier SIEM.
|
|
4
|
+
|
|
5
|
+

|
|
6
|
+
|
|
7
|
+
## Instalación
|
|
8
|
+
|
|
9
|
+
Necesitas Python 3.9 o superior y git.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
git clone https://github.com/BV-cs0/winlog-hunter.git
|
|
13
|
+
cd winlog-hunter
|
|
14
|
+
python -m pip install .
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Uso
|
|
18
|
+
|
|
19
|
+
**1. Abre PowerShell como administrador** y entra en la carpeta del proyecto:
|
|
20
|
+
|
|
21
|
+
```powershell
|
|
22
|
+
cd winlog-hunter
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
**2. Genera el informe** con los logs de las últimas 24 horas de tu equipo:
|
|
26
|
+
|
|
27
|
+
```powershell
|
|
28
|
+
powershell -ExecutionPolicy Bypass -File .\scripts\analisis-diario.ps1
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
**3. Abre el informe.** Se guarda en `Documentos\winlog-hunter` con la fecha en el nombre:
|
|
32
|
+
|
|
33
|
+
```powershell
|
|
34
|
+
start $HOME\Documents\winlog-hunter
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
> Para analizar más tiempo añade `-Horas 72`. Sin administrador también funciona, pero se omite el log Security.
|
|
38
|
+
|
|
39
|
+
## Detecciones
|
|
40
|
+
|
|
41
|
+
| ID | Detección | Eventos | MITRE ATT&CK |
|
|
42
|
+
|---|---|---|---|
|
|
43
|
+
| WLH-001 | Fuerza bruta (muchos fallos, misma cuenta y origen) | 4625 | T1110.001 |
|
|
44
|
+
| WLH-002 | Password spraying (un origen, muchas cuentas) | 4625 | T1110.003 |
|
|
45
|
+
| WLH-003 | Inicio de sesión correcto justo después de una fuerza bruta | 4625 → 4624 | T1110, T1078 |
|
|
46
|
+
| WLH-004 | Movimiento lateral (misma cuenta en varios equipos) | 4624 tipo 3/10 | T1021 |
|
|
47
|
+
| WLH-005 | Registro de eventos borrado | 1102, 104 | T1685.005 |
|
|
48
|
+
| WLH-006 | Servicio nuevo; alta si es PsExec o ejecuta algo sospechoso | 7045 | T1543.003, T1569.002 |
|
|
49
|
+
| WLH-007 | Tarea programada; alta si lanza PowerShell, scripts o rutas raras | 4698 | T1053.005 |
|
|
50
|
+
| WLH-008 | Cuenta de usuario creada | 4720 | T1136 |
|
|
51
|
+
| WLH-009 | Alta en grupo privilegiado (por SID, vale en cualquier idioma) | 4728, 4732, 4756 | T1098 |
|
|
52
|
+
| WLH-010 | PowerShell sospechoso; decodifica `-EncodedCommand` | Sysmon 1, 4688 | T1059.001 |
|
|
53
|
+
| WLH-011 | LOLBins: certutil, mshta, rundll32, regsvr32, bitsadmin, wmic | Sysmon 1, 4688 | T1218, T1105, T1197, T1047 |
|
|
54
|
+
| WLH-012 | Office (Word, Excel, Outlook...) lanzando una shell | Sysmon 1, 4688 | T1566.001, T1204.002 |
|
|
55
|
+
| WLH-013 | Acceso a la memoria de LSASS (Mimikatz, procdump...) | Sysmon 10 | T1003.001 |
|
|
56
|
+
| WLH-014 | Comandos de volcado: comsvcs MiniDump, ntdsutil, reg save SAM | Sysmon 1, 4688 | T1003.001-.003 |
|
|
57
|
+
| WLH-015 | DCSync: replicación de AD pedida por un usuario | 4662 | T1003.006 |
|
|
58
|
+
| WLH-016 | Kerberoasting: tickets de servicio RC4 | 4769 | T1558.003 |
|
|
59
|
+
| WLH-017 | Ejecución remota por SMB: PsExec, svcctl, atsvc, copia a ADMIN$ | 5145 | T1021.002, T1569.002 |
|
|
60
|
+
| WLH-018 | Shell lanzada por WMI o WinRM (wmiexec, Invoke-Command) | Sysmon 1, 4688 | T1047, T1021.006 |
|
|
61
|
+
| WLH-019 | Persistencia en el registro: Run, Winlogon, IFEO, COM, LSA, SAM | Sysmon 13 | T1547, T1546 |
|
|
62
|
+
| WLH-020 | Persistencia con suscripciones WMI | Sysmon 19-21 | T1546.003 |
|
|
63
|
+
| WLH-021 | Script de PowerShell malicioso: volcado de LSASS, AMSI, inyección | 4104 | T1059.001, T1003.001 |
|
|
64
|
+
|
|
65
|
+
Para reducir falsos positivos, la severidad depende del contexto: un servicio o una tarea normales salen como *baja*, y uno que ejecuta `powershell -enc` sale como *alta*. Los ataques en ráfaga (500 intentos de contraseña) se agrupan en un único hallazgo.
|
|
66
|
+
|
|
67
|
+
## Resultados con ataques reales
|
|
68
|
+
|
|
69
|
+
winlog-hunter se ha probado con [EVTX-ATTACK-SAMPLES](https://github.com/sbousseaden/EVTX-ATTACK-SAMPLES): 278 ficheros `.evtx` grabados en laboratorio mientras se ejecutaban ataques reales, organizados por táctica.
|
|
70
|
+
|
|
71
|
+
| Táctica | Ficheros | Detectados |
|
|
72
|
+
|---|---|---|
|
|
73
|
+
| Credential Access | 39 | 14 |
|
|
74
|
+
| Lateral Movement | 47 | 13 |
|
|
75
|
+
| Persistence | 22 | 12 |
|
|
76
|
+
| Execution | 34 | 7 |
|
|
77
|
+
| Herramientas de pruebas automatizadas | 8 | 5 |
|
|
78
|
+
| Privilege Escalation | 66 | 3 |
|
|
79
|
+
| Defense Evasion | 36 | 2 |
|
|
80
|
+
| Discovery | 11 | 1 |
|
|
81
|
+
| Command and Control | 6 | 0 |
|
|
82
|
+
| Otros | 9 | 1 |
|
|
83
|
+
| **Total** | **278** | **58** |
|
|
84
|
+
|
|
85
|
+
No se cuentan los ficheros en los que solo salta *registro borrado*, porque el autor vació los logs antes de grabar cada ataque.
|
|
86
|
+
|
|
87
|
+
Los puntos débiles son claros: la **escalada de privilegios** (bypass de UAC, tokens, servicios vulnerables) y la **evasión de defensas**. Casi todos esos ataques necesitan reglas de Sysmon 7 (carga de DLL), 8 (hilos remotos) y 11 (ficheros creados), que aún no están implementadas.
|
|
88
|
+
|
|
89
|
+
## Activar Sysmon (recomendado)
|
|
90
|
+
|
|
91
|
+
Sin Sysmon, Windows no registra los procesos que se ejecutan, los accesos a LSASS ni los cambios en el registro, así que 9 de las 21 reglas no tienen datos. Sysmon es gratuito y de Microsoft. En PowerShell como administrador:
|
|
92
|
+
|
|
93
|
+
```powershell
|
|
94
|
+
# 1. Descargar Sysmon y una configuración probada (la de SwiftOnSecurity)
|
|
95
|
+
Invoke-WebRequest https://download.sysinternals.com/files/Sysmon.zip -OutFile $env:TEMP\Sysmon.zip
|
|
96
|
+
Expand-Archive $env:TEMP\Sysmon.zip $env:TEMP\Sysmon -Force
|
|
97
|
+
Invoke-WebRequest https://raw.githubusercontent.com/SwiftOnSecurity/sysmon-config/master/sysmonconfig-export.xml -OutFile $env:TEMP\sysmon.xml
|
|
98
|
+
|
|
99
|
+
# 2. Instalarlo
|
|
100
|
+
& $env:TEMP\Sysmon\Sysmon64.exe -accepteula -i $env:TEMP\sysmon.xml
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Para la regla WLH-021, activa también el registro de bloques de script de PowerShell:
|
|
104
|
+
|
|
105
|
+
```powershell
|
|
106
|
+
New-Item -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging -Force |
|
|
107
|
+
New-ItemProperty -Name EnableScriptBlockLogging -Value 1 -PropertyType DWord -Force
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
El análisis diario incluye Sysmon y PowerShell en cuanto existen.
|
|
111
|
+
|
|
112
|
+
## Cómo sacar los logs de un equipo Windows manualmente
|
|
113
|
+
|
|
114
|
+
Para analizar otro equipo, o un log concreto, expórtalo y pásaselo a winlog-hunter:
|
|
115
|
+
|
|
116
|
+
```powershell
|
|
117
|
+
# 1. Exportar los logs (Security requiere administrador)
|
|
118
|
+
wevtutil epl Security C:\temp\Security.evtx
|
|
119
|
+
wevtutil epl System C:\temp\System.evtx
|
|
120
|
+
|
|
121
|
+
# 2. Analizarlos y guardar el informe
|
|
122
|
+
winlog-hunter analyze C:\temp\Security.evtx C:\temp\System.evtx -o informe.html
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
El formato del informe se elige por la extensión: `.html`, `.md` o `.json`. También acepta `.xml` de `wevtutil qe` y JSON de Winlogbeat o de un SIEM. En Linux/macOS, para leer `.evtx` instala antes `python3 -m pip install ".[evtx]"`.
|
|
126
|
+
|
|
127
|
+
## Análisis automático diario del propio equipo (Windows)
|
|
128
|
+
|
|
129
|
+
Para que el informe se genere solo cada día, en PowerShell **como administrador**:
|
|
130
|
+
|
|
131
|
+
```powershell
|
|
132
|
+
# Programarlo cada día a las 09:00
|
|
133
|
+
powershell -ExecutionPolicy Bypass -File .\scripts\instalar-tarea.ps1
|
|
134
|
+
|
|
135
|
+
# A otra hora
|
|
136
|
+
powershell -ExecutionPolicy Bypass -File .\scripts\instalar-tarea.ps1 -Hora 21:30
|
|
137
|
+
|
|
138
|
+
# Lanzarlo ahora sin esperar
|
|
139
|
+
Start-ScheduledTask -TaskName 'winlog-hunter diario'
|
|
140
|
+
|
|
141
|
+
# Quitarlo
|
|
142
|
+
powershell -ExecutionPolicy Bypass -File .\scripts\instalar-tarea.ps1 -Desinstalar
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
- Si hay algún hallazgo **crítico**, aparece un aviso en pantalla con el resumen y la ruta del informe.
|
|
146
|
+
- Los informes se guardan en `Documentos\winlog-hunter` y los de más de 30 días se borran solos.
|
|
147
|
+
- `ejecuciones.log`, en la misma carpeta, guarda un resumen de cada ejecución.
|
|
148
|
+
- Si el equipo está apagado a la hora programada, se ejecuta al encenderlo.
|
|
149
|
+
- Si mueves la carpeta del proyecto, vuelve a ejecutar el instalador.
|
|
150
|
+
|
|
151
|
+
## Reglas Sigma
|
|
152
|
+
|
|
153
|
+
La carpeta [`sigma/`](sigma/) tiene las 21 detecciones en formato Sigma, validadas con `sigma check`. Se convierten a la consulta de tu SIEM (Splunk, Elastic, Microsoft Sentinel, QRadar...):
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
python -m pip install sigma-cli
|
|
157
|
+
sigma plugin install splunk
|
|
158
|
+
sigma convert -t splunk -p windows-audit -p splunk_windows sigma/
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## Seguridad del propio analizador
|
|
162
|
+
|
|
163
|
+
Los logs pueden contener datos controlados por un atacante (nombres de usuario, líneas de comandos, nombres de tareas), así que la herramienta los trata como entrada hostil:
|
|
164
|
+
|
|
165
|
+
- **HTML.** Todo el contenido se escapa y el informe lleva una **Content-Security-Policy** que bloquea cualquier script.
|
|
166
|
+
- **Consola.** Se eliminan los caracteres de control, para que una secuencia ANSI dentro de un log no pueda manipular la terminal.
|
|
167
|
+
- **XML.** Se rechazan los documentos con `DOCTYPE` (protección frente a XXE y billion laughs).
|
|
168
|
+
- **Markdown.** Se escapan los caracteres especiales.
|
|
169
|
+
|
|
170
|
+
## Estructura
|
|
171
|
+
|
|
172
|
+
```text
|
|
173
|
+
src/winlog_hunter/
|
|
174
|
+
parsers.py lectura de EVTX / XML / JSON y normalización de eventos
|
|
175
|
+
rules.py las 21 reglas de detección mapeadas a MITRE ATT&CK
|
|
176
|
+
report.py informe en consola, HTML, Markdown y JSON
|
|
177
|
+
cli.py comando winlog-hunter
|
|
178
|
+
scripts/
|
|
179
|
+
analisis-diario.ps1 exporta los logs del equipo, genera el informe y avisa
|
|
180
|
+
instalar-tarea.ps1 programa el análisis diario
|
|
181
|
+
sigma/ las reglas en formato Sigma
|
|
182
|
+
docs/ captura del informe
|
|
183
|
+
samples/ datos sintéticos que usan los tests
|
|
184
|
+
tests/ tests automáticos
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Úsalo solo con logs de equipos que tengas autorización para analizar. Licencia MIT.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "winlog-hunter"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Detección de amenazas en logs de Windows (Security, System, Sysmon, PowerShell) mapeada a MITRE ATT&CK"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "Bryan Valenzuela" }]
|
|
13
|
+
keywords = ["blue-team", "soc", "dfir", "windows", "sysmon", "mitre-attack", "threat-hunting"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Topic :: Security",
|
|
21
|
+
"Topic :: System :: Logging",
|
|
22
|
+
"Environment :: Console",
|
|
23
|
+
"Intended Audience :: Information Technology",
|
|
24
|
+
"Intended Audience :: System Administrators",
|
|
25
|
+
"Natural Language :: Spanish",
|
|
26
|
+
]
|
|
27
|
+
dependencies = []
|
|
28
|
+
|
|
29
|
+
[project.optional-dependencies]
|
|
30
|
+
evtx = ["python-evtx>=0.7"]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://github.com/BV-cs0/winlog-hunter"
|
|
34
|
+
Source = "https://github.com/BV-cs0/winlog-hunter"
|
|
35
|
+
Issues = "https://github.com/BV-cs0/winlog-hunter/issues"
|
|
36
|
+
|
|
37
|
+
[project.scripts]
|
|
38
|
+
winlog-hunter = "winlog_hunter.cli:main"
|
|
39
|
+
|
|
40
|
+
[tool.setuptools.packages.find]
|
|
41
|
+
where = ["src"]
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Interfaz de línea de comandos."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from datetime import timedelta
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from . import __version__
|
|
12
|
+
from .models import SEVERITIES, SEVERITY_ORDER
|
|
13
|
+
from .parsers import load_events
|
|
14
|
+
from .report import RENDERERS, SEVERITY_LABEL, Stats, render_console
|
|
15
|
+
from .rules import RULES, Config, run_rules
|
|
16
|
+
|
|
17
|
+
FORMATS = ("console", "json", "markdown", "html")
|
|
18
|
+
_EXTENSION_FORMAT = {".json": "json", ".md": "markdown", ".markdown": "markdown", ".html": "html", ".htm": "html"}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
22
|
+
parser = argparse.ArgumentParser(
|
|
23
|
+
prog="winlog-hunter",
|
|
24
|
+
description="Analiza logs de Windows (Security, System, Sysmon) y detecta actividad "
|
|
25
|
+
"sospechosa mapeada a MITRE ATT&CK.",
|
|
26
|
+
)
|
|
27
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
28
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
29
|
+
|
|
30
|
+
analyze = sub.add_parser("analyze", help="analiza ficheros o carpetas de logs")
|
|
31
|
+
analyze.add_argument("paths", nargs="+", type=Path, help=".evtx, .xml (wevtutil), .jsonl/.json o carpetas")
|
|
32
|
+
analyze.add_argument("-f", "--format", choices=FORMATS, help="formato de salida (por defecto, según -o o consola)")
|
|
33
|
+
analyze.add_argument("-o", "--output", type=Path, help="fichero donde guardar el informe")
|
|
34
|
+
analyze.add_argument("--min-severity", choices=SEVERITIES, default="low", help="oculta hallazgos por debajo")
|
|
35
|
+
analyze.add_argument("--rules", help="IDs de reglas separados por comas, p. ej. WLH-001,WLH-003")
|
|
36
|
+
analyze.add_argument("--fail-on", choices=SEVERITIES, help="sale con código 1 si hay hallazgos de esa severidad o más")
|
|
37
|
+
analyze.add_argument("--threshold", type=int, default=5, help="fallos para considerar fuerza bruta (5)")
|
|
38
|
+
analyze.add_argument("--spray-accounts", type=int, default=5, help="cuentas distintas para password spraying (5)")
|
|
39
|
+
analyze.add_argument("--window", type=float, default=5, help="ventana de correlación en minutos (5)")
|
|
40
|
+
analyze.add_argument("--lateral-hosts", type=int, default=3, help="equipos distintos para movimiento lateral (3)")
|
|
41
|
+
analyze.add_argument("--no-color", action="store_true", help="desactiva los colores en consola")
|
|
42
|
+
|
|
43
|
+
sub.add_parser("rules", help="lista las reglas de detección")
|
|
44
|
+
return parser
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _enable_ansi() -> bool:
|
|
48
|
+
if os.name != "nt":
|
|
49
|
+
return True
|
|
50
|
+
try:
|
|
51
|
+
import ctypes
|
|
52
|
+
|
|
53
|
+
kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
|
|
54
|
+
handle = kernel32.GetStdHandle(-11)
|
|
55
|
+
mode = ctypes.c_uint32()
|
|
56
|
+
if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
|
|
57
|
+
return False
|
|
58
|
+
return bool(kernel32.SetConsoleMode(handle, mode.value | 0x0004))
|
|
59
|
+
except Exception:
|
|
60
|
+
return False
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _list_rules() -> int:
|
|
64
|
+
for r in RULES:
|
|
65
|
+
print(f"{r.id} [{SEVERITY_LABEL[r.severity]}] {', '.join(r.mitre)}")
|
|
66
|
+
print(f" {r.title}: {r.description}")
|
|
67
|
+
return 0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _analyze(args: argparse.Namespace) -> int:
|
|
71
|
+
known = {r.id for r in RULES}
|
|
72
|
+
only = None
|
|
73
|
+
if args.rules:
|
|
74
|
+
only = {rid.strip().upper() for rid in args.rules.split(",") if rid.strip()}
|
|
75
|
+
unknown = only - known
|
|
76
|
+
if unknown:
|
|
77
|
+
print(f"error: reglas desconocidas: {', '.join(sorted(unknown))}", file=sys.stderr)
|
|
78
|
+
return 2
|
|
79
|
+
for name in ("threshold", "spray_accounts", "lateral_hosts"):
|
|
80
|
+
if getattr(args, name) < 1:
|
|
81
|
+
print(f"error: --{name.replace('_', '-')} debe ser al menos 1", file=sys.stderr)
|
|
82
|
+
return 2
|
|
83
|
+
if args.window <= 0:
|
|
84
|
+
print("error: --window debe ser mayor que 0", file=sys.stderr)
|
|
85
|
+
return 2
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
loaded = load_events(args.paths)
|
|
89
|
+
except (FileNotFoundError, PermissionError) as exc:
|
|
90
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
91
|
+
return 2
|
|
92
|
+
if not loaded.events and loaded.warnings:
|
|
93
|
+
print("error: no se pudo leer ningún evento:", file=sys.stderr)
|
|
94
|
+
for warning in loaded.warnings[:10]:
|
|
95
|
+
print(f" - {warning}", file=sys.stderr)
|
|
96
|
+
return 2
|
|
97
|
+
|
|
98
|
+
config = Config(
|
|
99
|
+
window=timedelta(minutes=args.window),
|
|
100
|
+
brute_force_threshold=args.threshold,
|
|
101
|
+
spray_min_accounts=args.spray_accounts,
|
|
102
|
+
lateral_min_hosts=args.lateral_hosts,
|
|
103
|
+
)
|
|
104
|
+
all_findings = run_rules(loaded.events, config, only)
|
|
105
|
+
minimum = SEVERITY_ORDER[args.min_severity]
|
|
106
|
+
findings = [f for f in all_findings if f.rank >= minimum]
|
|
107
|
+
|
|
108
|
+
stats = Stats(
|
|
109
|
+
events=len(loaded.events),
|
|
110
|
+
files=loaded.files,
|
|
111
|
+
first_event=loaded.events[0].timestamp if loaded.events else None,
|
|
112
|
+
last_event=loaded.events[-1].timestamp if loaded.events else None,
|
|
113
|
+
warnings=loaded.warnings,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
fmt = args.format or (_EXTENSION_FORMAT.get(args.output.suffix.lower(), "console") if args.output else "console")
|
|
117
|
+
if fmt == "console":
|
|
118
|
+
color = (
|
|
119
|
+
not args.no_color
|
|
120
|
+
and args.output is None
|
|
121
|
+
and "NO_COLOR" not in os.environ
|
|
122
|
+
and sys.stdout.isatty()
|
|
123
|
+
and _enable_ansi()
|
|
124
|
+
)
|
|
125
|
+
text = render_console(findings, stats, color=color)
|
|
126
|
+
else:
|
|
127
|
+
text = RENDERERS[fmt](findings, stats)
|
|
128
|
+
|
|
129
|
+
if args.output:
|
|
130
|
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
131
|
+
args.output.write_text(text if text.endswith("\n") else text + "\n", encoding="utf-8")
|
|
132
|
+
print(f"Informe {fmt} guardado en {args.output} ({len(findings)} hallazgos)", file=sys.stderr)
|
|
133
|
+
else:
|
|
134
|
+
print(text)
|
|
135
|
+
|
|
136
|
+
# --fail-on es independiente de lo que se muestra: se evalúa sobre todos los hallazgos.
|
|
137
|
+
if args.fail_on and any(f.rank >= SEVERITY_ORDER[args.fail_on] for f in all_findings):
|
|
138
|
+
return 1
|
|
139
|
+
return 0
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def main(argv: list[str] | None = None) -> int:
|
|
143
|
+
for stream in (sys.stdout, sys.stderr):
|
|
144
|
+
if hasattr(stream, "reconfigure"):
|
|
145
|
+
stream.reconfigure(errors="replace")
|
|
146
|
+
args = build_parser().parse_args(argv)
|
|
147
|
+
if args.command == "rules":
|
|
148
|
+
return _list_rules()
|
|
149
|
+
return _analyze(args)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
if __name__ == "__main__":
|
|
153
|
+
raise SystemExit(main())
|