CEH Module 15
CEH Module 15
1 SQL
INJECTION What is SQL
Basic SQL Syntax
OVERVIEW
Structured Query Language
Used to interact with a relational database
Query (read) data from a database
Add new data
Update existing data
Delete data
Create new databases and tables
SELECT <column> FROM <table> WHERE <condition>
SELECT * FROM customers
SELECT f_name, l_name FROM customers WHERE cust_id = ‘12345’
SELECT * FROM customers WHERE cust_id = ‘12345’
AKA SQLi
The most common vulnerability in websites
An attack in which a normal SQL query has been modified
If the web app does not validate the input
It will send the modified SQL command to be executed by a back-end database
The attacker could also alter the data and put it back
Nobody would notice the change
SQLi that exfiltrates data will usually have a larger HTML response size than normal
Example:
An attacker extracts the full credit card database
That single response might be 20 to 50 MB
A normal response might only be 200 KB
Special SQL Characters
15.2 BASIC Simplest Injection Example
’ or 1=1
blah’ or 1=1
This is used to:
bypass authentication
identify injectable parameters
extract data
Prevents a
For example: syntax error
This query returns ALL accounts and their balances:
uName = getRequestString("username");
uPass = getRequestString("userpassword");
sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="' + uPass + '"'
uName = getRequestString("username");
uPass = getRequestString("userpassword");
sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="' + uPass + '"'
uName = getRequestString("username");
uPass = getRequestString("userpassword");
sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass = "' + uPass + '"'
uName = getRequestString("username");
uPass = getRequestString("userpassword");
sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass = "' + uPass + '"'
SELECT * FROM Users WHERE Name ="" OR ""=" AND Pass ="" OR ""="
inurl:index.php?id=
inurl:pages.php?id=
inurl:view.php?id=
Search for websites that rely on PHP scripts to generate dynamic SQL queries
PHP-based websites are usually your best targets because:
They can be set up by just about anyone (i.e. WordPress)
They often contain lots of valuable information about customers within the database you
are attempting to hack
Use Google Dorks to identify possible targets:
inurl:index.php?id=
inurl:pages.php?id=
inurl:view.php?id= For a more comprehensive list of Google Dorks see:
https://pastebin.com/C2awJsLB
https://brokenkeyssite.wordpress.com/
1. Take the results of your Google Dork
2. Paste it into the browser
3. Add a single quote to the end
4. Press enter
If you receive an error, the site is likely vulnerable to SQLi
Note: When testing for SQLi vulnerability, the actual contents of the error are not important
Example:
You enter:
https://www.example.com/index.php?catid=1’
Website returns:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near ''' at line 1 Warning: mysql_fetch_array() expects parameter 1 to be
resource, boolean given in /hj/var/www/listproducts.php on line 74
15.4 ERROR- SQL Errors
BASED SQL Creating an Error
INJECTION
Relies on error messages thrown by the database server to:
Indicate the website is vulnerable to SQLi
Obtain information about the structure of the database
The attacker uses information contained in the error to escalate the attack
Sometimes the names or structure of database elements are included in the error
The attacker visits
http://www.example.com
The attacker navigates to a page that displays the company’s products
The attacker looks at the first product
The URL is
http://www.example.com/listproducts.php?cat=1
The attacker adds a single quote to the URL to see if the database throws and error
http://www.example.com/listproducts.php?cat=1’
The database returns this error, strongly suggesting that the site is vulnerable to SQLi
The attacker visits
http://www.example.com
The attacker navigates to a page that displays the company’s products
The attacker looks at the first product
The URL is
http://www.example.com/listproducts.php?cat=1
The attacker adds a single quote to the URL to see if the database throws an error
http://www.example.com/listproducts.php?cat=1’
The database returns this error, strongly suggesting that the site is vulnerable to SQLi
15.5 SQL Unions
UNION SQL Using Unions in SQL Injection
INJECTION
The UNION keyword lets you execute one or more additional SELECT queries and
append the results to the original query
For a UNION query to work, two key requirements must be met:
The individual queries must return the same number of columns
The data types in each column must be compatible between the individual queries
Example:
/**
Return a single result set with two columns containing values from:
columns a and b in table1
columns c and d in table2
*/
SELECT a, b FROM table1 UNION SELECT c, d FROM table2
Leverages the UNION SQL operator
The attacker uses a UNION clause in the payload
Combines the results of two or more SELECT statements into a single result
You need to ensure that your attack meets SQL UNION requirements
The individual queries must return the same number of columns
The data types in each column must be compatible between the individual queries
Malicious query:
http://testphp.vulnweb.com/
artists.php?artist=1 UNION SELECT 1,version(),current_user()
Result: The web application displays the system version and the name of the current user:
5.1.73-0ubuntu0.10.04.1 moo@localhost
15.6 Using Blind SQLi
BLIND SQL Boolean-based Blind SQLi
If you do not see the expected result, you can still use Blind SQL injection
Blind SQL tries to trigger conditional responses
The attacker cannot directly see the result of the attack
But you get some kind of response depending on if the query is TRUE or FALSE
Takes a long time because data must be enumerated character by character
Boolean-based
Attacker sends a SQL query to the database
Forces the application to return a different result depending on whether the query returns
a TRUE or FALSE result
Time-based
Attacker sends a SQL query to the database
Forces the database to wait for a specified amount of time
Response time indicates if the result is TRUE or FALSE
Determine if the first character of the password is greater than the letter m
If so, you will receive a “Welcome Back” message
Evaluate 1st
Evaluate only
character of
one character
password
Continue using the same query but with different letters (or different operators) until you find the
first letter
blah' AND SUBSTRING((SELECT Password FROM Users
WHERE Username = 'Administrator'), 1, 1) > 't
FALSE
blah' AND SUBSTRING((SELECT Password FROM Users
WHERE Username = 'Administrator'), 1, 1) > 's
FALSE
blah' AND SUBSTRING((SELECT Password FROM Users
WHERE Username = 'Administrator'), 1, 1) > 'r
TRUE
You now know that the first letter of the administrator password is “s”
Keep going! Work on the second letter of the password…
blah' AND SUBSTRING((SELECT Password FROM Users WHERE Username =
'Administrator’), 2, 1) > 'm
Sometimes a vulnerable web app will return the same response for either Boolean-
based payload
In that case you can send a payload that includes a time delay command
If the attack is TRUE then the response will come after the delay
The actual command syntax will depend on the type of database
This example is false, so SQL will not respond:
BSQLHacker
Automated Blind SQL Injection
SQLmap
Popular open source tool that works against a wide range of database servers
SQLninja
Exploits web apps that use a SQL back end
SQLSus
a MySQL injection and takeover tool
Mole
You just need to discover a vulnerable URL and then pass it in the tool
DroidSQLi
Automated SQLi
sqlmapchik
Android port of the
popular sqlmap
Automates discovering
and exploiting SQL
vulnerabilities
15.8 EVADING Encoding
Concatenation
DETECTION Variables
All of these examples translate to “SELECT”
URL ASCII Encoding
%53%45%4C%45%43%54
URL double encoding (replace % with %25)
%2553%2545%254C%2545%2543%2554
Escaped Unicode (hex, code point, U+)
Hex: \x73\x65\x6c\x65\x63\x74
Code Point: \u0053\u0045\u004c\u0045\u0043\u0054
U+ : u+0053u+0045u+004cu+0045u+0043u+0054
All of these examples translate to “SELECT”
HTML Encoding
SELECT
Hex Encoding
0x53454c454354
SQL char() function
Pass ASCII integer value into the function for conversion to the equivalent character
CHAR(83)+CHAR(69)+CHAR(76)+CHAR(69)+CHAR(67)+CHAR(84)
Uses the SQL engine’s native ability to build a single string from multiple pieces
The attacker breaks the forbidden keyword into pieces
The SQL engine reconstructs the pieces into the original statement
Because ‘1’ always equals ‘1’, the WHERE clause will always return TRUE
EVERY record in the customers table would be returned
The website log shows the following incoming GET request:
[12Nov2021 10:07:23]
“GET /logon.php?user=test’ +oR+7>1%20—HTTP/1.1” 200 5825
[12Nov2021 10:10:03]
“GET /logon.php?user=admin’;%20—HTTP{/1.1” 200 5845
SQLMap
Automated SQLi
jSQL Injection
Java-based remote tester and SQLi deterrent tool
Havij
Web page vulnerability tester with automated SQLi
Burp
MITM web proxy for watching client-server interactions
BBQSQL
Python-based injection exploitation tool
Good for identifying sophisticated SQLi
Blisqy
Tests using time-based blind SQLi
Stored Procedures
Parameterized Queries
PHP Example
Python Example
SAFE CODING Java Example
page.php?user=0;%20TRUNCATE%20TABLE%20customers;
SELECT name, email, cust_type FROM customers WHERE userID = 0; TRUNCATE TABLE customers;
// Using traditional SQL question mark placeholders
$sql = 'SELECT name, cust_type FROM customers WHERE userID = ?';
$prep = $conn->prepare($sql);
$prep->execute([$_GET['user'], $_GET[‘cust_type']]); // indexed array
$result = $prep->fetchAll();
Normal query:
SELECT * FROM products WHERE name LIKE ‘’
Malicious query:
SELECT * FROM products WHERE name LIKE ‘%’; SELECT * FROM employees;
SQL query that retrieves a username and password for a login process
SELECT * FROM customers WHERE name = ‘’ AND password = ‘hashedInput’
An attacker could use a wildcard in SQLi
SQL query that retrieves a username and password for a login process
SELECT * FROM customers WHERE name = ‘’ AND password = ‘hashedInput’
An attacker could use a wildcard in SQLi
// Malicious queries:
SELECT * FROM employees WHERE ssn LIKE '%'
SELECT * FROM employees WHERE ssn LIKE '%'; DROP TABLE employees
/** If the attacker tries to enter ' ; or % those characters will lose their
special power and be treated as part of the social security number itself */
SELECT * FROM employees WHERE ssn LIKE '\'\;\% DROP TABLE employees'
15.11 SQL
INJECTION Review
REVIEW
INTRO TO
ETHICAL
SQL injection is most common vulnerability in websites
SQL injection uses non-validated input to send SQL commands through a Web app
HACKING
Common SQLi methods include error-based, UNION and blind SQL injection
REVIEW
A methodological approach must be taken to detect SQL injection vulnerabilities
INTRO TO
ETHICAL
SQL injection is most common vulnerability in websites
SQL injection uses non-validated input to send SQL commands through a Web app
HACKING
Common SQLi methods include error-based, UNION and blind SQL injection
REVIEW
A methodological approach must be taken to detect SQL injection vulnerabilities
The most basic SQL injection involves adding a single quote
You can return all rows in a table by injecting an always-true statement
such as OR 1=1
You can use the SQL inline comment -- to instruct the database engine
to ignore any other input (such as fields where you don’t know what
value to enter)
You can escape special characters so they are rendered useless when
used in SQL injection
Use parameterized queries and stored procedures to disallow users
from entering ad-hoc queries