Microsoft PowerPoint - TKU_安全的程式碼撰寫教育訓練_AppVuln pptx

Similar documents
導讀 ASP.NET HTML ASP 第一篇 基礎篇第 1 章 認識 ASP.NET ASP.NET ASP.NET ASP.NET ASP.NET 第 2 章 認識 Visual Studio 20 開發環境 Visual Studio 20 Visual Studio 20 第二篇 C# 程式

1.JasperReport ireport JasperReport ireport JDK JDK JDK JDK ant ant...6

Microsoft Word - WebGoat用户指南-beta2.doc

untitled

untitled

一 個 SQL Injection 實 例 的 啟 示 頁 2 / 6 因 此, 在 知 名 網 站 上 看 到 SQL Injection, 讓 人 驚 心, 卻 不 意 外 網 站 專 案 外 包 是 目 前 業 界 的 常 態, 而 在 價 格 取 勝 的 制 度 下, 低 價 得 標 的 S

untitled

6-1 Table Column Data Type Row Record 1. DBMS 2. DBMS MySQL Microsoft Access SQL Server Oracle 3. ODBC SQL 1. Structured Query Language 2. IBM

(TestFailure) JUnit Framework AssertionFailedError JUnit Composite TestSuite Test TestSuite run() run() JUnit

Important Notice SUNPLUS TECHNOLOGY CO. reserves the right to change this documentation without prior notice. Information provided by SUNPLUS TECHNOLO

EJB-Programming-4-cn.doc

epub 61-2

Microsoft Word - template.doc

Microsoft Word - Ch06.docx

untitled

Microsoft Word - 01.DOC

Servlet

untitled


ch_code_infoaccess

untitled

RUN_PC連載_8_.doc

Windows XP

Microsoft PowerPoint - 程式碼安全_Java_1126.ppt

chapter 2 HTML5 目錄iii HTML HTML HTML HTML HTML canvas

Fun Time (1) What happens in memory? 1 i n t i ; 2 s h o r t j ; 3 double k ; 4 char c = a ; 5 i = 3; j = 2; 6 k = i j ; H.-T. Lin (NTU CSIE) Referenc

AL-M200 Series

(CIP) Web /,. :, ISBN X.W T P393.4 CIP (2004) Web ( ) ( / ) : * 787

PowerPoint Presentation

第一章 章标题-F2 上空24,下空24

Microsoft PowerPoint - TKU_安全的程式碼撰寫教育訓練990622_Ok1.pptx

1 1 大概思路 创建 WebAPI 创建 CrossMainController 并编写 Nuget 安装 microsoft.aspnet.webapi.cors 跨域设置路由 编写 Jquery EasyUI 界面 运行效果 2 创建 WebAPI 创建 WebAPI, 新建 -> 项目 ->

p.2 1 <HTML> 2 3 <HEAD> 4 <TITLE> </TITLE> 5 </HEAD> 6 7 <BODY> 8 <H3><B> </B></H3> 9 <H4><I> </I></H4> 10 </BODY> </HTML> 1. HTML 1. 2.

untitled

untitled

IP505SM_manual_cn.doc

untitled

untitled

Microsoft Word - Functional_Notes_3.90_CN.doc

WebSphere Studio Application Developer IBM Portal Toolkit... 2/21 1. WebSphere Portal Portal WebSphere Application Server stopserver.bat -configfile..

ebook140-9

untitled

關於本書 Part 3 CSS XHTML Ajax Part 4 HTML 5 API JavaScript HTML 5 API Canvas API ( ) Video/Audio API ( ) Drag and Drop API ( ) Geolocation API ( ) Part 5

目錄

入學考試網上報名指南

Microsoft Word doc

<ADB6ADB1C25EA8FAA6DB2D4D56432E706466>

RUN_PC連載_10_.doc

( Version 0.4 ) 1

软件概述

概述

105 年 國 中 教 育 會 考 重 要 日 期 項 目 日 期 及 時 間 報 名 1. 集 體 報 名 :105 年 3 月 10 日 ( 星 期 四 ) 至 3 月 12 日 ( 星 期 六 ) 每 日 8:00~12:00 13:30~17:00 2. 個 別 報 名 : 於 上 網 填

RunPC2_.doc

Microsoft Word - Final Exam Review Packet.docx

Microsoft Word - SupplyIT manual 3_cn_david.doc

untitled

05 01 accordion UI containers 03 Accordion accordion UI accordion 54

Microsoft PowerPoint - 05-Status-Codes-Chinese.ppt

Microsoft Word - PHP7Ch01.docx

Untitiled

TopTest_Adminstrator.doc

1.ai

untitled

TX-NR3030_BAS_Cs_ indd

Microsoft Word - (web)_F.1_Notes_&_Application_Form(Chi)(non-SPCCPS)_16-17.doc

XML/DTD (1) XML (Markup) SGML HTML XML XML XML 2004/7/ All Rights Reserved 2

Microsoft Word - A doc

D getinitparameternames() 9 下 列 选 项 中, 属 于 Servlet API 中 提 供 的 request 对 象 的 包 装 类 的 是 ( ) A HttpServletRequestWrapper B HttpServletRequest C HttpServ

2 response personnel to speed up the rescue operations after various natural or man-made disasters. Keywords: SMS, Database, Disaster

Bus Hound 5

Perl

Chn 116 Neh.d.01.nis

新北考區105年國中教育會考簡章

epub83-1

EJB-Programming-3.PDF

chp6.ppt

投影片 1

ebook140-8

59 1 CSpace 2 CSpace CSpace URL CSpace 1 CSpace URL 2 Lucene 3 ID 4 ID Web 1. 2 CSpace LireSolr 3 LireSolr 3 Web LireSolr ID

XXXXXXXX

Abstract Since 1980 s, the Coca-Cola came into China and developed rapidly. From 1985 to now, the numbers of bottlers has increased from 3 to 23, and

「人名權威檔」資料庫欄位建置表

國立桃園高中96學年度新生始業輔導新生手冊目錄

Microsoft Word - Web Dynpro For ABAP跟踪测试工具简介 _2_.doc

〇〇考區105年國中教育會考簡章

Lorem ipsum dolor sit amet, consectetuer adipiscing elit

2005硕士论文模版

untitled

RUN_PC連載_12_.doc

USPTO Academic research Corporate needs Global/International Inventors Libraries News Media/Publication Patent Attorney or Agent USPTO e (ebusiness Ce

1 SQL Server 2005 SQL Server Microsoft Windows Server 2003NTFS NTFS SQL Server 2000 Randy Dyess DBA SQL Server SQL Server DBA SQL Server SQL Se

Product Type Batteries (only) Circuit Breatkers & Load Protection Connection Devices Contactors Ethernet Switches, Stratix Switches I/O Modules; PLC N

錄...1 說...2 說 說...5 六 率 POST PAY PREPAY DEPOSIT 更

Logitech Wireless Combo MK45 English

雲端 Cloud Computing 技術指南 運算 應用 平台與架構 10/04/15 11:55:46 INFO 10/04/15 11:55:53 INFO 10/04/15 11:55:56 INFO 10/04/15 11:56:05 INFO 10/04/15 11:56:07 INFO

CANVIO_AEROCAST_CS_EN.indd

Chapter 9: Objects and Classes

ebook4-12

HCD0174_2008

Microsoft Word - 口試本封面.doc

Transcription:

程式碼安全漏洞修復說明 日期 : 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