Post on 08-Jan-2017
@PhilippeDeRyck#Devoxx #AngularSecurity
ARE YOU BOTCHING THE SECURITY OFYOUR ANGULARJSAPPLICATION?
PhilippeDeRyck
@PhilippeDeRyck#Devoxx #AngularSecurity
IMAGINE AWORLD WITHOUT SECURITY PROBLEMS IN WEB APPLICATIONS …
Whatkindofworldwouldthatbe?
@PhilippeDeRyck#Devoxx #AngularSecurity
KNOWLEDGE IS THE KEY
Yetsecurityisoftenoverlooked
@PhilippeDeRyck#Devoxx #AngularSecurity
KNOWLEDGE IS KEY TO BUILDING SECURE APPLICATIONS
• Youdonotneedtobeasecurityexpert• ButyouneedtobeawareofthethreatsintheWeb
• Youwillwanttoapplyfundamentalsecurityprinciples
• Andfinally,youneedtoknowwhentocallasecurityexpert
• Byspreadingknowledge,Iwanttohelpyoubuildsecureapplications• Youwillbeabletoabsorblotsofknowledgeheretoday• Ifyouwantmore,contactmeaboutsecuritytraining
• Variousresourcesavailableonhttps://www.websec.be
• I’malsoachef,sothedemoswillmakeyou(evenmore)hungry!
@PhilippeDeRyck#Devoxx #AngularSecurity
CROSS-SITE SCRIPTING (XSS)
• AnXSSattackinjectsmaliciouscontentintoyourpages
• Inthe“original”XSSattacks,anattackerinjectedJavaScriptcode• Today,injectedcontentcanbeJavaScript,CSS,HTML,SVG,…
@PhilippeDeRyck#Devoxx #AngularSecurity
CROSS-SITE SCRIPTING (XSS)
• AnXSSattackinjectsmaliciouscontentintoyourpages
• Inthe“original”XSSattacks,anattackerinjectedJavaScriptcode• Today,injectedcontentcanbeJavaScript,CSS,HTML,SVG,…
• Therealproblemisthatinjectedcontentrunsinyourcontext• Completeaccesstoyourclient-sidedataandcode
• Abilitytouseanypermissionstheuserhasgrantedtoyourapplication
• ThefullpowerofXHRtocontactyourbackend,inthenameoftheuser
• XSSattacksareverypowerful,andunfortunatelyverycommon
• XSSisranked3rd intheOWASPtop10and4th
intheSANStop25
@PhilippeDeRyck#Devoxx #AngularSecurity
http://colesec.inventedtheinternet.com/beef-the-browser-exploitation-framework-project/
@PhilippeDeRyck#Devoxx #AngularSecurity
XSSVULNERABILITIES ARE NOT ONLY FOR CHUMPS
https://www.youtube.com/watch?v=K0noqLisW_chttp://motherboard.vice.com/read/tor-project-patches-cross-site-scripting-xss-bug-in-its-website
@PhilippeDeRyck#Devoxx #AngularSecurity
HOW DO YOU PROTECT AGAINST XSS?
• TherootcauseofXSSisconfusionbetweendataandcode• Browsergetsuntrusteddatamixedwithtrustedcode
• Thereisnowaytoknowwhichpartisdataandwhichiscode
<div><h3>Your search for “<i>Crazy Cats<script>alert(“Miauw!”)</script></i>”returned 5 results
</h3></div>
<div><h3>Your search for “$query” returned $count results
</h3></div>
@PhilippeDeRyck#Devoxx #AngularSecurity
HOW DO YOU PROTECT AGAINST XSS?
• TherootcauseofXSSisconfusionbetweendataandcode• Browsergetsuntrusteddatamixedwithtrustedcode
• Thereisnowaytoknowwhichpartisdataandwhichiscode
• Theserverneedstorenderthedataharmless
• Byescaping“dangerous”partsinthedata<div><h3>
Your search for “<i>Crazy Cats<script>alert(“Miauw!”)</script></i>
returned 5 results</h3></div>
@PhilippeDeRyck#Devoxx #AngularSecurity
ESCAPING OUTPUT TO PROTECT AGAINST XSS
• Escapingdangerouspartspreventsdatatobecomecode
• Serverdoesthisbeforesendingpagetothebrowser
• Theescapingprocessiscontext-sensitive• HTMLbody <h1>DATA</h1>
• HTMLattributes <div id=‘DATA’>
• Stylesheetcontext body { background-color: DATA;}
• Scriptcontext alert(“DATA”);• …
@PhilippeDeRyck#Devoxx #AngularSecurity
@PhilippeDeRyck#Devoxx #AngularSecurity
AND WHAT ABOUT XSSIN ANGULAR?
• Remembertheconfusionbetweendataandcode?
• TemplatesandJavaScriptcodeareconsideredtheapplication’scode• DatafetchedfromAPIsisconsidereddata
• AngularJSknowswhichpartsareuntrusted• AndautomaticallyappliesStrictContextualEscaping(SCE)• SCEappliestoalldatabindingswithng-bind or{{ }}• SCEison-by-defaultsinceversion1.2
• ButwhatifweactuallywanttoallowHTMLintheuser’sdata?
@PhilippeDeRyck#Devoxx #AngularSecurity
@PhilippeDeRyck#Devoxx #AngularSecurity
http://stackoverflow.com/questions/9381926/angularjs-insert-html-into-view/25513186#25513186
@PhilippeDeRyck#Devoxx #AngularSecurity
ALL IS GREAT …UNTIL YOU GET A CALL ONE EVENING
What,noway!Whathappened?Didtheystealourdata?
No,it’sworse!Muchworse!
TheyloadedEmberJS!
We’vebeenhacked!
Thenwhat?!
OH MY GOOOWD
@PhilippeDeRyck#Devoxx #AngularSecurity
LET’S INVESTIGATE THE STACKOVERFLOW ADVICE …
https://docs.angularjs.org/api/ng/service/$scehttps://docs.angularjs.org/error/$sce/unsafe
@PhilippeDeRyck#Devoxx #AngularSecurity
LETTING ANGULARJS1.X DO THE WORK FOR YOU
• SimpledatawillbeencodedfortherightcontextwithSCE
• AngularJSwillnotallowyoutodirectlyuseuntrusteddata
• Sanitizinguntrusteddatamakesitsafetouse
• StaticHTMLsnippetscanbemarkedassafeifabsolutelynecessary
<p>{{var}}</p>var = “test<script>alert(1)</script>”
<p ng-bind-html=“var”></p><input ng-model=“var” />
<input ng-model=“var” /> angular.module(“…”, [‘ngSanitize’]<p ng-bind-html=“var”></p>
<p ng-bind-html=“var”></p>var = $sce.trustAsHtml(“<b>test</b>)”
@PhilippeDeRyck#Devoxx #AngularSecurity
AND IT’S EVEN BETTER IN ANGULARJS2.X
• Alldataissanitizedbydefault
• StaticHTMLcanbemarkedsafeifabsolutelynecessary
<input ng-model=“var” /> <p>{{var}}</p>
<p>{{var}}</p>var = domSanitizer.bypassSecurityTrustHtml(“<b>test</b>)”)
@PhilippeDeRyck#Devoxx #AngularSecurity
http://stackoverflow.com/a/25513186
@PhilippeDeRyck#Devoxx #AngularSecurity
RULE#1
DO NOT MARK UNTRUSTED DATA AS SAFE
Usethebuilt-insanitizertoremovedangerousfeaturesfromtheuntrusteddata
@PhilippeDeRyck#Devoxx #AngularSecurity
MIXING ANGULARJS WITH TRADITIONAL APPLICATIONS
• AngularJSisoftenusedwithintraditionalapplications• TheserverbuildsanHTMLpage,usinguntrusteddata
• AngularJSisusedtosimplifyUIdevelopment
<script src=“…/angular.js”></script>…<div><h3>
Your search for “<i>encode($query)</i>” returned {{nbOfResults}} results
</h3></div>
@PhilippeDeRyck#Devoxx #AngularSecurity
MIXING ANGULARJSWITH TRADITIONAL APPLICATIONS
• TheserverwillneedtoprotectagainstXSSattacks• ButisthatevenpossibleinanAngularJSenvironment?
<div class=”ng-app”>{{constructor.constructor(‘alert(1)’)}}
</div>
<div class="ng-app"><b class="ng-style: {x:constructor.constructor('alert(1)')()};" />
</div>
Herekittykittykitty…
x: y
@PhilippeDeRyck#Devoxx #AngularSecurity
MIXING ANGULARJSWITH TRADITIONAL APPLICATIONS
• TheserverwillneedtoprotectagainstXSSattacks• ButisthatevenpossibleinanAngularJSenvironment?
• AngularJStrieditwiththeexpressionsandbox• PreventsdirectaccesstoglobalJavaScriptfunctionality• Impossibletogetright,soonlyavailableinAngularJS1.2- 1.5.8
• Angular2offersofflinetemplatecompilation
@PhilippeDeRyck#Devoxx #AngularSecurity
RULE#2
DO NOT COMBINE TEMPLATES WITH USER-SUPPLIED DATA ON THE SERVER
Providethedataseparatelytotheclient-sideAngularJSapplication
@PhilippeDeRyck#Devoxx #AngularSecurity
BUT WHAT IF AN XSSATTACK HAPPENS ANYWAY?
@PhilippeDeRyck#Devoxx #AngularSecurity
SO WHAT IF XSSHAPPENS ANYWAY?
• ShieldyourselfbydeployingContentSecurityPolicy• CSPactsasasecondlevelofdefenseagainstXSSattacks• XSSattackswillbeseverelyconstrainedorevenblocked
• CSPlocksdownwhatcanhappeninawebpage• Refusestoexecuteinlinescriptandstyle• Onlyloadsexternalresourcesifexplicitlyallowed
• CSPseemsscary,butisactuallyawesome
@PhilippeDeRyck#Devoxx #AngularSecurity
THE NUTS AND BOLTS OF CSP
• CSPisaserver-drivenbrowser-enforcedpolicy• ServerprovidesaCSPpolicyinaheaderormeta tag
• BrowserenforcestheCSPpolicyonthepageContent-Security-Policy:
default-src 'self';
script-src 'self' https://code.jquery.com/jquery-3.1.1.min.js https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js;
img-src data:;
style-src 'self' https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css;
font-src 'self' https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/fonts/
@PhilippeDeRyck#Devoxx #AngularSecurity
AQUICK OVERVIEW OF CSP’S DIRECTIVES
• CSPhasdirectivesforallkindsofresources• default-src appliestoanyresource,ifthere’snomorespecific directive• img-src,script-src,style-src,…
• Adirectivecanhavenumerousvalidvalues
• Keywords:‘none’,‘self’,*• Expressions:https://websec.be,https:,https://websec.be/jquery.js,*.websec.be
• CSPhassomeincompatibilitieswithtraditionalwebapps
• ButiseasytodeployonanAngularJSapplication
@PhilippeDeRyck#Devoxx #AngularSecurity
BROWSER SUPPORT FOR CSPLEVEL 1IS AWESOME
http://caniuse.com/#search=csp
@PhilippeDeRyck#Devoxx #AngularSecurity
FOLLOWING UP ON CSPVIOLATIONS
• CSPincludesareportingfeature• Thebrowserautomaticallysendsareportwhenaviolationoccurs
{ "csp-report": { "document-uri": "https://www.websec.be/blog/cspfromscratch/", "violated-directive": "script-src 'self' https://…", "effective-directive": "script-src", "original-policy": "default-src 'self’…", "blocked-uri": "eval", "line-number": 1, column-number": 1609, "source-file": "https://a.disquscdn.com", "status-code": 0 } }
@PhilippeDeRyck#Devoxx #AngularSecurity
FOLLOWING UP ON CSPVIOLATIONS
• CSPincludesareportingfeature• Thebrowserautomaticallysendsareportwhenaviolationoccurs
• CSPcanbeenabledinreport-onlymode
• Policyviolationswillnotbeblocked,butareportissent• Perfectfordry-runningyourpolicybeforedeploying
• Collectingreportsisstraightforward,butalsoabittricky• report-uri.io willgetyoustarted
https://report-uri.io/
@PhilippeDeRyck#Devoxx #AngularSecurity
WRITING SANE CSPPOLICIES
• DeployCSPusingtheContent-Security-Policy responseheader• meta tagsareagoodalternativeifheadersaretoodifficulttouse
•Makeyourpolicyassecureaspossible
• Avoid‘unsafe-inline’and‘unsafe-eval’,especiallyforscripts• Specifyresourcesuptothefileleveltoavoidbypassattacks• Defineallimportantdirectivestoavoidoverrideattackswithmeta tags
• UseGoogle’sCSPEvaluatortocheckyourpolicyhttps://csp-evaluator.withgoogle.com/
@PhilippeDeRyck#Devoxx #AngularSecurity
WRITING SANE CSPPOLICIES
https://csp-evaluator.withgoogle.com/
@PhilippeDeRyck#Devoxx #AngularSecurity
RULE#3
LEVERAGE THE TREMENDOUS POWER OF CSP
Makesureyourappsarecompatible,andlockdownyourCSPpolicy
@PhilippeDeRyck#Devoxx #AngularSecurity
Security
@PhilippeDeRyck#Devoxx #AngularSecurity
SO FAR,WE ONLY TALKED ABOUT XSS
• Butthere’salotmoretobuildingasecureapplication
• Thewebhasevolvedalotinthelastfewyears• Plentyofnewthreats,butalsoplentyofnewsecuritytechnologies
• FundamentalsforbuildingsecureAngularJSapplications
• DeployyourapplicationsoverHTTPS• Usestrongauthenticationmechanisms
• Performaccesscontrolintherightplaces,withtherightdata
• Protectagainstcommonthreatsagainstsessionmanagement
@PhilippeDeRyck#Devoxx #AngularSecurity
SECURE SESSION MANAGEMENT IS CRITICAL
websec.be
anysite.io
Visitwebpage
Welcomepage
LoginasPhilippeWelcomePhilippe
Visitwebpage
Welcomepage
LoginasPhilippeWelcomePhilippe
SID=1234
1234:
auth:false
1234:
auth:true
user:Philippe
Session={
auth:false
}
Session={
auth:true
user:Philippe
}
@PhilippeDeRyck#Devoxx #AngularSecurity
THE UNDERESTIMATED THREAT OF CSRF
websec.be
anysite.io
loginasPhilippeWelcomepage
Showmessages
Latestmessages
Showobligatorycatpics
Kittensfromhell
@PhilippeDeRyck#Devoxx #AngularSecurity
CSRFIN THE REAL WORLD
Ebay.com
Resetpassword
OK,wewillgiveyouacall
Changetelephonenumber
Surething,Philippe
http://news.softpedia.com/news/CSRF-Vulnerability-in-eBay-Allows-Hackers-to-Hijack-User-Accounts-Video-383316.shtml
Resetpasswordwithsecretcode
Alldone
@PhilippeDeRyck#Devoxx #AngularSecurity
TRADITIONAL CSRFDEFENSES ARE CRUMBLINGwebsec.be
anysite.io
loginasPhilippeWelcomepage
Postmessage
Surething,Philippe
Showobligatorycatpics
Kittensfromhell
<form … ><input type=“hidden” name=“csrftoken” value”1234abc” />...
</form>
@PhilippeDeRyck#Devoxx #AngularSecurity
TRANSPARENT CSRFTOKENS WORK WITHOUT FORMSwebsec.be
anysite.io
loginasPhilippeWelcome,Philippe
Postmessage
Surething,Philippe
Showobligatorycatpics
Kittensfromhell
POST …Cookie: SID=123, XSRF-TOKEN=abcX-XSRF-TOKEN: abc
@PhilippeDeRyck#Devoxx #AngularSecurity
ANGULARJSSUPPORTS TRANSPARENT TOKENS BY DEFAULT
@PhilippeDeRyck#Devoxx #AngularSecurity
WHY DON’T WE JUST FIX COOKIES?websec.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
@PhilippeDeRyck#Devoxx #AngularSecurity
AND WHAT IF IATTACH A TOKEN IN A HEADER?websec.be
anysite.io
loginasPhilippeHi,here’satoken
Postmessage
Surething,Philippe
Showobligatorycatpics
Kittensfromhell
Authorization: Bearer eyJhbGciO…
@PhilippeDeRyck#Devoxx #AngularSecurity
RULE#4
USE CSRFDEFENSES TO PREVENT UNINTENTIONAL REQUESTS
AngularJShasyourback,ifyouenableCSRFtokensonthebackend
@PhilippeDeRyck#Devoxx #AngularSecurity
KNOWLEDGE IS THE KEY TO SECURITY
#3 LEVERAGE THE TREMENDOUS POWER OF CSP
#2 DO NOT COMBINE TEMPLATES WITH USER-SUPPLIED DATA
#1 NEVER EVER MARK UNTRUSTED DATA AS SAFE
#0 TELL ALL YOUR FRIENDS ABOUT THESE RULES!
#4 USE CSRFDEFENSES TO PREVENT UNINTENTIONAL REQUESTS
@PhilippeDeRyck#Devoxx #AngularSecurity
MORE KNOWLEDGE,BETTER SECURITY
/in/philippederyck @PhilippeDeRyck philippe.deryck@cs.kuleuven.be
https://www.websec.be
Wanttostayinformed?Subscribetoourmailinglist!