38
Web Security: Session Management CS155 *Original slides were created by Prof. Dan Boneh

Web Security: Session Management - cs.columbia.edusuman/6183_slides/sess_mgmt.pdfeven when it should not (CSRF) Embed in all URL links: token leaks via HTTP Referer header In a hidden

  • Upload
    dotu

  • View
    224

  • Download
    0

Embed Size (px)

Citation preview

Web Security: Session Management

CS155

*OriginalslideswerecreatedbyProf.DanBoneh

Sameoriginpolicy:reviewReview:SameOriginPolicy(SOP)forDOM:

– OriginAcanaccessoriginB’sDOMifmatchon (scheme,domain,port)

Thislecture:SameOriginalPolicy(SOP)forcookies:

–  Basedon:([scheme],domain,path)

optional

scheme://domain:port/path?params

scope

Setting/deleting cookies by server

Default scope is domain and path of setting URL

BrowserServer

GET …

HTTP Header: Set-cookie: NAME=VALUE ;

domain = (when to send) ; path = (when to send) secure = (only send over SSL); expires = (when expires) ; HttpOnly

ifexpires=NULL:thissessiononly

ifexpires=pastdate:browserdeletescookie

Scope setting rules (write SOP) domain:anydomain-suffixofURL-hostname,exceptTLD

example:host=“login.site.com”

⇒ login.site.comcansetcookiesforallof.site.combutnotforanothersiteorTLD

ProblemaQcforsiteslike.stanford.edu(andsomehosQngcenters)

path:canbesettoanything

allowed domains login.site.com

.site.com

disallowed domains other.site.com othersite.com

.com

Cookies are identified by (name,domain,path)

Both cookies stored in browser’s cookie jar both are in scope of login.site.com

cookie 1 name = userid value = test domain = login.site.com path = / secure

cookie 2 name = userid value = test123 domain = .site.com path = / secure

disQnctcookies

Reading cookies on server (read SOP)

BrowsersendsallcookiesinURLscope:

•  cookie-domainisdomain-suffixofURL-domain,and

•  cookie-pathisprefixofURL-path,and•  [protocol=HTTPSifcookieis“secure”]

Goal:serveronlyseescookiesinitsscope

BrowserServerGET//URL-domain/URL-path

Cookie:NAME=VALUE

Examples

hZp://checkout.site.com/hZp://login.site.com/hZps://login.site.com/

cookie1name=useridvalue=u1domain=login.site.compath=/secure

cookie2name=useridvalue=u2domain=.site.compath=/non-secure

both set by login.site.com

cookie:userid=u2cookie:userid=u2cookie:userid=u1;userid=u2

Clientsideread/write:document.cookie

Se?ngacookieinJavascript: document.cookie=“name=value;expires=…;”

Readingacookie: alert(document.cookie) printsstringcontainingallcookiesavailablefor

document(basedon[protocol],domain,path)

DeleCngacookie: document.cookie=“name=;expires=Thu,01-Jan-70”

document.cookieobenusedtocustomizepageinJavascript

javascript: alert(document.cookie)

Javascript URL

Displays all cookies for current document

Viewing/deleting cookies in Browser UI

Cookieprotocolproblems

Cookie protocol problems Serverisblind:

–  DoesnotseecookieaZributes(e.g.secure,HZpOnly)–  Doesnotseewhichdomainsetthecookie

Serveronlysees:Cookie:NAME=VALUE

Example 1: login server problems 1.  Alicelogsinatlogin.site.com login.site.comsetssession-idcookiefor.site.com

2.Alicevisitsevil.site.com overwrites.site.comsession-idcookie

withsession-idofuser“badguy”

3.Alicevisitscourse.site.comtosubmithomework course.site.comthinksitistalkingto“badguy”

Problem:course.site.comexpectssession-idfromlogin.site.com; cannottellthatsession-idcookiewasoverwriZen

Example 2: “secure” cookies are not secure

AlicelogsinathNps://accounts.google.com

AlicevisitshNp://www.google.com(cleartext)•  NetworkaZackercaninjectintoresponse

Set-Cookie:SSID=badguy;secureandoverwritesecurecookie

Problem:networkaZackercanre-writeHTTPScookies! ⇒HTTPScookievaluecannotbetrusted

