<<

Web Security: Sessions; CSRF; start on authentication

CS 161: Security Prof. Raluca Ada Popa Nov 10, 2016

Credit: some slides are adapted from previous offerings of this course or from CS 241 of Prof. Dan Boneh Announcements

Proj 3 due on Thur, Nov 17 Recall: Cookie scope

GET … Server HTTP Header: Set-cookie: NAME=VALUE ; domain = (when to send) ; scope path = (when to send) secure = (only send over SSL); expires = (when expires) ; HttpOnly • Expires is expiration date

• Delete cookie by setting “expires” to date in past • HttpOnly: cookie cannot be accessed by Javascript, but only sent by browser Recall: What scope a server may set for a cookie domain: any domain-suffix of URL-hostname, except TLD [top-level domains, e.g. ‘.com’] example: host = “login.site.com” allowed domains disallowed domains login.site.com user.site.com .site.com othersite.com .com path: can be set to anything Recall: When browser sends cookie

Server GET //URL-domain/URL-path Cookie: NAME = VALUE

A cookie with domain = example.com, and path = /some/path/ will be included on a request to http://foo.example.com/some/path/subdirectory/hello.txt Client side read/write: document.cookie

Setting a cookie in Javascript: document.cookie = “name=value; expires=…; ”

Reading a cookie: alert(document.cookie) prints string containing all cookies available for document (based on [protocol], domain, path)

Deleting a cookie: document.cookie = “name=; expires= Thu, 01-Jan-00”

document.cookie often used to customize page in Javascript Viewing/deleting cookies in Browser UI

Firefox: Tools -> page info -> security -> view cookies Sessions Sessions

A sequence of requests and responses from one browser to one (or more) sites

n Session can be long (Gmail - two weeks) or short (e.g., banking)

n without session mgmt:

users would have to constantly re-authenticate

Session management:

n Authorize user once;

n All subsequent requests are tied to user Pre-history: HTTP auth

HTTP request: GET /index.html HTTP response contains: WWW-Authenticate: Basic realm="Password Required“

://cs161.berkeley.edu

Browsers sends hashed password on all subsequent HTTP requests: Authorization: Basic ZGFddfibzsdfgkjheczI1NXRleHQ=

What problems can you see with this model? HTTP auth problems

Hardly used in commercial sites

n User cannot log out other than by closing browser w What if user has multiple accounts? w What if multiple users on same computer?

n Site cannot customize password dialog

n Confusing dialog to users

n Easily spoofed Session tokens

Browser Web Site GET /index.

set anonymous session token

GET /books.html anonymous session token

POST /do-login check Username & password credentials elevate to a logged-in session token

POST /checkout logged-in session token Validate token Storing session tokens: Lots of options (but none are perfect)

• Browser cookie: Set-Cookie: SessionToken=fduhye63sfdb

• Embedd in all URL : https://site.com/checkout ? SessionToken=kh7y3b

• In a hidden form field:

Can you see problems with these? Storing session tokens: problems

• Browser cookie: browser sends cookie with every request, even when it should not (see CSRF attack)

• Embed in all URL links: token leaks via HTTP Referer header (your browser tells a site which previous site it visited last in the Referer header, which may contain session tokens)

• In a hidden form field: short sessions only

Best answer: a combination of all of the above. Cross Site Request Forgery RN Release Notes RNRNRN ReleaseRelease Notes NotesNotes

