MySQL UDF Privilege Escalation
MySQL user-defined functions (UDFs) are custom functions loaded from a shared library on the server filesystem. When an attacker can write a malicious shared library to the MySQL plugin directory and load it as a UDF, they gain the ability to execute OS commands through SQL queries. The commands run as the MySQL process user: typically mysql on Linux. On systems where MySQL runs as root this is direct root code execution. This technique requires FILE privilege, CREATE ROUTINE privilege, and write access to the plugin directory.
MySQL UDF Privilege Escalation Prerequisites
Confirm the required privileges and identify the plugin directory:
plugin_dir: /usr/lib/mysql/plugin/ secure_file_priv:
Required for this technique:
- FILE privilege to write the shared library to disk
- CREATE ROUTINE privilege to register the UDF function
secure_file_privempty or set to a path that includes the plugin directory- Plugin directory writable by the MySQL process user
Get the UDF Shared Library from sqlmap
sqlmap ships precompiled UDF libraries for both Linux and Windows. The .so_ files are XOR/zlib-cloaked (to avoid AV detection at rest) and must be decoded with sqlmap's own cloak.py utility before use:
/usr/share/sqlmap/data/udf/mysql/linux/64/lib_mysqludf_sys.so_
Convert the Library to a Hex String
MySQL's INTO DUMPFILE requires the binary content as a hex literal to avoid encoding issues:
Query OK, 1 row affected (0.02 sec)
Create the UDF Function
Load the shared library and create the UDF function that exposes OS command execution:
Execute OS Commands via the UDF
sys_eval returns command output as a string. sys_exec executes silently and returns the exit code:
+-----------------------------+
| sys_eval('id') |
+-----------------------------+
| uid=112(mysql) gid=117(mysql) groups=117(mysql) |
+-----------------------------+
Get a Reverse Shell via UDF
Clean Up After the Assessment
Remove the UDF function and shared library after the assessment to avoid leaving persistent backdoors:
References
-
MySQL: CREATE FUNCTION for loadable functionsDOCS: MySQL: CREATE FUNCTION for loadable functions, dev.mysql.com/doc/refman/8.0/en/create-function-loadable.html (opens in new tab)
UDF loading syntax, SONAME reference, and plugin directory requirements
-
sqlmap UDF libraries on GitHubREPO: sqlmap UDF libraries on GitHub, github.com/sqlmapproject/sqlmap/tree/master/data/udf/mysql (opens in new tab)
Precompiled lib_mysqludf_sys libraries for Linux and Windows x86/x64