set-cookie:SSID=A7_ESAgDpKYk5TGnf;Domain=.google.com;Path=/; Expires=Wed,09-Mar-202318:35:11GMT;Secure;HNpOnly

set-cookie:SAPISID=wj1gYKLFy-RmWybP/ANtKMtPIHNambvdI4;Domain=.google.com;Path=/; Expires=Wed,09-Mar-202318:35:11GMT;Secure

Interaction with the DOM SOP CookieSOPpathseparaQon: x.com/Adoesnotseecookiesofx.com/B

Notasecuritymeasure:x.com/AhasaccesstoDOMofx.com/B

<iframesrc=“x.com/B"></iframe>

alert(frames[0].document.cookie);

PathseparaQonisdoneforefficiencynotsecurity: x.com/Aisonlysentthecookiesitneeds

Cookies have no integrity Usercanchangeanddeletecookievalues

•  Editcookiedatabase(FF:cookies.sqlite)•  ModifyCookieheader(FF:TamperDataextension)

Sillyexample:shoppingcartsobware Set-cookie: shopping-cart-total=150($)

Usereditscookiefile(cookiepoisoning): Cookie: shopping-cart-total=15($)

Similarproblemwithhiddenfields<INPUTTYPE=“hidden”NAME=priceVALUE=“150”>

16

17

Not so silly … (as of 2/2000)

•  D3.COM Pty Ltd: ShopFactory 5.8 •  @Retail Corporation: @Retail •  Adgrafix: Check It Out •  Baron Consulting Group: WebSite Tool •  ComCity Corporation: SalesCart •  Crested Butte Software: EasyCart •  Dansie.net: Dansie Shopping Cart •  Intelligent Vending Systems: Intellivend •  Make-a-Store: Make-a-Store OrderPage •  McMurtrey/Whitaker & Associates: Cart32 3.0 •  [email protected]: CartMan 1.04 •  Rich Media Technologies: JustAddCommerce 5.0 •  SmartCart: SmartCart •  Web Express: Shoptron 1.2

Source:hZp://xforce.iss.net/xforce/xfdb/4621

Solution: cryptographic checksums

Bindingtosession-id(SID)makesithardertoreplayoldcookies

Goal:dataintegrityRequiresserver-sidesecretkeykunknowntobrowser

BrowserServer k Set-Cookie:NAME= value T

Cookie:NAME= value T

Generate tag: T ← MACsign(k, SID ll name ll value )

Verify tag: MACverify(k, SID ll name ll value, T)

19

Example: ASP.NET

System.Web.ConfiguraQon.MachineKey–  SecretwebserverkeyintendedforcookieprotecQon

CreaQnganencryptedcookiewithintegrity:

HZpCookiecookie=newHZpCookie(name,val);HZpCookieencodedCookie= HNpSecureCookie.Encode(cookie);

DecrypQngandvalidaQnganencryptedcookie:

HNpSecureCookie.Decode(cookie);

SessionManagement

Sessions Asequenceofrequestsandresponsesfromonebrowsertoone(ormore)sites

–  Sessioncanbelong(e.g.Gmail)orshort–  withoutsessionmgmt:

userswouldhavetoconstantlyre-authenQcate

Sessionmgmt:authorizeuseronce;–  AllsubsequentrequestsareQedtouser

Pre-history: HTTP auth HTTP request: GET /index.html

HTTP response contains: WWW-Authenticate: Basic realm="Password Required“ Browsers sends hashed password on all subsequent HTTP requests: Authorization: Basic ZGFddfibzsdfgkjheczI1NXRleHQ=

HTTP auth problems Hardlyusedincommercialsites:

•  Usercannotlogoutotherthanbyclosingbrowser– WhatifuserhasmulQpleaccounts?mulQpleusersonsamemachine?

•  Sitecannotcustomizepassworddialog

•  Confusingdialogtousers

•  Easilyspoofed

Session tokens Browser

GET/index.html

setanonymoussessiontoken

GET/books.htmlanonymoussessiontoken

POST/do-loginUsername&password

elevatetoalogged-insessiontoken

POST/checkoutlogged-insessiontoken

checkcredenCals(crypto)

Validatetoken

website

Storing session tokens: Lots of options (but none are perfect)

Browsercookie: Set-Cookie:SessionToken=fduhye63sfdb