What Changed From 2010 to 2013? WhatWhat Changed From 2010 toto 2013?2013? WhatThe threat Changed landscape for From applications 2010 security to constantly2013? changes. Key factors in this evolution are advances made by attackers, ThetheTheThe releasethreat threatthreat landscape oflandscape new technologies for for applications applications with security new security weaknesses constantly constantlyconstantly as changes. changes.wellchanges. as Keymore Key Key factors factors builtfactors in in defenses,thisin this this evolution evolution evolution and arethe are are advances deployment advances advances made made madeof byincreasingly by attackeby attacke attackers, rs, rs, thecomplexthethe release releaserelease systems. of ofof new new Totechnologies technologies keep pace, with wewith periodicallynew newnew weaknesses weaknessesweaknesses update as as aswellthe wellwell OWASPas as asmore more more Top built built built 10. in in defenses,Inin defenses, thisdefenses, 2013 and and release,and the the the deployment deployment wedeployment made ofthe ofincreasingly of followingincreasingly increasingly changes: complex complexcomplex systems. systems. To To keep keep pace, pace, we we periodically periodically update updateupdate the thethe OWASP OWASPOWASP Top Top Top 10. 10. 10. In In thisIn this this 2013 2013 2013 release, release, release, we we wemade made made the the the following following following changes: changes: changes: 1) Broken Authentication and Session Management moved up in prevalence based on our data set. We believe this is probably 1)1)1) BrokenbecauseBrokenBroken Authentication Authenticationthis area is being and and lookedSession Session at Management Managementharder,Management not becausemoved movedmoved up these upup in in prevalencein prevalence issuesprevalence are based actually based based on on onmoreour our our data prevalent.data data set. set. set. We We We Thisbelieve believe believe caused this this this isRisks probablyis is probably probablyA2 and becauseA3becausebecause to switch this this area places. area is isbeing being looked looked at at harder, harder,harder, not notnot because becausebecause these thesethese issues issues issues are are are actually actually actually more more more prevalent. prevalent. prevalent. This This This caused caused caused Risks Risks Risks A2 A2 andA2 and and A3 A3A3 to toto switch switch places. places. 2) Cross -Site Request Forgery (CSRF) moved down in prevalence based on our data set from 2010-A5 to 2013-A8. We believe 2)2)2) CrossthisCrossCross is-Site -because-Site Request Request CSRF Forgery Forgery has been (CSRF) (CSRF) in the moved movedmoved OWASP down downdown Top in in inprevalence10 prevalenceprevalence for 6 years, based basedbased and on organizationson on our our our data data data set set set fromand from from framework 2010 2010 2010-A5-A5- A5to developersto 2013to 2013 2013-A8.-A8.- A8.We have We Webelieve believe focused believe thisonthisthis it is isenoughis because becausebecause to CSRF CSRFsignificantly has has been been reduce in in the thethe OWASPthe OWASPOWASP number Top TopTop 10 of 1010 forCSRF forfor 6 6years,6vulnerabilities years,years, and and and organizations organizations organizations in real world and and and applications.framework framework framework developers developers developers have have have focused focused focused on onon it it itenough enough to to significantly significantly reduce reduce the thethe number numbernumber of of ofCSRF CSRFCSRF vulnerabilities vulnerabilitiesvulnerabilities in inrealin real real world world world applications. applications. applications. 3) We broadened Failure to Restrict URL Access from the 2010 OWASP Top 10 to be more inclusive: 3)3)3) We WeWe broadened broadened Failure Failure to to Restrict Restrict URL URL Access AccessAccess from fromfrom the thethe 2010 20102010 OWASP OWASPOWASP Top Top Top 10 10 10to to beto be bemore more more inclusive: inclusive: inclusive: + 2010-A8: Failure to Restrict URL Access is now 2013-A7: Missing Function Level Access Control – to cover all of function +++ 2010level2010- A8:access-A8: Failure Failure control. to to Restrict RestrictThere URLare URL manyAccess AccessAccess ways is isnowis nownowto 2013specify 20132013-A7:- -A7:whichA7: Missing MissingMissing function Function Function Function is being Level Level Level accessed, Access Access Access Control Controlnot Control just – to –the – to cover to URL.cover cover all all of all offunction of function function levellevellevel access accessaccess control. control. There There are areare many manymany ways waysways to to tospecify specifyspecify which whichwhich function function function is isbeing is being being accessed, accessed, accessed, not not not just just just the the the URL. URL. URL. 4) We merged and broadened 2010-A7 & 2010-A9 to CREATE: 2013-A6: Sensitive Data Exposure: 4) 4)4) WeWeWe merged merged and and broadened broadened 2010 2010-A7--A7 & &&2010 20102010-A9--A9A9 to to toCREATE: CREATE:CREATE: 2013 2013 2013-A6:--A6:A6: Sensitive Sensitive Sensitive Data Data Data Exposure Exposure Exposure: : : – This new category was created by merging 2010-A7 – Insecure Cryptographic Storage & 2010-A9 - Insufficient Transport ––– ThisThis new new category category was was created created by byby merging mergingmerging 2010 20102010-A7--A7A7 – Insecure–– InsecureInsecure Cryptographic Cryptographic Cryptographic Storage Storage Storage & &2010 & 2010 2010-A9-A9- A9- Insufficient - -Insufficient Insufficient Transport Transport Transport Layer Protection, plus adding browser side sensitive data risks as well. This new category covers sensitive data LayerLayer Protection, Protection, plus plus adding adding browser browserbrowser side sideside sensitive sensitivesensitive data datadata risks risks risks as as aswell. well. well. This This This new new new category category category covers covers covers sensitive sensitive sensitive data data data protection (other than access control which is covered by 2013-A4 and 2013-A7) from the moment sensitive data is protectionprotection (other (other than than access access control controlcontrol which whichwhich is iscoveredis coveredcovered by byby 2013 2013 2013-A4--A4A4 and and and 2013 2013 2013-A7)-A7)-A7) from from from the the the moment moment moment sensitive sensitive sensitive data data data is is is provided by the user, sent to and stored within the application, and then sent back to the browser again. providedprovided by by the the user, user, sent sent to to and and stored storedstored within withinwithin the thethe application, application,application, and and and then then then sent sent sent back back back to to theto the the browser browser browser again. again. again. 5)5)5) WeWeWe added:added: added: 2013 2013 2013-A9:-A9:-A9: Using Using Using Known Known Known Vulnerable VulnerableVulnerable Components ComponentsComponents: : 5) We added: 2013-A9: Using Known Vulnerable Components:

