SlideShare a Scribd company logo
1 of 27
Download to read offline
Trusted Types
and the end of DOM XSS
Krzysztof Kotowicz, Google
@kkotowicz
koto@google.com
What if we could...
● Fix the root cause of DOM XSS
● Help developers write secure code
● Simplify security reviews
● Dramatically reduce the attack surface
● Without breaking our applications?
DOM XSS
DOM XSS refresher
● Purely client-side XSS variant
● Data read from user controlled source is passed to a DOM XSS sink
● Example:
location.hash ⇒ … ⇒ bar.innerHTML
https://example.com/#<img src=x onerror=alert(1)>
Why do we still have DOM XSS?
Easy to
introduce
Hard to
detect
&
● It's not just innerHTML
● Many string -> code functions (DOM XSS sinks)
● They accept URLs, HTML, or Javascript code
DOM API is not secure by default
eval('foo()');
document.createElement('div').innerHTML = '<foo>';
document.createElement('script').src = '//foo';
document.createElement('a').setAttribute('onclick', 'foo()');
document.createElement('div').insertAdjacentHTML('beforebegin',
'<foo>');
new DOMParser().parseFromString('<foo>', 'text/html');
window.open('//foo');
> 60
sinks
● Sources far from sink, complex data flows
● JavaScript is dynamic
● DOM XSS lurks in the shadows: script gadgets
It's hard to analyze code
// What is bar?
foo.innerHTML = bar
// Non-deterministic value
function getPropertyName() {
if (condition)
return 'innerHTML';
}
foo[getPropertyName()] = bar
Growing problem
● DOM sinks can be used by your own code
● … or the libraries you use
● … or the scripts you load (analytics?)
● … or the script that they load at runtime.
● Each of those potentially adds DOM XSS.
● Applications grow in size.
● It's untenable to write & deploy DOM-XSS free apps
● At Google, DOM XSS is already the most common XSS variant.
We know how to address it!
Safe Types (link)
● 6+ years of experience
● Protects Gmail and almost all other
Google applications
● Evidence of efficacy
● Securely produce values that end up in DOM
● Implemented as Java{Script},Go, … libraries
● We're porting this approach directly to the browsers
Trusted Types
github.com/WICG/trusted-types
Design principles
● Empower the developers to:
○ Write secure code easy
○ Use the secure by default APIs
○ Get early feedback
● Empower the security professionals to:
○ Control the security-relevant code
○ Be looped-in when needed
○ Review the application
● Integrate with the existing ecosystem
○ Don't break the web!
○ Be backwards-compatible
○ Leverage existing solutions
Main idea
● Don't pass (HTML, URL, script URL) strings to the DOM sinks
● Use objects instead
● DOM already supports it:
● Instead of plain JS objects, use typed objects
○ TrustedHTML, TrustedScript, TrustedURL, TrustedScriptURL
● Make DOM sinks reject strings, and accept only the matching type
el.innerHTML = {toString: function() {return 'hello' }};
el.innerHTML // 'hello'
DOM sinks reject the strings:
DOM sinks accept the typed objects:
Enforcement mode
element.innerHTML = aString;
Content-Security-Policy: trusted-types *
element.innerHTML = aTrustedHTML;
DOM sinks accept & report the strings:
DOM sinks accept the typed objects:
Report-only
element.innerHTML = aString;
element.innerHTML = aTrustedHTML;
Content-Security-Policy-Report-Only: trusted-types *; report-uri https://
DOM sinks accept the strings:
DOM sinks accept the typed objects:
No enforcement
element.innerHTML = aString;
element.innerHTML = aTrustedHTML;
Content-Security-Policy: -
Creating the types
● First, create policies that define validation rules
● Policies have a unique name
● Use the policies to create Trusted Type objects
export const SanitizingPolicy = TrustedTypes.createPolicy('sanitizing', {
createHTML(s: string) => myCustomSanitizer(s)
}, false);
import {SanitizingPolicy} from './security/sanitizing-policy.ts';
// Calls myCustomSanitizer(foo).
const trustedTHML = SanitizingPolicy.createHTML(foo);
element.innerHTML = trustedHTML;
● You can create policy named "default"
● It will be called as a fallback when you're using a string with a sink.
TrustedTypes.createPolicy('default', {
createHTML(s) {
console.log("fix me plz", s);
return s;
}
}, true)
Default policy
DEMO #1
bit.ly/trusted-types-demo1
Control policy creation:
● Policy name whitelist:
● No duplicate policy names
Control policy usage:
● Policies are JavaScript objects
● Lock them in a module, inside a local function variable etc.
Control over policies
Content-Security-Policy: trusted-types sanitizing other
No drive-by policies!
Control over policies
(function() {
// Seemingly unsafe policy
const unsafePolicy = TrustedTypes.createPolicy('main-component', {
createHTML: (s) => s,
});
// No XSS because of the usage limitation
unsafePolicy.createHTML(`<div>My application component<div>`)
})();
Reduced attack surface
● The risky data flow will always be:
source ⇒ … ⇒ policy ⇒ Trusted Type ⇒ … ⇒ … ⇒ DOM sink
● Policies are secure => Application is secure
● No access to the policy object? Cannot introduce DOM XSS!
● Dramatically minimize the trusted codebase, simplify reviews
Benefits
Strongly typed API
● Easier to inspect statically
● Enabling code completion, linting, documentation, automatic refactoring
● Security validation at compile time … and at runtime
Backwards compatibility
● Use types in place of strings with no breakage
Complements other security solutions
● E.g. nonce based CSP for server-side XSS + Trusted Types for DOM XSS
Benefits
DEMO #2
bit.ly/trusted-types-demo2
Trusted Types in practice
● DOM XSS sink functions are not called too often
● Policies in a few trusted components
○ Frameworks
○ Templating engines
○ HTML sanitizers (DOMPurify)
● Few misbehaving dependencies
● Code size overhead negligible
○ 66 bytes of the smallest polyfill
○ ~300 bytes in Google Closure
Porting modern applications is easy (we're already doing this!)
No!
● Designed to integrate smoothly with frameworks
○ Sample
● Helper libraries, tool integrations (WIP)
● Automatic refactorings for common use cases
○ E.g. Sinks called with string literals
● Support for a gradual migration
○ Start using TT without enforcement
○ Write a default policy to catch-all
○ Identify & address missing pieces through a default policy
○ Toggle report-only enforcement
○ Enforce when ready
Is it hard to migrate?
● Support in Chromium browsers (origin trial - tinyurl.com/try-trusted-types)
● Discussion group - trusted-types@googlegroups.com
● W3C specification draft - https://wicg.github.io/trusted-types/
● Polyfills & documentation at https://github.com/WICG/trusted-types
● Adopting in Google applications
Working on external integrations:
● DOMPurify
● TypeScript type definitions - http://definitelytyped.org/
● Trials with Angular (sample patch), React, more to come…
● Secure policies library
● <your-project-here>
Project status
tinyurl.com/try-trusted-types
Let's end DOM XSS together!
We're hiring too - koto@google.com

More Related Content

What's hot

Switch statements in Java
Switch statements  in JavaSwitch statements  in Java
Switch statements in Java
Jin Castor
 

What's hot (20)

Stack using Linked List
Stack using Linked ListStack using Linked List
Stack using Linked List
 
x86
x86x86
x86
 
NTUSTxTDOH - Pwn基礎 2015/12/27
NTUSTxTDOH - Pwn基礎 2015/12/27NTUSTxTDOH - Pwn基礎 2015/12/27
NTUSTxTDOH - Pwn基礎 2015/12/27
 
Manipulators
ManipulatorsManipulators
Manipulators
 
STACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data StructureSTACK ( LIFO STRUCTURE) - Data Structure
STACK ( LIFO STRUCTURE) - Data Structure
 
Linked list
Linked listLinked list
Linked list
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Insertion Sort
Insertion SortInsertion Sort
Insertion Sort
 
Java. Интерфейс Map - ассоциативные массивы.
Java. Интерфейс Map - ассоциативные массивы.Java. Интерфейс Map - ассоциативные массивы.
Java. Интерфейс Map - ассоциативные массивы.
 
Java. Сборщик мусора. Работа с памятью.
Java.  Сборщик мусора. Работа с памятью. Java.  Сборщик мусора. Работа с памятью.
Java. Сборщик мусора. Работа с памятью.
 
PostgreSQL Query Cache - "pqc"
PostgreSQL Query Cache - "pqc"PostgreSQL Query Cache - "pqc"
PostgreSQL Query Cache - "pqc"
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 
FPGA2018: A Lightweight YOLOv2: A binarized CNN with a parallel support vecto...
FPGA2018: A Lightweight YOLOv2: A binarized CNN with a parallel support vecto...FPGA2018: A Lightweight YOLOv2: A binarized CNN with a parallel support vecto...
FPGA2018: A Lightweight YOLOv2: A binarized CNN with a parallel support vecto...
 
MySQL 5.7 String Functions
MySQL 5.7 String FunctionsMySQL 5.7 String Functions
MySQL 5.7 String Functions
 
Switch statements in Java
Switch statements  in JavaSwitch statements  in Java
Switch statements in Java
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
ROC 50 MILES 2023 ΤΕΧΝΙΚΗ ΕΝΗΜΕΡΩΣH
ROC 50 MILES 2023 ΤΕΧΝΙΚΗ ΕΝΗΜΕΡΩΣHROC 50 MILES 2023 ΤΕΧΝΙΚΗ ΕΝΗΜΕΡΩΣH
ROC 50 MILES 2023 ΤΕΧΝΙΚΗ ΕΝΗΜΕΡΩΣH
 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 

Similar to Trusted Types and the end of DOM XSS

Trusted Types - Securing the DOM from the bottom up (JSNation Amsterdam)
Trusted Types - Securing the DOM from the bottom up (JSNation Amsterdam)Trusted Types - Securing the DOM from the bottom up (JSNation Amsterdam)
Trusted Types - Securing the DOM from the bottom up (JSNation Amsterdam)
Krzysztof Kotowicz
 
[OPD 2019] Trusted types and the end of DOM XSS
[OPD 2019] Trusted types and the end of DOM XSS[OPD 2019] Trusted types and the end of DOM XSS
[OPD 2019] Trusted types and the end of DOM XSS
OWASP
 
Course_Presentation cyber --------------.pptx
Course_Presentation cyber --------------.pptxCourse_Presentation cyber --------------.pptx
Course_Presentation cyber --------------.pptx
ssuser020436
 
Scriptless Attacks - Stealing the Pie without touching the Sill
Scriptless Attacks - Stealing the Pie without touching the SillScriptless Attacks - Stealing the Pie without touching the Sill
Scriptless Attacks - Stealing the Pie without touching the Sill
Mario Heiderich
 

Similar to Trusted Types and the end of DOM XSS (20)

Trusted Types @ W3C TPAC 2018
Trusted Types @ W3C TPAC 2018Trusted Types @ W3C TPAC 2018
Trusted Types @ W3C TPAC 2018
 
Trusted Types - Securing the DOM from the bottom up (JSNation Amsterdam)
Trusted Types - Securing the DOM from the bottom up (JSNation Amsterdam)Trusted Types - Securing the DOM from the bottom up (JSNation Amsterdam)
Trusted Types - Securing the DOM from the bottom up (JSNation Amsterdam)
 
[OPD 2019] Trusted types and the end of DOM XSS
[OPD 2019] Trusted types and the end of DOM XSS[OPD 2019] Trusted types and the end of DOM XSS
[OPD 2019] Trusted types and the end of DOM XSS
 
The Supporting Role of Antivirus Evasion while Persisting
The Supporting Role of Antivirus Evasion while PersistingThe Supporting Role of Antivirus Evasion while Persisting
The Supporting Role of Antivirus Evasion while Persisting
 
Let's talk Security
Let's talk SecurityLet's talk Security
Let's talk Security
 
XP Days 2019: First secret delivery for modern cloud-native applications
XP Days 2019: First secret delivery for modern cloud-native applicationsXP Days 2019: First secret delivery for modern cloud-native applications
XP Days 2019: First secret delivery for modern cloud-native applications
 
Introduction to Web Application Security - Blackhoodie US 2018
Introduction to Web Application Security - Blackhoodie US 2018Introduction to Web Application Security - Blackhoodie US 2018
Introduction to Web Application Security - Blackhoodie US 2018
 
Course_Presentation cyber --------------.pptx
Course_Presentation cyber --------------.pptxCourse_Presentation cyber --------------.pptx
Course_Presentation cyber --------------.pptx
 
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
 
The innerHTML Apocalypse
The innerHTML ApocalypseThe innerHTML Apocalypse
The innerHTML Apocalypse
 
Rethinking The Policy Agent
Rethinking The Policy AgentRethinking The Policy Agent
Rethinking The Policy Agent
 
Future-proof Development for Classic SharePoint
Future-proof Development for Classic SharePointFuture-proof Development for Classic SharePoint
Future-proof Development for Classic SharePoint
 
Ever Present Persistence - Established Footholds Seen in the Wild
Ever Present Persistence - Established Footholds Seen in the WildEver Present Persistence - Established Footholds Seen in the Wild
Ever Present Persistence - Established Footholds Seen in the Wild
 
Web security: Securing Untrusted Web Content in Browsers
Web security: Securing Untrusted Web Content in BrowsersWeb security: Securing Untrusted Web Content in Browsers
Web security: Securing Untrusted Web Content in Browsers
 
Scriptless Attacks - Stealing the Pie without touching the Sill
Scriptless Attacks - Stealing the Pie without touching the SillScriptless Attacks - Stealing the Pie without touching the Sill
Scriptless Attacks - Stealing the Pie without touching the Sill
 
BSides Rochester 2018: Chaim Sanders: How the Cookie Crumbles: Modern HTTP St...
BSides Rochester 2018: Chaim Sanders: How the Cookie Crumbles: Modern HTTP St...BSides Rochester 2018: Chaim Sanders: How the Cookie Crumbles: Modern HTTP St...
BSides Rochester 2018: Chaim Sanders: How the Cookie Crumbles: Modern HTTP St...
 
Security .NET.pdf
Security .NET.pdfSecurity .NET.pdf
Security .NET.pdf
 
cf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Woodcf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Wood
 
HTML, CSS & Javascript Architecture (extended version) - Jan Kraus
HTML, CSS & Javascript Architecture (extended version) - Jan KrausHTML, CSS & Javascript Architecture (extended version) - Jan Kraus
HTML, CSS & Javascript Architecture (extended version) - Jan Kraus
 
Self-Protecting JavaScript: A Lightweight Approach to Enforcing Security Poli...
Self-Protecting JavaScript: A Lightweight Approach to Enforcing Security Poli...Self-Protecting JavaScript: A Lightweight Approach to Enforcing Security Poli...
Self-Protecting JavaScript: A Lightweight Approach to Enforcing Security Poli...
 

More from Krzysztof Kotowicz

Hacking HTML5 offensive course (Zeronights edition)
Hacking HTML5 offensive course (Zeronights edition)Hacking HTML5 offensive course (Zeronights edition)
Hacking HTML5 offensive course (Zeronights edition)
Krzysztof Kotowicz
 

More from Krzysztof Kotowicz (15)

Biting into the forbidden fruit. Lessons from trusting Javascript crypto.
Biting into the forbidden fruit. Lessons from trusting Javascript crypto.Biting into the forbidden fruit. Lessons from trusting Javascript crypto.
Biting into the forbidden fruit. Lessons from trusting Javascript crypto.
 
Hacking HTML5 offensive course (Zeronights edition)
Hacking HTML5 offensive course (Zeronights edition)Hacking HTML5 offensive course (Zeronights edition)
Hacking HTML5 offensive course (Zeronights edition)
 
I'm in ur browser, pwning your stuff - Attacking (with) Google Chrome Extensions
I'm in ur browser, pwning your stuff - Attacking (with) Google Chrome ExtensionsI'm in ur browser, pwning your stuff - Attacking (with) Google Chrome Extensions
I'm in ur browser, pwning your stuff - Attacking (with) Google Chrome Extensions
 
HTML5: Atak i obrona
HTML5: Atak i obronaHTML5: Atak i obrona
HTML5: Atak i obrona
 
I'm in your browser, pwning your stuff
I'm in your browser, pwning your stuffI'm in your browser, pwning your stuff
I'm in your browser, pwning your stuff
 
Advanced Chrome extension exploitation
Advanced Chrome extension exploitationAdvanced Chrome extension exploitation
Advanced Chrome extension exploitation
 
Html5: Something wicked this way comes (Hack in Paris)
Html5: Something wicked this way comes (Hack in Paris)Html5: Something wicked this way comes (Hack in Paris)
Html5: Something wicked this way comes (Hack in Paris)
 
Something wicked this way comes - CONFidence
Something wicked this way comes - CONFidenceSomething wicked this way comes - CONFidence
Something wicked this way comes - CONFidence
 
Html5: something wicked this way comes - HackPra
Html5: something wicked this way comes - HackPraHtml5: something wicked this way comes - HackPra
Html5: something wicked this way comes - HackPra
 
Html5: something wicked this way comes
Html5: something wicked this way comesHtml5: something wicked this way comes
Html5: something wicked this way comes
 
Creating, obfuscating and analyzing malware JavaScript
Creating, obfuscating and analyzing malware JavaScriptCreating, obfuscating and analyzing malware JavaScript
Creating, obfuscating and analyzing malware JavaScript
 
Tworzenie, zaciemnianie i analiza złośliwego kodu JavaScript
Tworzenie, zaciemnianie i analiza złośliwego kodu JavaScriptTworzenie, zaciemnianie i analiza złośliwego kodu JavaScript
Tworzenie, zaciemnianie i analiza złośliwego kodu JavaScript
 
Jak ocalić swoje dane przed SQL injection?
Jak ocalić swoje dane przed SQL injection?Jak ocalić swoje dane przed SQL injection?
Jak ocalić swoje dane przed SQL injection?
 
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
 
Kompletny przewodnik po SQL injection dla developerów PHP (i nie tylko)
Kompletny przewodnik po SQL injection dla developerów PHP (i nie tylko)Kompletny przewodnik po SQL injection dla developerów PHP (i nie tylko)
Kompletny przewodnik po SQL injection dla developerów PHP (i nie tylko)
 

Recently uploaded

Recently uploaded (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 

Trusted Types and the end of DOM XSS

  • 1. Trusted Types and the end of DOM XSS Krzysztof Kotowicz, Google @kkotowicz koto@google.com
  • 2. What if we could... ● Fix the root cause of DOM XSS ● Help developers write secure code ● Simplify security reviews ● Dramatically reduce the attack surface ● Without breaking our applications?
  • 4. DOM XSS refresher ● Purely client-side XSS variant ● Data read from user controlled source is passed to a DOM XSS sink ● Example: location.hash ⇒ … ⇒ bar.innerHTML https://example.com/#<img src=x onerror=alert(1)>
  • 5. Why do we still have DOM XSS? Easy to introduce Hard to detect &
  • 6. ● It's not just innerHTML ● Many string -> code functions (DOM XSS sinks) ● They accept URLs, HTML, or Javascript code DOM API is not secure by default eval('foo()'); document.createElement('div').innerHTML = '<foo>'; document.createElement('script').src = '//foo'; document.createElement('a').setAttribute('onclick', 'foo()'); document.createElement('div').insertAdjacentHTML('beforebegin', '<foo>'); new DOMParser().parseFromString('<foo>', 'text/html'); window.open('//foo'); > 60 sinks
  • 7. ● Sources far from sink, complex data flows ● JavaScript is dynamic ● DOM XSS lurks in the shadows: script gadgets It's hard to analyze code // What is bar? foo.innerHTML = bar // Non-deterministic value function getPropertyName() { if (condition) return 'innerHTML'; } foo[getPropertyName()] = bar
  • 8. Growing problem ● DOM sinks can be used by your own code ● … or the libraries you use ● … or the scripts you load (analytics?) ● … or the script that they load at runtime. ● Each of those potentially adds DOM XSS. ● Applications grow in size. ● It's untenable to write & deploy DOM-XSS free apps ● At Google, DOM XSS is already the most common XSS variant.
  • 9. We know how to address it! Safe Types (link) ● 6+ years of experience ● Protects Gmail and almost all other Google applications ● Evidence of efficacy ● Securely produce values that end up in DOM ● Implemented as Java{Script},Go, … libraries ● We're porting this approach directly to the browsers
  • 11. Design principles ● Empower the developers to: ○ Write secure code easy ○ Use the secure by default APIs ○ Get early feedback ● Empower the security professionals to: ○ Control the security-relevant code ○ Be looped-in when needed ○ Review the application ● Integrate with the existing ecosystem ○ Don't break the web! ○ Be backwards-compatible ○ Leverage existing solutions
  • 12. Main idea ● Don't pass (HTML, URL, script URL) strings to the DOM sinks ● Use objects instead ● DOM already supports it: ● Instead of plain JS objects, use typed objects ○ TrustedHTML, TrustedScript, TrustedURL, TrustedScriptURL ● Make DOM sinks reject strings, and accept only the matching type el.innerHTML = {toString: function() {return 'hello' }}; el.innerHTML // 'hello'
  • 13. DOM sinks reject the strings: DOM sinks accept the typed objects: Enforcement mode element.innerHTML = aString; Content-Security-Policy: trusted-types * element.innerHTML = aTrustedHTML;
  • 14. DOM sinks accept & report the strings: DOM sinks accept the typed objects: Report-only element.innerHTML = aString; element.innerHTML = aTrustedHTML; Content-Security-Policy-Report-Only: trusted-types *; report-uri https://
  • 15. DOM sinks accept the strings: DOM sinks accept the typed objects: No enforcement element.innerHTML = aString; element.innerHTML = aTrustedHTML; Content-Security-Policy: -
  • 16. Creating the types ● First, create policies that define validation rules ● Policies have a unique name ● Use the policies to create Trusted Type objects export const SanitizingPolicy = TrustedTypes.createPolicy('sanitizing', { createHTML(s: string) => myCustomSanitizer(s) }, false); import {SanitizingPolicy} from './security/sanitizing-policy.ts'; // Calls myCustomSanitizer(foo). const trustedTHML = SanitizingPolicy.createHTML(foo); element.innerHTML = trustedHTML;
  • 17. ● You can create policy named "default" ● It will be called as a fallback when you're using a string with a sink. TrustedTypes.createPolicy('default', { createHTML(s) { console.log("fix me plz", s); return s; } }, true) Default policy
  • 19. Control policy creation: ● Policy name whitelist: ● No duplicate policy names Control policy usage: ● Policies are JavaScript objects ● Lock them in a module, inside a local function variable etc. Control over policies Content-Security-Policy: trusted-types sanitizing other No drive-by policies!
  • 20. Control over policies (function() { // Seemingly unsafe policy const unsafePolicy = TrustedTypes.createPolicy('main-component', { createHTML: (s) => s, }); // No XSS because of the usage limitation unsafePolicy.createHTML(`<div>My application component<div>`) })();
  • 21. Reduced attack surface ● The risky data flow will always be: source ⇒ … ⇒ policy ⇒ Trusted Type ⇒ … ⇒ … ⇒ DOM sink ● Policies are secure => Application is secure ● No access to the policy object? Cannot introduce DOM XSS! ● Dramatically minimize the trusted codebase, simplify reviews Benefits
  • 22. Strongly typed API ● Easier to inspect statically ● Enabling code completion, linting, documentation, automatic refactoring ● Security validation at compile time … and at runtime Backwards compatibility ● Use types in place of strings with no breakage Complements other security solutions ● E.g. nonce based CSP for server-side XSS + Trusted Types for DOM XSS Benefits
  • 24. Trusted Types in practice ● DOM XSS sink functions are not called too often ● Policies in a few trusted components ○ Frameworks ○ Templating engines ○ HTML sanitizers (DOMPurify) ● Few misbehaving dependencies ● Code size overhead negligible ○ 66 bytes of the smallest polyfill ○ ~300 bytes in Google Closure Porting modern applications is easy (we're already doing this!)
  • 25. No! ● Designed to integrate smoothly with frameworks ○ Sample ● Helper libraries, tool integrations (WIP) ● Automatic refactorings for common use cases ○ E.g. Sinks called with string literals ● Support for a gradual migration ○ Start using TT without enforcement ○ Write a default policy to catch-all ○ Identify & address missing pieces through a default policy ○ Toggle report-only enforcement ○ Enforce when ready Is it hard to migrate?
  • 26. ● Support in Chromium browsers (origin trial - tinyurl.com/try-trusted-types) ● Discussion group - trusted-types@googlegroups.com ● W3C specification draft - https://wicg.github.io/trusted-types/ ● Polyfills & documentation at https://github.com/WICG/trusted-types ● Adopting in Google applications Working on external integrations: ● DOMPurify ● TypeScript type definitions - http://definitelytyped.org/ ● Trials with Angular (sample patch), React, more to come… ● Secure policies library ● <your-project-here> Project status
  • 27. tinyurl.com/try-trusted-types Let's end DOM XSS together! We're hiring too - koto@google.com