EmbedinallURLlinks: hZps://site.com/checkout?SessionToken=kh7y3b

Inahiddenformfield: <inputtype=“hidden” name=“sessionid” value=“kh7y3b”>

Storing session tokens: problems

Browsercookie:browsersendscookiewitheveryrequest,evenwhenitshouldnot(CSRF)

EmbedinallURLlinks:tokenleaksviaHTTPRefererheader

Inahiddenformfield:doesnotworkforlong-livedsessions

Bestanswer:acombinaQonofalloftheabove.

(orifuserpostsURLinapublicblog)

The HTTP referer header

RefererleaksURLsessiontokento3rdparQesReferersupression:•  notsentwhenHTTPSsitereferstoanHTTPsite•  inHTML5:<a rel=”noreferrer” href=www.example.com>

The Logout Process WebsitesmustprovidealogoutfuncQon:•  FuncQonality:letusertologinasdifferentuser•  Security:preventothersfromabusingaccount

Whathappensduringlogout:1.DeleteSessionTokenfromclient2.Marksessiontokenasexpiredonserver

Problem:manywebsitesdo(1)butnot(2)!!⇒EspeciallyriskyforsiteswhofallbacktoHTTPaberlogin

Sessionhijacking

SessionhijackingAZackerwaitsforusertologin

thenaZackerstealsuser’sSessionTokenand“hijacks” session

⇒aZackercanissuearbitraryrequestsonbehalfofuser

Example:FireSheep[2010]

FirefoxextensionthathijacksFacebooksessiontokensoverWiFi.SoluQon:HTTPSaberlogin

Beware: Predictable tokens

Example1:counter

⇒userlogsin,getscountervalue,

canviewsessionsofotherusers

Example2:weakMAC.token={userid,MACk(userid)}•  WeakMACexposeskfromfewcookies.

ApacheTomcat:generateSessionId()•  ReturnsrandomsessionID[serverretrievesclientstatebasedonsess-id]

SessiontokensmustbeunpredictabletoaZacker

Togenerate:useunderlyingframework(e.g.ASP,Tomcat,Rails)

Rails:token=MD5(currentQme,randomnonce)

Beware:SessiontokenthebExample1:loginoverHTTPS,butsubsequentHTTP•  EnablescookiethebatwirelessCafé(e.g.Firesheep)•  OtherwaysnetworkaZackercanstealtoken:

–  SitehasmixedHTTPS/HTTPpages⇒tokensentoverHTTP– Man-in-the-middleaZacksonSSL

Example2:CrossSiteScripQng(XSS)exploits

Amplifiedbypoorlogoutprocedures:–  Logoutmustinvalidatetokenonserver

Mitigating SessionToken theft by binding SessionToken to client’s computer

ClientIPaddr:makesithardertousetokenatanothermachine–  ButhonestclientmaychangeIPaddrduringsession

•  clientwillbeloggedoutfornoreason.

Clientuseragent:weakdefenseagainsttheb,butdoesn’thurt.

SSLsessionid:sameproblemasIPaddress(andevenworse)

Acommonidea:embedmachinespecificdatainSID

SessionfixaQonaZacksSupposeaZackercansettheuser’ssessiontoken:•  ForURLtokens,trickuserintoclickingonURL•  Forcookietokens,setusingXSSexploitsAZack:(say,usingURLtokens)

1.  AZackergetsanonymoussessiontokenforsite.com

2.  SendsURLtouserwithaZacker’ssessiontoken3.  UserclicksonURLandlogsintosite.com

–  thiselevatesaZacker’stokentologged-intoken

4.  AZackeruseselevatedtokentohijackuser’ssession.

SessionfixaQon:lesson When elevating user from anonymous to logged-in:

always issue a new session token

After login, token changes to value unknown to attacker

⇒ Attacker’s token is not elevated.

Summary

•  Alwaysassumecookiedataretrievedfromclientisadversarial

•  SessiontokensaresplitacrossmulQpleclientstatemechanisms:–  Cookies,hiddenformfields,URLparameters–  Cookiesbythemselvesareinsecure(CSRF,cookieoverwrite)–  SessiontokensmustbeunpredictableandresistthebbynetworkaZacker

•  Ensurelogoutinvalidatessessiononserver

THEEND