Top++++ ThisThisThis issueissue issue was was wasweb mentioned mentioned mentioned as asas part partpartvulnerabilities of of ofof 2010 2010 20102010-A6---A6A6A6 – –Security– Security Security Misconfiguration, Misconfiguration, Misconfiguration, but butbut but now now nownow has has hashas a category a aa category categorycategory of ofits ofof its ownitsits own ownown as as the asas the the the growthgrowthgrowth and and and depth depth depth of of of component component component based based basedbased development development developmentdevelopment has hashas significantly significantly significantly increased increasedincreased increased the the thethe risk risk riskrisk of of usingofof using usingusing known known knownknown vulnerable vulnerable vulnerablevulnerable components.components.components. OWASPOWASPOWASPOWASP Top TopTop 10 1010 – –– 2010 20102010 (Previous) (Previous)(Previous)(Previous) OWASPOWASPOWASP Top TopTopTop 10 10 1010 – – –2013– 2013 20132013 (New) (New) (New)(New)

A1A1A1A1 –– – – InjectionInjection InjectionInjection A1A1A1 – Injection– – Injection Injection

A3A3A3A3 –– – – BrokenBroken BrokenBroken Authentication Authentication Authentication and and and Session Session Session Management Management ManagementManagement A2A2A2 – Broken– – Broken Broken Authentication AuthenticationAuthentication Authentication and and andand Session Session SessionSession Management Management ManagementManagement

A2A2A2A2 –– – – CrossCross CrossCross--SiteSite--Site Scripting Scripting Scripting (XSS) (XSS) (XSS) A3A3A3 – Cross– – Cross Cross-Site--Site-Site Scripting Scripting ScriptingScripting (XSS) (XSS) (XSS)(XSS)

A4A4A4A4 –– – – InsecureInsecure InsecureInsecure Direct Direct Direct Object Object Object References References References A4A4A4 – Insecure– – Insecure Insecure Direct DirectDirect Direct Object Object ObjectObject References References ReferencesReferences

A6A6A6A6 –– – – SecuritySecurity SecuritySecurity Misconfiguration Misconfiguration Misconfiguration A5A5A5 – Security– – Security Security Misconfiguration Misconfiguration MisconfigurationMisconfiguration A6A6 – Sensitive– Sensitive Data Data Exposure Exposure A7A7A7A7 –– – – InsecureInsecure InsecureInsecure Cryptographic Cryptographic Cryptographic Storage Storage Storage – – –Merged Merged MergedMerged with with withwith A9 A9 A9A9 A6A6 – – SensitiveSensitive DataData ExposureExposure A8A8 – –Failure Failure to to Restrict Restrict URL URL Access Access – –Broadened Broadened into into A7A7 – Missing– Missing Function Function Level Level Access Access Control Control A8A8 – – Failure Failure to to Restrict Restrict URL URL Access Access – – Broadened Broadened into into A7A7 – – MissingMissing FunctionFunction LevelLevel AccessAccess ControlControl A5A5 – –Cross Cross-Site-Site Request Request Forgery Forgery (CSRF) (CSRF) A8A8 – Cross– Cross-Site-Site Request Request Forgery Forgery (CSRF) (CSRF) A5A5 – – Cross Cross-Site-Site Request Request Forgery Forgery (CSRF) (CSRF) A8A8 – – CrossCross--SiteSite RequestRequest ForgeryForgery (CSRF)(CSRF) > A9A9 – Using– Using Known Known Vulnerable Vulnerable Components Components > A9A9 – – UsingUsing KnownKnown VulnerableVulnerable ComponentsComponents A10A10 – –Unvalidated Unvalidated Redirects Redirects and and Forwards Forwards A10A10 – Unvalidated– Unvalidated Redirects Redirects and and Forwards Forwards A10A10 – – Unvalidated Unvalidated Redirects Redirects and and Forwards Forwards A10A10 –– UnvalidatedUnvalidated RedirectsRedirects andand ForwardsForwards A9A9 – –Insufficient Insufficient Transport Transport Layer Layer Protection Protection MergedMerged with with 2010 2010-A7-A7 into into new new 2013 2013-A6-A6 A9A9 – – Insufficient Insufficient Transport Transport Layer Layer Protection Protection MergedMerged with with 20102010--A7A7 intointo newnew 20132013--A6A6

