SlideShare a Scribd company logo
1 of 23
Download to read offline
Frontend Security: Applying Contextual Escaping Automatically, or
How to Stop XSS in Seconds
PRESENTED BY Nera Liu and Adonis Fung⎪ May 21, 2015
Problem Statement
What makes XSS prevention so hard?
Background > Related Work > Our Approach > Evaluations > Conclusion
XSS Quick Explanation
Given no proper output filtering:
<h1>Hello <?php echo $_GET['name']; ?></h1>
An attack vector can come through the query string
at victim.com/?name=XXX, where XXX is:
"'><script>alert(1)</script>
HTML of victim.com ends up being:
<h1>Hello "'><script>alert(1)</script></h1>
Cross-Site Scripting (XSS)
Root Cause
- Untrusted inputs executed as scripts under a victim’s origin/domain
Consequences
- Cookie stealing, privacy leaking
- Fully control the web content
- Bug bounty costs
Cross-Site Scripting (XSS)
■ Ranked No. 3 / OWASP Top 10 WebApp Security Risks
Screen-captured from https://www.owasp.org/index.php/Top_10_2013-A3-Cross-Site_Scripting_(XSS)
XSS Defenses
Defense-in-depth:
- Prevent, Detect, Contain, etc...
Generally, apply output filtering to prevent XSS
- Blindly-escape sensitive chars (e.g., & < > " ' `)
- PHP: htmlentities(untrusted_data)
- JavaScript: untrustedData.replace(/[&<>"'`]/, ...)
- Templating: {{untrustedData}} is blindly-escaped by default
Blindly-escaping is still vulnerable!
Blindly-escaping (&<>"'`) would not stop XSS, when
- {{url}} is an untrusted user input (assumed thereafter)
- {{url}} is javascript:alert(1), or
- {{url}} is # onclick=alert(1)
→ We need Contextual Escaping!
- While blindlyEscape( data ) works, but not for url
- blacklistProtocol( escapeUnquoted ( encodeURI( url ) ) )
A template is typically written like so:
<a href={{url}}>{{data}}</a>
XSS Output Filtering
Contextual-escaping
Filters (Secure)
Blindly-escaping
Filters (Vulnerable)
Manual
(error-prone and
doesn’t scale)
Automatic
(defaulted by
template engines) ✔
✘
✘
✔
Related Work
Limited solutions/attempts available
- Use Closure/AngularJS w/Strict Contextual Escaping
- Use XML Templates with Java/JSP
- Without Contextual Escaping: React, Dust, etc...
Deployability/Adoption Issues
- Framework specific
- Browser compatibility issues
- Not for existing projects, unless requiring many code changes
Highlights
- Efficient HTML 5 compliant parser w/auto corrections
- Auto apply contextual, just-sufficient, and faster escaping
- Effortless adoption requiring as little as 2 LoC changes
https://yahoo.github.io/secure-handlebars
Our Approach: Secure Handlebars
Automatic contextual escaping made easy
Handlebars
Context Parser
Handlebars PreProcessor
High-level Architecture
Template
Parser
Template
AST
HTML5 Parser
(w/auto corrections)
JS Parser
AST
Walker
Template
w/filter markups
abstracting branching logics and output expressions
CSS Parser
Pre-
compiler
Contextual XSS Filters
(registered as helpers/callbacks)
HTML
Data
(possibly untrusted)
Runtime
Compiler
Template
Spec.
Our solution comprises of only the blue boxes
Handlebars
Context Parser
Handlebars PreProcessor
High-level Architecture
Template
Parser
Template
AST
HTML5 Parser
(w/auto corrections)
JS Parser
AST
Walker
Template
w/filter markups
abstracting branching logics and output expressions
CSS Parser
Pre-
compiler
Contextual XSS Filters
(registered as helpers/callbacks)
HTML
Data
(possibly untrusted)
Runtime
Compiler
Template
Spec.
Our solution comprises of only the blue boxes
Pre-Processor: Good Template Samples
[Before]
<a href="{{url}}">{{url}}</a>
[After]
<a href="{{{yubl (yavd (yufull url))}}}">{{{yd url}}}</a>
Add contextual escaping filters
{{{ }}} - disable the default blindly-escaping
yufull - encodeURI()with IPv6 support
yavd - html-escape double-quote character (" → &quot;)
yubl - disable dangerous protocols such as javascript:
yd - html-escape less-than character (< → &lt;)
Pre-Processor: Bad Template Samples
[Before]
<input type="button" onclick="doSth({{data}})">
Warning!
Ensure placeholders are never put in scriptable contexts
- Security anti-pattern to place (possibly) untrusted data in executable contexts
- Workaround:
- <input type="button" data-sth="{{data}}"
onclick="doSth(this.getAttribute('data-sth'))">
Pre-Processor: Branching Consistency Check
[Before]
{{#if highlight}}<strong>{{else}}<em {{/if}} {{unknownCxt}} ...
[After] A warning is raised!
{{#if highlight}}<strong>{{else}}<em {{/if}} {{data}} ...
Walk through branches & ensure they end up in identical state/context
- Likely a careless mistake or typo
- Obviously, context of {{unknownCxt}} is ambiguous
Warning!
Handlebars
Context Parser
Handlebars PreProcessor
High-level Architecture
Template
Parser
Template
AST
HTML5 Parser
(w/auto corrections)
JS Parser
AST
Walker
Template
w/filter markups
abstracting branching logics and output expressions
CSS Parser
Pre-
compiler
Contextual XSS Filters
(registered as helpers/callbacks)
HTML
Data
(possibly untrusted)
Runtime
Compiler
Template
Spec.
Our solution comprises of only the blue boxes
Standard Compliant
- Can even auto-correct parse errors to enforce
consistent parsing across browsers
Robust, lightweight, and efficient
- Simplified state transitions
- No unnecessary handling (no DOM)
Design Principles of Context Parser
Figured from Overview of HTML 5 Parsing Model: https://html.spec.whatwg.org/multipage/syntax.html#overview-of-the-parsing-model
Handlebars
Context Parser
Handlebars PreProcessor
High-level Architecture
Template
Parser
Template
AST
HTML5 Parser
(w/auto corrections)
JS Parser
AST
Walker
Template
w/filter markups
abstracting branching logics and output expressions
CSS Parser
Pre-
compiler
Contextual XSS Filters
(registered as helpers/callbacks)
HTML
Data
(possibly untrusted)
Runtime
Compiler
Template
Spec.
Our solution comprises of all blue boxes
Design Principles of XSS Filters
Context-aware
- More Secure - escape only
those that can break out
from its context
Just sufficient encoding
- Faster - no need to
escape all & > " ' `
- More friendly - no more
double-encoding issues like
&amp;lt;
Deployability
Adoption
- Switch from express-handlebars to express-secure-handlebars npm
- 2 LOCs changes: (1) dependency in package.json, (2) require(...)
- Alternatively, a more decoupled approach:
- pre-process tmpl to get it rewrited during build process at server
- only register helpers for data filtering and binding at client-side
Browser Compatibility
- IE 7+, Safari 5+, Chrome, Firefox
Evaluations
Deployed in one the largest properties
- Negligible offline overhead
- takes <3s to analyze/pre-process 880 templates
- Insignifiant runtime overhead (i.e., filter callbacks, size: 1.3KB gz)
- unchained filters: up to 2 times faster than default
- chained filters: slower but is already minimal to be secure
- True positives found!
- e.g., unquoted, onclick, URI attributes, script tags, etc.
- More secure, efficient, and easier adoption
- Open-sourced at github.com/yahoo and npmjs.com
- Contact/Collaborate with us for more template support
Conclusion: Building A Safer Internet for All
Automatic contextual escaping made easy
Thank you!
Nera, Albert, Adon
{neraliu, albertyu, adon}@yahoo-inc.
com
Twitter: @neraliu, @yukinying, @adonatwork

More Related Content

What's hot

Top 10 Security Vulnerabilities (2006)
Top 10 Security Vulnerabilities (2006)Top 10 Security Vulnerabilities (2006)
Top 10 Security Vulnerabilities (2006)Susam Pal
 
Vulnerable Active Record: A tale of SQL Injection in PHP Framework
Vulnerable Active Record: A tale of SQL Injection in PHP FrameworkVulnerable Active Record: A tale of SQL Injection in PHP Framework
Vulnerable Active Record: A tale of SQL Injection in PHP FrameworkPichaya Morimoto
 
Attacks against Microsoft network web clients
Attacks against Microsoft network web clients Attacks against Microsoft network web clients
Attacks against Microsoft network web clients Positive Hack Days
 
XSS Primer - Noob to Pro in 1 hour
XSS Primer - Noob to Pro in 1 hourXSS Primer - Noob to Pro in 1 hour
XSS Primer - Noob to Pro in 1 hoursnoopythesecuritydog
 
Security In PHP Applications
Security In PHP ApplicationsSecurity In PHP Applications
Security In PHP ApplicationsAditya Mooley
 
Static Analysis: The Art of Fighting without Fighting
Static Analysis: The Art of Fighting without FightingStatic Analysis: The Art of Fighting without Fighting
Static Analysis: The Art of Fighting without FightingRob Ragan
 
Intro to Php Security
Intro to Php SecurityIntro to Php Security
Intro to Php SecurityDave Ross
 
Filter Evasion: Houdini on the Wire
Filter Evasion: Houdini on the WireFilter Evasion: Houdini on the Wire
Filter Evasion: Houdini on the WireRob Ragan
 
DEFCON 23 - Jason Haddix - how do i shot web
DEFCON 23 - Jason Haddix - how do i shot webDEFCON 23 - Jason Haddix - how do i shot web
DEFCON 23 - Jason Haddix - how do i shot webFelipe Prado
 
Comparing DOM XSS Tools On Real World Bug
Comparing DOM XSS Tools On Real World BugComparing DOM XSS Tools On Real World Bug
Comparing DOM XSS Tools On Real World BugStefano Di Paola
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraMathias Karlsson
 
SQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developersSQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developersKrzysztof Kotowicz
 
Breaking AngularJS Javascript sandbox
Breaking AngularJS Javascript sandboxBreaking AngularJS Javascript sandbox
Breaking AngularJS Javascript sandboxMathias Karlsson
 
JSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedJSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedKazuho Oku
 
Why haven't we stamped out SQL injection and XSS yet
Why haven't we stamped out SQL injection and XSS yetWhy haven't we stamped out SQL injection and XSS yet
Why haven't we stamped out SQL injection and XSS yetRomain Gaucher
 
주로사용되는 Xss필터와 이를 공격하는 방법
주로사용되는 Xss필터와 이를 공격하는 방법주로사용되는 Xss필터와 이를 공격하는 방법
주로사용되는 Xss필터와 이를 공격하는 방법guestad13b55
 
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSSWeb Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSSIvan Ortega
 
Eight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programsEight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programsAleksandr Yampolskiy
 

What's hot (20)

Top 10 Security Vulnerabilities (2006)
Top 10 Security Vulnerabilities (2006)Top 10 Security Vulnerabilities (2006)
Top 10 Security Vulnerabilities (2006)
 
Vulnerable Active Record: A tale of SQL Injection in PHP Framework
Vulnerable Active Record: A tale of SQL Injection in PHP FrameworkVulnerable Active Record: A tale of SQL Injection in PHP Framework
Vulnerable Active Record: A tale of SQL Injection in PHP Framework
 
Defending against Injections
Defending against InjectionsDefending against Injections
Defending against Injections
 
Attacks against Microsoft network web clients
Attacks against Microsoft network web clients Attacks against Microsoft network web clients
Attacks against Microsoft network web clients
 
XSS Primer - Noob to Pro in 1 hour
XSS Primer - Noob to Pro in 1 hourXSS Primer - Noob to Pro in 1 hour
XSS Primer - Noob to Pro in 1 hour
 
Security In PHP Applications
Security In PHP ApplicationsSecurity In PHP Applications
Security In PHP Applications
 
Static Analysis: The Art of Fighting without Fighting
Static Analysis: The Art of Fighting without FightingStatic Analysis: The Art of Fighting without Fighting
Static Analysis: The Art of Fighting without Fighting
 
Intro to Php Security
Intro to Php SecurityIntro to Php Security
Intro to Php Security
 
Filter Evasion: Houdini on the Wire
Filter Evasion: Houdini on the WireFilter Evasion: Houdini on the Wire
Filter Evasion: Houdini on the Wire
 
DEFCON 23 - Jason Haddix - how do i shot web
DEFCON 23 - Jason Haddix - how do i shot webDEFCON 23 - Jason Haddix - how do i shot web
DEFCON 23 - Jason Haddix - how do i shot web
 
Comparing DOM XSS Tools On Real World Bug
Comparing DOM XSS Tools On Real World BugComparing DOM XSS Tools On Real World Bug
Comparing DOM XSS Tools On Real World Bug
 
Polyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPraPolyglot payloads in practice by avlidienbrunn at HackPra
Polyglot payloads in practice by avlidienbrunn at HackPra
 
SQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developersSQL Injection: complete walkthrough (not only) for PHP developers
SQL Injection: complete walkthrough (not only) for PHP developers
 
Breaking AngularJS Javascript sandbox
Breaking AngularJS Javascript sandboxBreaking AngularJS Javascript sandbox
Breaking AngularJS Javascript sandbox
 
JSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedJSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons Learned
 
Why haven't we stamped out SQL injection and XSS yet
Why haven't we stamped out SQL injection and XSS yetWhy haven't we stamped out SQL injection and XSS yet
Why haven't we stamped out SQL injection and XSS yet
 
주로사용되는 Xss필터와 이를 공격하는 방법
주로사용되는 Xss필터와 이를 공격하는 방법주로사용되는 Xss필터와 이를 공격하는 방법
주로사용되는 Xss필터와 이를 공격하는 방법
 
Introduction to shodan
Introduction to shodanIntroduction to shodan
Introduction to shodan
 
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSSWeb Security - OWASP - SQL injection & Cross Site Scripting XSS
Web Security - OWASP - SQL injection & Cross Site Scripting XSS
 
Eight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programsEight simple rules to writing secure PHP programs
Eight simple rules to writing secure PHP programs
 

Similar to Frontend Security: Applying Contextual Escaping Automatically, or How to Stop XSS in Seconds

EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdfEN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdfGiorgiRcheulishvili
 
Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2Jim Manico
 
04. xss and encoding
04.  xss and encoding04.  xss and encoding
04. xss and encodingEoin Keary
 
What's Our Software Doing With All That User Input
What's Our Software Doing With All That User InputWhat's Our Software Doing With All That User Input
What's Our Software Doing With All That User InputKim Carter
 
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014(WEB301) Operational Web Log Analysis | AWS re:Invent 2014
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014Amazon Web Services
 
Sandboxing JS and HTML. A lession Learned
Sandboxing JS and HTML. A lession LearnedSandboxing JS and HTML. A lession Learned
Sandboxing JS and HTML. A lession LearnedMinded Security
 
Prevoty NYC Java SIG 20150730
Prevoty NYC Java SIG 20150730Prevoty NYC Java SIG 20150730
Prevoty NYC Java SIG 20150730chadtindel
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesBrad Hill
 
Thug: a new low-interaction honeyclient
Thug: a new low-interaction honeyclientThug: a new low-interaction honeyclient
Thug: a new low-interaction honeyclientAngelo Dell'Aera
 
How do JavaScript frameworks impact the security of applications?
How do JavaScript frameworks impact the security of applications?How do JavaScript frameworks impact the security of applications?
How do JavaScript frameworks impact the security of applications?Ksenia Peguero
 
Building Web Sites that Work Everywhere
Building Web Sites that Work EverywhereBuilding Web Sites that Work Everywhere
Building Web Sites that Work EverywhereDoris Chen
 
Manindra kishore _incident_handling_n_log_analysis - ClubHack2009
Manindra kishore _incident_handling_n_log_analysis - ClubHack2009Manindra kishore _incident_handling_n_log_analysis - ClubHack2009
Manindra kishore _incident_handling_n_log_analysis - ClubHack2009ClubHack
 
Internet Explorer 8
Internet Explorer 8Internet Explorer 8
Internet Explorer 8David Chou
 
[Wroclaw #2] Web Application Security Headers
[Wroclaw #2] Web Application Security Headers[Wroclaw #2] Web Application Security Headers
[Wroclaw #2] Web Application Security HeadersOWASP
 
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...Amazon Web Services
 

Similar to Frontend Security: Applying Contextual Escaping Automatically, or How to Stop XSS in Seconds (20)

EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdfEN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
EN - BlackHat US 2009 favorite XSS Filters-IDS and how to attack them.pdf
 
Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2Top Ten Java Defense for Web Applications v2
Top Ten Java Defense for Web Applications v2
 
04. xss and encoding
04.  xss and encoding04.  xss and encoding
04. xss and encoding
 
What's Our Software Doing With All That User Input
What's Our Software Doing With All That User InputWhat's Our Software Doing With All That User Input
What's Our Software Doing With All That User Input
 
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014(WEB301) Operational Web Log Analysis | AWS re:Invent 2014
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014
 
Sandboxing JS and HTML. A lession Learned
Sandboxing JS and HTML. A lession LearnedSandboxing JS and HTML. A lession Learned
Sandboxing JS and HTML. A lession Learned
 
Prevoty NYC Java SIG 20150730
Prevoty NYC Java SIG 20150730Prevoty NYC Java SIG 20150730
Prevoty NYC Java SIG 20150730
 
W3 conf hill-html5-security-realities
W3 conf hill-html5-security-realitiesW3 conf hill-html5-security-realities
W3 conf hill-html5-security-realities
 
Thug: a new low-interaction honeyclient
Thug: a new low-interaction honeyclientThug: a new low-interaction honeyclient
Thug: a new low-interaction honeyclient
 
How do JavaScript frameworks impact the security of applications?
How do JavaScript frameworks impact the security of applications?How do JavaScript frameworks impact the security of applications?
How do JavaScript frameworks impact the security of applications?
 
Building Web Sites that Work Everywhere
Building Web Sites that Work EverywhereBuilding Web Sites that Work Everywhere
Building Web Sites that Work Everywhere
 
Axis2 Landscape
Axis2 LandscapeAxis2 Landscape
Axis2 Landscape
 
Manindra kishore _incident_handling_n_log_analysis - ClubHack2009
Manindra kishore _incident_handling_n_log_analysis - ClubHack2009Manindra kishore _incident_handling_n_log_analysis - ClubHack2009
Manindra kishore _incident_handling_n_log_analysis - ClubHack2009
 
Internet Explorer 8
Internet Explorer 8Internet Explorer 8
Internet Explorer 8
 
Sergey Stoyan 2016
Sergey Stoyan 2016Sergey Stoyan 2016
Sergey Stoyan 2016
 
Sergey Stoyan 2016
Sergey Stoyan 2016Sergey Stoyan 2016
Sergey Stoyan 2016
 
[Wroclaw #2] Web Application Security Headers
[Wroclaw #2] Web Application Security Headers[Wroclaw #2] Web Application Security Headers
[Wroclaw #2] Web Application Security Headers
 
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
 
Isset Presentation @ EECI2009
Isset Presentation @ EECI2009Isset Presentation @ EECI2009
Isset Presentation @ EECI2009
 
gofortution
gofortutiongofortution
gofortution
 

Recently uploaded

Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 

Recently uploaded (20)

Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 

Frontend Security: Applying Contextual Escaping Automatically, or How to Stop XSS in Seconds

  • 1. Frontend Security: Applying Contextual Escaping Automatically, or How to Stop XSS in Seconds PRESENTED BY Nera Liu and Adonis Fung⎪ May 21, 2015
  • 2. Problem Statement What makes XSS prevention so hard? Background > Related Work > Our Approach > Evaluations > Conclusion
  • 3. XSS Quick Explanation Given no proper output filtering: <h1>Hello <?php echo $_GET['name']; ?></h1> An attack vector can come through the query string at victim.com/?name=XXX, where XXX is: "'><script>alert(1)</script> HTML of victim.com ends up being: <h1>Hello "'><script>alert(1)</script></h1>
  • 4. Cross-Site Scripting (XSS) Root Cause - Untrusted inputs executed as scripts under a victim’s origin/domain Consequences - Cookie stealing, privacy leaking - Fully control the web content - Bug bounty costs
  • 5. Cross-Site Scripting (XSS) ■ Ranked No. 3 / OWASP Top 10 WebApp Security Risks Screen-captured from https://www.owasp.org/index.php/Top_10_2013-A3-Cross-Site_Scripting_(XSS)
  • 6. XSS Defenses Defense-in-depth: - Prevent, Detect, Contain, etc... Generally, apply output filtering to prevent XSS - Blindly-escape sensitive chars (e.g., & < > " ' `) - PHP: htmlentities(untrusted_data) - JavaScript: untrustedData.replace(/[&<>"'`]/, ...) - Templating: {{untrustedData}} is blindly-escaped by default
  • 7. Blindly-escaping is still vulnerable! Blindly-escaping (&<>"'`) would not stop XSS, when - {{url}} is an untrusted user input (assumed thereafter) - {{url}} is javascript:alert(1), or - {{url}} is # onclick=alert(1) → We need Contextual Escaping! - While blindlyEscape( data ) works, but not for url - blacklistProtocol( escapeUnquoted ( encodeURI( url ) ) ) A template is typically written like so: <a href={{url}}>{{data}}</a>
  • 8. XSS Output Filtering Contextual-escaping Filters (Secure) Blindly-escaping Filters (Vulnerable) Manual (error-prone and doesn’t scale) Automatic (defaulted by template engines) ✔ ✘ ✘ ✔
  • 9. Related Work Limited solutions/attempts available - Use Closure/AngularJS w/Strict Contextual Escaping - Use XML Templates with Java/JSP - Without Contextual Escaping: React, Dust, etc... Deployability/Adoption Issues - Framework specific - Browser compatibility issues - Not for existing projects, unless requiring many code changes
  • 10. Highlights - Efficient HTML 5 compliant parser w/auto corrections - Auto apply contextual, just-sufficient, and faster escaping - Effortless adoption requiring as little as 2 LoC changes https://yahoo.github.io/secure-handlebars Our Approach: Secure Handlebars Automatic contextual escaping made easy
  • 11. Handlebars Context Parser Handlebars PreProcessor High-level Architecture Template Parser Template AST HTML5 Parser (w/auto corrections) JS Parser AST Walker Template w/filter markups abstracting branching logics and output expressions CSS Parser Pre- compiler Contextual XSS Filters (registered as helpers/callbacks) HTML Data (possibly untrusted) Runtime Compiler Template Spec. Our solution comprises of only the blue boxes
  • 12. Handlebars Context Parser Handlebars PreProcessor High-level Architecture Template Parser Template AST HTML5 Parser (w/auto corrections) JS Parser AST Walker Template w/filter markups abstracting branching logics and output expressions CSS Parser Pre- compiler Contextual XSS Filters (registered as helpers/callbacks) HTML Data (possibly untrusted) Runtime Compiler Template Spec. Our solution comprises of only the blue boxes
  • 13. Pre-Processor: Good Template Samples [Before] <a href="{{url}}">{{url}}</a> [After] <a href="{{{yubl (yavd (yufull url))}}}">{{{yd url}}}</a> Add contextual escaping filters {{{ }}} - disable the default blindly-escaping yufull - encodeURI()with IPv6 support yavd - html-escape double-quote character (" → &quot;) yubl - disable dangerous protocols such as javascript: yd - html-escape less-than character (< → &lt;)
  • 14. Pre-Processor: Bad Template Samples [Before] <input type="button" onclick="doSth({{data}})"> Warning! Ensure placeholders are never put in scriptable contexts - Security anti-pattern to place (possibly) untrusted data in executable contexts - Workaround: - <input type="button" data-sth="{{data}}" onclick="doSth(this.getAttribute('data-sth'))">
  • 15. Pre-Processor: Branching Consistency Check [Before] {{#if highlight}}<strong>{{else}}<em {{/if}} {{unknownCxt}} ... [After] A warning is raised! {{#if highlight}}<strong>{{else}}<em {{/if}} {{data}} ... Walk through branches & ensure they end up in identical state/context - Likely a careless mistake or typo - Obviously, context of {{unknownCxt}} is ambiguous Warning!
  • 16. Handlebars Context Parser Handlebars PreProcessor High-level Architecture Template Parser Template AST HTML5 Parser (w/auto corrections) JS Parser AST Walker Template w/filter markups abstracting branching logics and output expressions CSS Parser Pre- compiler Contextual XSS Filters (registered as helpers/callbacks) HTML Data (possibly untrusted) Runtime Compiler Template Spec. Our solution comprises of only the blue boxes
  • 17. Standard Compliant - Can even auto-correct parse errors to enforce consistent parsing across browsers Robust, lightweight, and efficient - Simplified state transitions - No unnecessary handling (no DOM) Design Principles of Context Parser Figured from Overview of HTML 5 Parsing Model: https://html.spec.whatwg.org/multipage/syntax.html#overview-of-the-parsing-model
  • 18. Handlebars Context Parser Handlebars PreProcessor High-level Architecture Template Parser Template AST HTML5 Parser (w/auto corrections) JS Parser AST Walker Template w/filter markups abstracting branching logics and output expressions CSS Parser Pre- compiler Contextual XSS Filters (registered as helpers/callbacks) HTML Data (possibly untrusted) Runtime Compiler Template Spec. Our solution comprises of all blue boxes
  • 19. Design Principles of XSS Filters Context-aware - More Secure - escape only those that can break out from its context Just sufficient encoding - Faster - no need to escape all & > " ' ` - More friendly - no more double-encoding issues like &amp;lt;
  • 20. Deployability Adoption - Switch from express-handlebars to express-secure-handlebars npm - 2 LOCs changes: (1) dependency in package.json, (2) require(...) - Alternatively, a more decoupled approach: - pre-process tmpl to get it rewrited during build process at server - only register helpers for data filtering and binding at client-side Browser Compatibility - IE 7+, Safari 5+, Chrome, Firefox
  • 21. Evaluations Deployed in one the largest properties - Negligible offline overhead - takes <3s to analyze/pre-process 880 templates - Insignifiant runtime overhead (i.e., filter callbacks, size: 1.3KB gz) - unchained filters: up to 2 times faster than default - chained filters: slower but is already minimal to be secure - True positives found! - e.g., unquoted, onclick, URI attributes, script tags, etc.
  • 22. - More secure, efficient, and easier adoption - Open-sourced at github.com/yahoo and npmjs.com - Contact/Collaborate with us for more template support Conclusion: Building A Safer Internet for All Automatic contextual escaping made easy
  • 23. Thank you! Nera, Albert, Adon {neraliu, albertyu, adon}@yahoo-inc. com Twitter: @neraliu, @yukinying, @adonatwork