HackTheBox - Unit42 (Sherlock)

HackTheBox - Unit42 (Sherlock)

·

10 min read

«En este Sherlock, te familiarizarás con los registros de Sysmon y varios EventIDs útiles para identificar y analizar actividades maliciosas en un sistema Windows. Unit42 de Palo Alto llevó a cabo recientemente una investigación sobre una campaña de UltraVNC, en la que los atacantes utilizaban una versión de UltraVNC con un backdoor para conseguir acceso persistente a sistemas. Este laboratorio se inspira en esa campaña y guía a los participantes a través de la fase de acceso inicial de la campaña (del malware).»

El reto proporciona un archivo de registro de eventos de Windows:

PS C:\Users\noc\Desktop\HTB\unit42> ls


    Directory: C:\Users\noc\Desktop\HTB\unit42


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        14/02/2024     03:43        1118208 Microsoft-Windows-Sysmon-Operational.evtx

Se puede utilizar el Windows Event Viewer, he visto a gente usar Splunk, la herramienta de Eric Zimmerman EvtxeCmd.exe… Pero me pareció más cómodo usar chainsaw, open source y utilizable tanto en linux como en windows. Tras descargarlo, copié el archivo de logs al mismo directorio.

PS C:\Users\noc\Desktop\HTB\chainsaw_x86_64-pc-windows-msvc\chainsaw> ls


    Directory: C:\Users\noc\Desktop\HTB\chainsaw_x86_64-pc-windows-msvc\chainsaw


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        04/01/2025     02:06                mappings
------        28/12/2024     18:26        9495040 chainsaw.exe
------        28/12/2024     18:22          35817 LICENCE
-a----        14/02/2024     03:43        1118208 Microsoft-Windows-Sysmon-Operational.evtx
------        28/12/2024     18:22          52251 README.md

PS C:\Users\noc\Desktop\HTB\chainsaw_x86_64-pc-windows-msvc\chainsaw> .\chainsaw.exe
Rapidly work with Forensic Artefacts

Usage: chainsaw.exe [OPTIONS] <COMMAND>

Commands:
  dump     Dump artefacts into a different format
  hunt     Hunt through artefacts using detection rules for threat detection
  lint     Lint provided rules to ensure that they load correctly
  search   Search through forensic artefacts for keywords or patterns
  analyse  Perform various analyses on artefacts
  help     Print this message or the help of the given subcommand(s)

Options:
      --no-banner                  Hide Chainsaw's banner
      --num-threads <NUM_THREADS>  Limit the thread number (default: num of CPUs)
  -v...                            Print verbose output
  -h, --help                       Print help
  -V, --version                    Print version

Examples:

    Hunt with Sigma and Chainsaw Rules:
        ./chainsaw hunt evtx_attack_samples/ -s sigma/ --mapping mappings/sigma-event-logs-all.yml -r rules/

    Hunt with Sigma rules and output in JSON:
        ./chainsaw hunt evtx_attack_samples/ -s sigma/ --mapping mappings/sigma-event-logs-all.yml --json

    Search for the case-insensitive word 'mimikatz':
        ./chainsaw search mimikatz -i evtx_attack_samples/

    Search for Powershell Script Block Events (EventID 4014):
        ./chainsaw search -t 'Event.System.EventID: =4104' evtx_attack_samples/

En este caso solo se necesitará chainsaw.exe search, que permite buscar artefactos forenses en logs utilizando palabras clave, patrones específicos o expresiones regulares.

PS C:\Users\noc\Desktop\HTB\chainsaw_x86_64-pc-windows-msvc\chainsaw> .\chainsaw.exe search --help
Search through forensic artefacts for keywords or patterns

Usage: chainsaw.exe search [OPTIONS] [PATTERN] [PATH]...

Arguments:
  [PATTERN]  A string or regular expression pattern to search for. Not used when -e or -t is specified
  [PATH]...  The paths containing files to load and hunt through