16 HTML Forms

Allow a user to provide some data which gets sent with an HTTP POST request to a server

First name:

Last name:

When filling in Alice and Smith, and clicking submit, the browser issues

HTTP POST request bank.com/action.php?firstname=Alice&lastname=Smith As always, the browser attaches relevant cookies Recall: session using cookies

Browser Server Basic picture

Server Victim bank.com

1

4

2

User Victim

cookie for Attack Server bank.com

What can go bad? URL contains transaction action, bank checks cookie Cross Site Request Forgery (CSRF)

Example:

n User logs in to bank.com w Session cookie remains in browser state

n User visits malicious site containing:

n Browser sends user auth cookie with request w Transaction will be fulfilled Problem:

n cookie auth is insufficient when side effects occur Form with cookie

Cookie: SessionID=523FA4cd2E

User credentials Form post with cookie

Cookie: SessionID=523FA4cd2E

User credentials 2008 CSRF attack

An attacker could • add videos to a user’s "Favorites," • add himself to a user’s "Friend" or "Family" list, • send arbitrary messages on the user’s behalf, • flagged videos as inappropriate, • automatically shared a video with a user’s contacts, subscribed a user to a "channel" (a set of videos published by one person or group), and • added videos to a user’s "QuickList" (a list of videos a user intends to watch at a later point).

Defenses CSRF Defenses

Secret Validation Token

Referer Validation

Referer: http://www.facebook.com/home.php

Others (e.g., custom HTTP Header)

X-Requested-By: XMLHttpRequest Secret Token Validation

The server requests a secret token for every action, the user’s browser obtained this token if the user visited the site and browsed to that action, instead of directly sending an action; attacker won’t have the token 1. goodsite.com server includes a secret token into the webpage (e.g., in forms as a hidden field) 2. Requests to goodsite.com include the secret 3. goodsite.com server checks that the token embedded in the webpage is the expected one; reject request if not Can the token be?

• 123456

• Dateofbirth Validation token must be hard to guess by the attacker How token is used

! The server stores state that binds the user's CSRF token to the user's session id

! Embeds CSRF token in every form

! On every request the server validates that the supplied CSRF token is associated with the user's session id

! Disadvantage is that the server needs to maintain a large state table to validate the tokens. Other CRSF protection: Referer Validation

– When the browser issues an HTTP request, it includes a referer header that indicates which URL initiated the request

– This information in the Referer header could be used to distinguish between same site request and cross site request Referer Validation Referer Validation Defense

HTTP Referer header n Referer: http://www.facebook.com/ ü n Referer: http://www.attacker.com/evil.html û n Referer: ? w Strict policy disallows (secure, less usable) w Lenient policy allows (less secure, more usable) Privacy Issues with Referer header

! The referer contains sensitive information that impinges on the privacy

! The referer header reveals contents of the search query that lead to visit a .

! Some organizations are concerned that confidential information about their corporate intranet might leak to external via Referer header Referer Privacy Problems

Referer may leak privacy-sensitive information http://intranet.corp.apple.com/ projects/iphone/competitors.html Common sources of blocking:

n Network stripping by the organization

n Network stripping by local machine

n Stripped by browser for HTTPS -> HTTP transitions

n User preference in browser

Hence, such block might help attackers in the lenient policy case Custom HTTP Headers

– Browsers prevent sites from sending custom HTTP headers to another site but allow sites to send custom HTTP headers to themselves. – Cookie value is not actually required to prevent CSRF attacks, the mere presence of the header is sufficient. – To use this scheme as a CSRF Defense, a site must issue all state modifying requests using XMLHttpRequest, attach the header and reject all requests that do not accompany the header . Custom Header Defense

XMLHttpRequest is for same-origin requests

n Can use setRequestHeader within origin Limitations on data export format

n No setRequestHeader equivalent

