程式碼安全漏洞修復說明 日期 : 99/6/22 叡揚資訊產品顧問林榮秋 Willy_lin@mail.gss.com.tw
常見安全的弱點修復說明 1. SQL Injection 2. Cross Site Scripting (XSS) 3. HTTP Response Splitting 4. Command Injection 5. Path Manipulation 6. Cross Site Request Forgery (CSRF) 7. Password Management 8. Race Conditions 9. Error Handling 10.Misconfiguration 2
程式碼修復說明 SQLInjection 3
SQL Injection 漏洞問題 [ X ] 有安全漏洞的 SQL 程式碼 ( 使用字串相加方式 ) ' or '1'='1 傳回所有 items Table 內的資料 4
預防 SQL Injection 漏洞的安全寫法 [ V ] 安全的寫法 ( 撰寫使用參數化 SQL 語法 ) ' or '1'='1 5 查無資料!
SQL Injection 問題 修補漏洞的安全撰寫方式範例 objcon.open() sqlstr = "Insert INTO [Announcements] (Title, Content, Creator, CreateTime) sqlstr = sqlstr & " Values( @parameter1, @parameter2, @parameter3, @parameter4 ) conn = New SqlCommand(sqlstr, objcon) conn.parameters.add("@parameter1", SqlDbType.NVarChar,20).Value = institletextbox.text conn.parameters.add("@parameter2", SqlDbType.NVarChar,100).Value = InsertHtmlEditor.HTML conn.parameters.add("@parameter3", SqlDbType.NVarChar,10).Value = uid conn.parameters.add("@parameter4", (@ SqlDbType.DateTime).Value = GETDATE() cnt = conn.executenonquery() 修改步驟解析 : [Step1] : 原本相加的字串, 改為 @ parameter1 ~ @ parametern [Step2] : 使用 conn.parameters.add(@ parameter1 ~ N) = 原本要相加變數 6
MS Help.Net Parameter 寫法的 Sample Code 7
MS Help : SqlDbType 列舉型別 8
9 SQL Injection 使用黑名單方式處理
SQL Injection 使用黑名單方式處理 駭客更高竿的鑽洞語法 itemname = " oorr 1=1 " +. 10
SQL 語法無法參數化的部分的安全寫法 11
SQL 語法無法參數化的部分的安全寫法 12
網站程式安全撰寫基本樣式 : N_To_S Pattern 13
程式碼修復說明 Cross-Site CossS Scripting (XSS) 14
Cross-site scripting (XSS) 常見類型 攻擊語法直接寫在超連結或引用的參數欄位 攻擊語法寫入在資料庫的字串欄位中 攻擊語法寫入在竄改的網頁 因為可以撰寫程式所以 XSS 變化無窮 不同的 XSS 攻擊法要用不同的防禦法 15
XSS 攻擊案例 : 總統府網站事件 16
17 XSS 攻擊案例 : 總統府網站事件
XSS 攻擊語法直接寫在引用的參數欄位 http://www.president.gov.tw/phpbin/dore2/list.php4?issuedate=&issueyy=&issue MM=&issueDD=&title=%3E%22+%3Ciframe+src% 3Dhttp://www.youtube.com/watch_popup?v%3 DTdFTeWHQ3CA%3E+%3Ci&content=& &_section=3& 3&_ piecelen=50&_orderby=issuedate,rid&_desc=1 配合電子郵件或部落格網頁撰寫超連結 XSS 攻擊 18
URL 連結 XSS 攻擊語法 + 搭配 Google 搜尋 19
XSS 修補漏洞的安全撰寫方式 XSS 攻擊語法致命傷 > 要撰寫程式所以字元數較多 執行前要加檢查程序 : (1) 合理長度值檢查 ( 白名單模式 ) On Server Side 例 : title 字串長度是否正常長度, 例如 title.length() < 20 (2) 不合理值檢查 ( 黑名單模式 ) On Server Side 例如 : iframe Convert.ToChar( 20
謹記在心 : 瀏覽器前端的驗證函式防駭功效不足 21 Client Side Validation 或 Client Side 限制資料長度 只能防呆, 不能防駭客竄改資料!
Use.Net Server 端的驗證控制項檢核資料 RequiredFieldValidator RangeValidator RegularExpressionValidator CompareValidator CustomValidator ValidationSummary 22
顯示資料到網頁的 XSS 防禦方式 HTTP Request Business Logic Database HTTP Response Display Logic Server.HtmlEncode() 23
ASP or ASP.Net 使用 Server.HtmlEncode() 說明 Encoding Mapping 駭客輸入 : <script> alert( xss ); </script> Server.HtmlEncode() 之後 <script> alert("xss"); </script> t& t 瀏覽器僅會顯示文字在網頁上 <script> alert( xss ); </script> 24
PHP 使用 Htmlspecialchars() Encoding Mapping 駭客輸入 : <script> alert( xss ); </script> Htmlspecialchars() 之後 <script> alert("xss"); </script> 瀏覽器僅會顯示文字在網頁上 <script> alert( xss ); </script> 25
.Net 對於 XSS 攻擊不安全的元件 26
XSS 問題程式 : Response.write () 修補漏洞的方式分析 輸出到網頁的 XSS 問題, 加 Server.HtmlEncode() 安全防護 修補漏洞的安全撰寫方式 Response.Write( Server.HtmlEncode(strReturn) ) ; 27
XSS 問題類型 : System.Web.UI.WebControls.BaseDataList.set_DataSource() DataSource() 修補漏洞的方式分析 DataList 預設套用的樣版物件是 Label 有 XSS 問題樣板中無法撰寫 Server.HtmlEncode() 所以修改方式之一是手動改樣版預設元件, 套用安全的 TextBox 元件 為了產生與 Label 相同呈現效果, 設定屬性 BorderStyle="None" ReadOnly="True" 28
Sample Code 29
程式碼修復說明 HTTP Response se Splitting 30
Header Manipulation 問題 Addition of unvalidated data to the HTTP header Could result in XSS vulnerability Browser cache poisoning Server cache poisoning Consider : <% response.sendredirect("/region.jsp? regioncode="+ request.getparameter("regioncode")); %> 31
Header Manipulation 問題 An HTTP response would look like : HTTP/1.1 302 Moved Temporarily Date: Wed, 24 Dec 2003 12:53:28 GMT Location: http://120.14.10.16/region.jsp?regioncode=us 14 10 16/region s Server: Apache 2.049 Fri Jan 2 13:15:34 PDT Content-Type: text/html Set-Cookie: JSESSIONID=alkjwerf345sdf0sd9f8; path=/ Connection: Close <html><head><title>302 Moved Temporarily</title></head> <body bgcolor="#ffffff"> <p>this document you requested has moved temporarily.</p> </body></html> 32
Header Manipulation 問題 Since input for region is not validated Attacker could supply /region.jsp?regioncode=us%0d%0acontent- i C t Length:%200%0d%0a%0d%0aHTTP/1.1%20200%20OK%0d%0aContent- Type:%20text/html%0d%0aContent- Length:%2019%0d%0a%0d%0a<html>Got you hacked mate!</html> 33
Header Manipulation 問題 Since input for region is not validated Attacker could supply HTTP/1.1 1 302 Moved Temporarily Date: Wed, 20 Jan 2003 15:26:41 GMT Location: 120.14.10.16/region.jsp?regionCode=us 1 st Response Content-Length: 0 1R Request, 2Responses (Response Splitting) Hacker provided data 2 nd Response (Controlled by Hacker) HTTP/1.1 200 OK Content-Type: text/html Content-Length: 19 <html>got you hacked mate!</html> Server: Apache 2.049 Fri Jan 20 15:26:41 PDT 2003 271009 with Content-Type: text/html Set-Cookie: JSESSIONID=123wertyu567345; path=/ Connection: Close... 34
Header Manipulation 問題 Normal User Proxy Server Hacker Hacker send 2 requests to HTTP Server Proxy server see 2 requests and 3 responses, dropped the last response and cached the hacker controlled response as the valid response for 2 nd request The 2 nd request is due to HTTP Response Splitting and is controlled by hacker
Good news for HTTP Response Splitting ASP.NET 2.0 By default,.net 2.0 will return 500 and throw exception when there is "\r\n" in methods that involve HTTP response headers You can set enableheaderchecking to false in web.config in order to disable this protection ASP.NET 1.1 Please apply ASP.NET SP1 To disable, <httpwebrequest useunsafeheaderparsing= true /> Tomcat 5.0 36 Tomcat will escape \r\n \ you try to add extra HTTP header Tomcat 4.x is vulnerable
HTTP Response Splitting 37
程式碼修復說明 Command Injection 38
Command Injection 安全漏洞問題 39
Command Injection 安全漏洞問題 40
程式碼修復說明 Path Manipulation at 41
Path Manipulation Hacker can control which file to be opened Filename: c:\data\ + filename filename../boot.ini Filepath: Can be solved by validation i path + myprog.dll Path can be c:\tmp\hacker _ upload\ check 42
Path Manipulation 43
程式碼修復說明 Cross Site Request Forgery (CSRF) 44
Cross-site request forgery (CSRF) Logged into a online bank, at the same time, browsing some other web sites 45
Cross-site request forgery The online bank The bank sends the money since this is a valid request Hacker Website Inside in the page, there is a image <img src="http://bank.example/transfer? account=victim&amount=1000000&for=hacker"> 46 The browser will send the request to the bank with a valid cookie.
How to fix : 使用需要人工識別的機制及驗證碼 47
程式碼修復說明 Password Management age e 48
Password Management Don t hard code password in source code You can t change password in the future Pretty easy to decompile and get the password in binary code Don t stored plain text password in config file or registry key DO: store obfuscated password in config file 49
Password Management: Sample Code <parameter> <name>url</name> <value>jdbc:...</value> </parameter> <parameter> <name>driverclassname</name> <value>com.oracle.jdbcdriver</value> oracle </parameter> <parameter> <name>username</name> <value> MGLQAbY6ADV49yWAQnaTztr742gGO1x= </value> </parameter> <parameter> <name>password</name> <value> DV49MGLQyWAGAbY6O1qQnaTztr742g= </value> </parameter> 50
程式碼修復說明 Race Conditions o 51
Race Condition : Multi-Thread Question: What s wrong with this code? public class GuestBook extends HttpServlet { } public static String name; protected void dopost (HttpServletRequest req, HttpServletResponse res) { } name = req.getparameter("name"); t ")... out.println(name + ", thanks for visiting!"); 52
Race Condition Answer: Hackers will hack Retrieve others customer information because value is explicit to hacker Thread 1 Thread 2 Value in name name = Dick Dick name = Jane Dick -> Jane Jane, Thanks for visiting Jane Jane, Thanks for visiting 53
Race Condition Answer: don t use class variable, using local variable public class GuestBook extends HttpServlet { } String name; protected void dopost (HttpServletRequest req, HttpServletResponse res){ String name = req.getparameter("name");... out.println(name tl + ", thanks for visiting!"); iti } 54
Race Condition (File) Question: What s wrong with this code? public class TocTou extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException {... File f = new File("/tmp/file.txt ); FileWriter fw = new FileWriter(f); fw.write(msg, 0, msg.length()); fw.close(); f.setreadonly();... Two users access the same page at the } } 55 same time. We will still use the same file name
Race Condition Solution public class TocTou extends HttpServlet { public void doget(httpservletrequest req, HttpServletResponse res) throws ServletException, IOException {... } File f = File.createTempFile( aaa,.tmp ); FileWriter fw = new FileWriter(f); fw.write(msg, 0, msg.length()); fw.close(); f.setreadonly();... } 56
程式碼修復說明 Error Handling 57
Poor Error Handling Question: What s wrong with this code? DataSet dataset = null; try { dataset = doexchange(); } catch ( Exception e) { e.printstacktrace(); } Overly broad Catch System Information Leak } (or Empty Catch Block if empty) 58
Poor Error Handling Dump Exception is not exception handling DataSet dataset = null; Boolean done = false; for(int i=0; i<3; i++) { try { dataset = doexchange(); done = true; break; } catch ( Exception e) { log.warn( Do Exchange Failed: ); } } if (!done ) return false; for(int i=0; i<dataset.size(); i++) { DataRow row = dataset.getrow(i); } Retry doexchange() 3 times Systematic logging framework 59
Poor Error Handling Don t send any part of the Exception to HTML 60
A better Error Page Save all data a to a file and allow admin to retrieve by using a UUID - All HTTP request headers - Exception details 61 But beware of your disk space
程式碼修復說明 Misconfiguration o 62
Misconfiguration: Environment <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" lt " Inherits="_Default" ValidateRequest="false" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/dtd/xhtml1- /TR/ transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> 63
程式碼修復說明 Value ueshadowing 64
Value Shadowing 問題 此程式以不明確的方式存取伺服器變數, 這可會使程式易受到攻擊 HttpRequest 類別提供透過程式從陣列存取表單中 QueryString Form Cookies 或 ServerVariables 集合存取變數的能力 如 Request[ myparam ]) 當有一個以上名稱相同的變數時,.NET framwork 會傳回在集合以下列順序搜尋時, 第一個出現的變數值 :QueryString Form Cookies, 然後 ServerVariables 因為 QueryString 依搜尋順序第一個出現, 因此 QueryString 參數可以取代 Form cookie 及伺服器變數的值 同樣地,Form 值可以取代 Cookies 和 ServerVariables 集合中的變數, 而 Cookies 集合的變數可取代 ServerVariables 的變數 65
Value Shadowing 修改方式 有安全漏洞問題的程式碼 修補漏洞的安全撰寫方式 >> 使用明確的集合名稱存取 strfunc = (Request.Form["Func"] ==null? : Request.Form["Func"]); strfunc = Request.Cookies ["Func"]; strfunc = Request.ServerVariables ["Func"]; strfunc = Request.QueryString ["Func"]; 66
意見討論 67