Options:
  -e, --regex <pattern>        A string or regular expression pattern to search for
      --extension <EXTENSION>  Only search through files with the provided extension
      --from <FROM>            The timestamp to search from. Drops any documents older than the value provided. (YYYY-MM-ddTHH:mm:SS)
  -i, --ignore-case            Ignore the case when searching patterns
  -j, --json                   Print the output in json format
      --jsonl                  Print the output in jsonl format
      --load-unknown           Allow chainsaw to try and load files it cannot identify
      --local                  Output the timestamp using the local machine's timestamp
      --match-any              Require any of the provided patterns to be found to constitute a match
  -o, --output <OUTPUT>        The path to output results to
  -q                           Suppress informational output
      --skip-errors            Continue to search when an error is encountered
  -t, --tau <TAU>              Tau expressions to search with. e.g. 'Event.System.EventID: =4104'. Multiple conditions are logical ANDs unless the 'match-any' flag is specified
      --timestamp <TIMESTAMP>  The field that contains the timestamp
      --timezone <TIMEZONE>    Output the timestamp using the timezone provided
      --to <TO>                The timestamp to search up to. Drops any documents newer than the value provided. (YYYY-MM-ddTHH:mm:SS)
  -h, --help                   Print help

Pregunta 1

Cuantos Event logs hay con el Event ID 11? (How many Event logs are there with Event ID 11?)

La opción -t permite usar “expresiones Tau”, como 'Event.System.EventID: =11', para filtrar eventos según sus atributos (como IDs específicos):

PS C:\Users\noc\Desktop\HTB\chainsaw_x86_64-pc-windows-msvc\chainsaw> .\chainsaw.exe search -t 'Event.System.EventID: =11' .\Microsoft-Windows-Sysmon-Operational.evtx
(..)
[+] Found 56 hits

Se identificaron 56 eventos con el EventID 11, que indican la creación de archivos en el sistema.

R: 56

Cronología de Eventos ID 11

  1. [2024-02-14 03:41:26.459]

    • Proceso: C:\Program Files\Mozilla Firefox\firefox.exe

    • Archivo creado: C:\Users\CYBERJ~1\AppData\Local\Temp\skZdsnwf.exe

    • Usuario: DESKTOP-887GK2L\CyberJunkie

  2. [2024-02-14 03:41:26.459]

    • Proceso: C:\Program Files\Mozilla Firefox\firefox.exe

    • Archivo creado: C:\Users\CyberJunkie\Downloads\skZdsnwf.exe.part

    • Usuario: DESKTOP-887GK2L\CyberJunkie

  3. [2024-02-14 03:41:26.464]

    • Proceso: C:\Program Files\Mozilla Firefox\firefox.exe

    • Archivo creado: C:\Users\CyberJunkie\Downloads\Preventivo24.02.14.exe.exe

    • Usuario: DESKTOP-887GK2L\CyberJunkie

  4. [2024-02-14 03:41:30.472]

    • Proceso: C:\Program Files\Mozilla Firefox\firefox.exe

    • Archivo creado: C:\Users\CyberJunkie\Downloads\Preventivo24.02.14.exe.exe:Zone.Identifier

    • Usuario: DESKTOP-887GK2L\CyberJunkie

  5. [2024-02-14 03:41:45.211]

    • Proceso: C:\Program Files\Mozilla Firefox\firefox.exe

    • Archivo creado: C:\Users\CyberJunkie\AppData\Roaming\Mozilla\Firefox\Profiles\avsa4d81.default-release\prefs-1.js

    • Usuario: DESKTOP-887GK2L\CyberJunkie

  6. [2024-02-14 03:41:58.404]

    • Proceso: C:\Users\CyberJunkie\Downloads\Preventivo24.02.14.exe.exe

    • Archivo creado: C:\Users\CyberJunkie\AppData\Roaming\Photo and Fax Vn\install\F97891C\Games\taskhost.exe

    • Usuario: DESKTOP-887GK2L\CyberJunkie

  7. [2024-02-14 03:41:58.623]

    • Proceso: C:\Windows\system32\msiexec.exe

    • Archivo creado: C:\Windows\Temp\~DF3F75EAA6EFF686F3.TMP

    • Usuario: NT AUTHORITY\SYSTEM

  8. [2024-02-14 03:41:58.655]

    • Proceso: C:\Windows\system32\msiexec.exe

    • Archivo creado: C:\Windows\Temp\~DF6B36AD641199B0BF.TMP

    • Usuario: NT AUTHORITY\SYSTEM