n XHR2 has a whitelist for cross-site requests Issue POST requests via AJAX:

Doesn't work across domains

X-Requested-By: XMLHttpRequest Summary: sessions and CSRF

Cookies add state to HTTP

n Cookies are used for session management

n They are attached by the browser automatically to HTTP requests CSRF attacks execute request on benign site because cookie is sent automatically Defenses for CSRF:

n embed unpredicatable token and check it later

n check referer header Authentication & Impersonation Authentication

Verifying someone really is who they say they claim they are should authenticate client Client should authenticate web server Impersonation

Pretending to be someone else Attacker can try to:

n Impersonate client

n Impersonate server Authenticating users

How can a computer authenticate the user?

n “Something you know” w e.g., password, PIN

n “Something you have” w e.g., smartphone, ATM card, car key

n “Something you are” w e.g., fingerprint, iris scan, facial recognition Two-factor authentication

Authentication using two of:

n Something you know (account details or passwords)

n Something you have (tokens or mobile phones)

n Something you are (biometrics) Example

Online banking:

n Hardware token or card (“smth you have”)

n Password (“smth you know”) Mobile phone two-factor authentication:

- Password (“smth you know”)

- Code received via SMS (“smth you have”) Is this a good 2FA?

Password + Answer to security question

This is not two-factor authentication because both of the factors are something you know After authenticating..

Session established

n Session ID stored in cookie

n Web server maintains list of active sessions (sessionID mapped to user info) Reauthentication happens on every http request automatically

n Recall that every http request contains cookie After authenticating..

Alice

Server

sessionID = Active sessions: 3458904043 sessionID | name Must be unpredictable 3458904043 | Alice 5465246234 | Bob Session hijacking attack: • Attacker steals sessionID, e.g., using a packet sniffer • Impersonates user After authenticating..

Alice

Server

sessionID = Active sessions: 3458904043 3458904043 | Alice Must be unpredictable 5465246234 | Bob

Protect sessionID from packet sniffers: • Send encrypted over HTTPS • Use secure flag to ensure this When should session/cookie expire? • Often is more secure • But less usable for user Other flags? • httponly to prevent scripts from getting to it After authenticating..

Alice

Server

sessionID = Active sessions: 3458904043 3458904043 | Alice Must be unpredictable 5465246234 | Bob

What if attacker obtains old sessionID somehow?

• When user logs out, server must remove Alice’s entry from active sessions • Server must not reuse the same session ID in the future • Old sessionID will not be useful Authenticating the server

Why should user authenticate the web server she is interacting with? User is introducing sensitive data to server including credentials for performing actions Phishing

Attacker creates fake website that appears similar to a real one Tricks user to visit site (e.g. sending email) User inserts credentials and sensitive data which gets sent to attacker then directs to real site or shows maintenance issues http://paypal.attacker.com/

http://ebay.attacker.com/ http://ebay.attacker.com/ http://ebay.attacker.com/ http://ebay.attacker.com/ http://ebay.attacker.com/ Phishing prevention

User should check URL!

http://ebay.attacker.com/ Does not suffice to check what it says you click on

Now go to Google! http://google.com

Because it can be: http://google.com

Check the address bar! URL obfuscation attack

Attacker can choose similarly looking URL with a typo

bankofamerca.com bankofthevvest.com Homeograph attack

- Unicode characters from international alphabets may be used in

paypal.com (first p in Cyrillic)

- URL seems correct, but is not

Another example: www.pnc.com⁄webapp⁄unsec⁄homepage.var.cn Phishing prevention

User should check URL! n Carefully! “Spear Phishing”

Targeted phishing that includes details that seemingly must mean it’s legitimate Yep, this is itself a spear-phishing attack! Sophisticated phishing

Context-aware phishing – 10% users fooled

n Spoofed email includes info related to a recent eBay transaction/listing/purchase Social phishing – 70% users fooled

n Send spoofed email appearing to be from one of the victim’s friends (inferred using social networks)

West Point experiment

n Cadets received a spoofed email near end of semester: “There was a problem with your last grade report; click here to resolve it.” 80% clicked. Why does phishing work?

User mental model vs. reality

n Browser security model too hard to understand! The easy path is insecure; the secure path takes extra effort Risks are rare Authenticating the server

Users should:

n Check the address bar carefully. Or, load the site via a or by typing into the address bar.

n Guard against spam

n Do not click on links, attachments from unknown Browsers also receive regular blacklists of phishing sites (but this is not immediate) Mail servers try to eliminate phishing email Questions?