Desde Firefox se descargaron varios archivos, incluido Preventivo24.02.14.exe.exe, en la carpeta de descargas del usuario CyberJunkie. Posteriormente, el ejecutable creó un archivo malicioso taskhost.exe en una ubicación oculta dentro de AppData\Roaming\Photo and Fax Vn, lo que indica actividad sospechosa. Además, se observó la ejecución de msiexec.exe, que generó archivos temporales en el directorio Windows\Temp bajo el usuario NT AUTHORITY\SYSTEM, sugiriendo que el ejecutable descargado desencadenó actividades maliciosas, posiblemente para instalar software no autorizado o persistente en el sistema.

Pregunta 2

Cada vez que se crea un proceso en memoria, se registra un evento con Event ID 1 con detalles como línea de comandos, hashes, ruta del proceso, ruta del proceso padre, etc. Esta información es muy útil para un analista porque permite ver todos los programas ejecutados en un sistema, lo que significa que se puede detectar cualquier proceso malicioso que se esté ejecutando. ¿Cuál es el proceso malicioso que infectó el sistema de la víctima? (Whenever a process is created in memory, an event with Event ID 1 is recorded with details such as command line, hashes, process path, parent process path, etc. This information is very useful for an analyst because it allows us to see all programs executed on a system, which means we can spot any malicious processes being executed. What is the malicious process that infected the victim's system?)

Se pueden filtrar los eventos de creación de procesos (EventID 1) para identificar procesos ejecutados:

PS C:\Users\noc\Desktop\HTB\chainsaw_x86_64-pc-windows-msvc\chainsaw> .\chainsaw.exe search -t 'Event.System.EventID: =1' .\Microsoft-Windows-Sysmon-Operational.evtx
(...)
[+] Found 6 hits

Para reducir esta cantidad de texto, se pueden filtrar los campos más relevantes:

  • ProcessID: ID del proceso creado.

  • UtcTime: Marca de tiempo del evento.

  • Image: Ruta completa del archivo ejecutable del proceso creado.

  • ParentProcessId: ID del proceso padre.

  • ParentImage: Ruta completa del archivo ejecutable del proceso padre.

Esto proporciona datos sobre:

  • Qué procesos se ejecutaron.

  • Quién los lanzó (proceso padre).

  • Cuándo ocurrieron.

PS C:\Users\noc\Desktop\HTB\chainsaw_x86_64-pc-windows-msvc\chainsaw> .\chainsaw.exe search -t 'Event.System.EventID: =1' .\Microsoft-Windows-Sysmon-Operational.evtx | Select-String "ParentImage|Image|UtcTime|ProcessId|ParentProcessId"

[+] Found 6 hits
    Image: C:\Users\CyberJunkie\Downloads\Preventivo24.02.14.exe.exe
    ParentProcessId: 1116
    ParentImage: C:\Windows\explorer.exe
      ProcessID: 3028
    UtcTime: 2024-02-14 03:41:57.604
    ProcessId: 10220

    Image: C:\Windows\System32\msiexec.exe
    ParentProcessId: 740
    ParentImage: C:\Windows\System32\services.exe
      ProcessID: 3028
    UtcTime: 2024-02-14 03:41:57.787
    ProcessId: 6996

    Image: C:\Windows\SysWOW64\msiexec.exe
    ParentProcessId: 10220
    ParentImage: C:\Windows\System32\msiexec.exe
      ProcessID: 3028
    UtcTime: 2024-02-14 03:41:57.905
    ProcessId: 10324

    Image: C:\Windows\SysWOW64\msiexec.exe
    ParentProcessId: 10672
    ParentImage: C:\Users\CyberJunkie\Downloads\Preventivo24.02.14.exe.exe
      ProcessID: 3028
    UtcTime: 2024-02-14 03:41:58.178
    ProcessId: 10280

    Image: C:\Windows\SysWOW64\msiexec.exe
    ParentProcessId: 10220
    ParentImage: C:\Windows\System32\msiexec.exe

Preventivo24.02.14.exe.exe fue ejecutado manualmente desde el Explorador de Windows y generó múltiples instancias del proceso msiexec.exe, tanto desde System32 como SysWOW64, sugiriendo un comportamiento malicioso orientado a instalar o configurar componentes en el sistema.

R: C:\Users\CyberJunkie\Downloads\Preventivo24.02.14.exe.exe

Para obtener más detalles del archivo, se puede buscar su nombre en internet, pero mejor incluso es buscar si el hash del archivo aparece en páginas como VirusTotal.

Añadiendo Hashes a los filtros:

PS C:\Users\noc\Desktop\HTB\chainsaw_x86_64-pc-windows-msvc\chainsaw> .\chainsaw.exe search -t 'Event.System.EventID: =1' .\Microsoft-Windows-Sysmon-Operational.evtx | Select-String "ParentImage|Image|UtcTime|ProcessId|Hashes|ParentProcessId"

En “Behavior“ se pueden ver más detalles del comportamiento del malware: comunicación con servidores externos (C2), modificaciones en el registro de Windows para persistencia, creación de archivos en rutas críticas del sistema, posibles capacidades de captura de información sensible, técnicas de evasión y de persistencia…

Pregunta 3

¿Qué servicio de almacenamiento en la nube se utilizó para distribuir el malware? (Which Cloud drive was used to distribute the malware?)

Para responder a esto, se puede filtrar por los Event ID 22: solicitudes DNS registradas.

PS C:\Users\noc\Desktop\HTB\chainsaw_x86_64-pc-windows-msvc\chainsaw> .\chainsaw.exe search -t 'Event.System.EventID: =22' .\Microsoft-Windows-Sysmon-Operational.evtx

2024-02-14 03:41:25.269 → Firefox hizo una solicitud DNS a uc2f030016253ec53f4953980a4e.dl.dropboxusercontent.com

2024-02-14 03:41:56.955 → Preventivo24.02.14.exe.exe hizo una solicitud DNS a example.com (Pregunta 6), probablemente como una manera del malware de verificar si tiene conexión a internet.

También se puede filtrar por el Event ID 15, que registra eventos relacionados con la creación de flujos alternativos de datos (Alternate Data Streams, ADS) en archivos, como el Zone.Identifier (un ADS que Windows añade automáticamente a los archivos descargados de fuentes externas), confirmando que el archivo fue descargado desde Dropbox.

PS C:\Users\noc\Desktop\HTB\chainsaw_x86_64-pc-windows-msvc\chainsaw> .\chainsaw.exe search -t 'Event.System.EventID: =15' .\Microsoft-Windows-Sysmon-Operational.evtx

 EventData:
    RuleName: technique_id=T1189,technique_name=Drive-by Compromise
    UtcTime: 2024-02-14 03:41:30.472
    ProcessGuid: 817BDDF3-3514-65CC-0802-000000001900
    ProcessId: 4292
    Image: C:\Program Files\Mozilla Firefox\firefox.exe
    TargetFilename: C:\Users\CyberJunkie\Downloads\Preventivo24.02.14.exe.exe:Zone.Identifier
    CreationUtcTime: 2024-02-14 03:41:26.459
    Hash: SHA1=2CFE549E8DEB113DFAD2E7702637C1772ACFDBE6,MD5=41F87E73FBAEA5D3B335EBC3B3B70FAE,SHA256=5607425CF7DCB090216F4531D099FD780193899383CBB3441017E3615E03068B,IMPHASH=00000000000000000000000000000000
    Contents: '[ZoneTransfer]  ZoneId=3  ReferrerUrl=https://www.dropbox.com/  HostUrl=https://uc2f030016253ec53f4953980a4e.dl.dropboxusercontent.com/cd/0/get/CNNlOCYTD8cqLXFQzXaeYHRkHg_PoR35Et2T0_IkqE5ijvkTAQNljV7ZkK2fLXWI2bJy944RnwKttvmNWpVd5olpBcffnvnL_IfEjzr65jZZUOxtWA9rSgJ1jc91IZILHVAJHgRhjpZYLtGo83_QbeInB7x2oEAoYg-JLF54zbhziQ/file#  '
    User: DESKTOP-887GK2L\CyberJunkie

Además, se observa que la descarga es un caso de compromiso "Drive-by" (T1189), asociado con enlaces maliciosos. También se puede ver la url completa desde la que se descargó (HostUrl).

R: Dropbox

Pregunta 4

Para muchos de los archivos que escribió en el disco, el archivo malicioso inicial utilizó una técnica de evasión llamada Time Stomping, en la que se cambia la fecha de creación del archivo para que parezca más antiguo y se camufle con otros archivos. ¿A qué fecha se cambió la creación del archivo PDF? (For many of the files it wrote to disk, the initial malicious file used a defense evasion technique called Time Stomping, where the file creation date is changed to make it appear older and blend in with other files. What was the timestamp changed to for the PDF file?)

Para responder a esto, hay otro evento de Sysmon por el que filtrar: el Event ID 2, en el que se “registra cuando un proceso modifica explícitamente una hora de creación de archivos“.

PS C:\Users\noc\Desktop\HTB\chainsaw_x86_64-pc-windows-msvc\chainsaw> .\chainsaw.exe search -t 'Event.System.EventID: =2' .\Microsoft-Windows-Sysmon-Operational.evtx

  • CreationUtcTime (2024-01-14 08:10:06.029): Hora de creación que se asignó al archivo mediante la manipulación (resultado de la técnica de Timestomp).

  • UtcTime (2024-02-14 03:41:58.404): Hora real del sistema cuando ocurrió la modificación.

R: 2024-01-14 08:10:06

Pregunta 5

El archivo malicioso dejó unos archivos en el disco. ¿Dónde se creó «once.cmd» en el disco? Por favor, responde con la ruta completa junto al nombre del archivo (The malicious file dropped a few files on disk. Where was "once.cmd" created on disk? Please answer with the full path along with the filename)

Para filtrar de manera más efectiva, se añade el PID de Preventivo24.02.14.exe.exe (primera captura de la Pregunta 2) añadiendo -t 'Event.EventData.ProcessId: =10672'.

PS C:\Users\noc\Desktop\HTB\chainsaw_x86_64-pc-windows-msvc\chainsaw> .\chainsaw.exe search -t 'Event.System.EventID: =11' -t 'Event.EventData.ProcessId: =10672'  .\Microsoft-Windows-Sysmon-Operational.evtx

Preventivo24.02.14.exe.exe fue responsable de crear (entre otros…) el archivo once.cmd en el disco en la siguiente ruta: C:\Users\CyberJunkie\AppData\Roaming\Photo and Fax Vn\Photo and vn 1.1.2\install\F97891C\WindowsVolume\Games\once.cmd

R: C:\Users\CyberJunkie\AppData\Roaming\Photo and Fax Vn\Photo and vn 1.1.2\install\F97891C\WindowsVolume\Games\once.cmd

Pregunta 6

El archivo malicioso intentó acceder a un dominio de prueba, probablemente para comprobar el estado de la conexión a Internet. ¿A qué dominio intentó conectarse? (The malicious file attempted to reach a dummy domain, most likely to check the internet connection status. What domain name did it try to connect to?)

Ya se vió en la pregunta 3 filtrando las DNS requests (Event ID 22): Preventivo24.02.14.exe.exe hizo una solicitud DNS a www.example.com para verificar la conectividad a internet.

R: www.example.com

Pregunta 7

¿A qué dirección IP intentó conectarse el proceso malicioso? (Which IP address did the malicious process try to reach out to?)

Para responder a esto se pueden filtrar por los Event ID 3, en los que se registran las conexiones TCP/UDP del proceso malicioso:

PS C:\Users\noc\Desktop\HTB\chainsaw_x86_64-pc-windows-msvc\chainsaw> .\chainsaw.exe search -t 'Event.System.EventID: =3' -t 'Event.EventData.ProcessId: =10672'  .\Microsoft-Windows-Sysmon-Operational.evtx

El archivo Preventivo24.02.14.exe.exe inició una conexión TCP hacia el host remoto con dirección IP 93.184.216.34 en el puerto 80 (HTTP). La conexión fue realizada desde la dirección IP local 172.17.79.132 utilizando el puerto de origen 61177 el 2024-02-14 a las 03:41:57 UTC. Adicionalmente, el evento está relacionado con la técnica T1036 - Masquerading, lo que indica que el ejecutable puede haber intentado camuflarse como un archivo legítimo para evitar detecciones.

R: 93.184.216.34

Pregunta 8

El proceso malicioso se ha autodestruido después de infectar el PC con una variante de UltraVNC con un backdoor. ¿Cuándo finalizó el proceso? (The malicious process terminated itself after infecting the PC with a backdoored variant of UltraVNC. When did the process terminate itself?)

Los Event ID 5 en Sysmon corresponden a la terminación de un proceso. El proceso malicioso C:\Users\CyberJunkie\Downloads\Preventivo24.02.14.exe.exe se terminó a sí mismo después de infectar el sistema con una variante de UltraVNC con un backdoor. Según el Event ID 5, este proceso finalizó a las 2024-02-14 a las 03:41:58.795 UTC.

R: 2024-02-14 03:41:58.795