Trusted Types & the end of DOM XSS

Jakub Vrana, Krzysztof Kotowicz (Google)

ZeroNights 2019 · Day 1

Overview

This talk, "Trusted Types & the end of DOM XSS," presented by Jakub Vrana and Krzysztof Kotowicz from Google at ZeroNights, introduces Trusted Types, a novel browser API designed to fundamentally eliminate DOM-based Cross-Site Scripting (XSS) vulnerabilities. The speakers argue that despite extensive security efforts, including hardened libraries, static/dynamic analysis, security reviews, and bug bounty programs, DOM XSS remains a pervasive and costly problem for even the most security-conscious organizations. Trusted Types aims to solve this by introducing strong typing for sensitive DOM manipulation sinks, thereby restricting the direct use of attacker-controlled strings and enforcing security policies at the browser level.

Watch on YouTube

Visual summary for Trusted Types & the end of DOM XSS by Jakub Vrana, Krzysztof Kotowicz
Visual summary for Trusted Types & the end of DOM XSS by Jakub Vrana, Krzysztof Kotowicz

Key moments

  1. 2:00 XSS is still a top vulnerability
  2. 6:30 Demonstrating why DOM XSS is hard to detect
  3. 10:00 Trusted Types: Strongly-typed DOM sinks for security
  4. 14:40 Creating trusted objects using security policies
  5. 20:00 Practical strategy for deploying Trusted Types
  6. 25:00 Live demo: Trusted Types on Google Contacts
  7. 30:00 Benefits and the future of eliminating DOM XSS

Trusted Types & the end of DOM XSS

Speakers: Jakub Vrana, Krzysztof Kotowicz (Google)

Conference: ZeroNights

YouTube: https://www.youtube.com/watch?v=vYA81UAExKA

Overview

This talk, "Trusted Types & the end of DOM XSS," presented by Jakub Vrana and Krzysztof Kotowicz from Google at ZeroNights, introduces Trusted Types, a novel browser API designed to fundamentally eliminate DOM-based Cross-Site Scripting (XSS) vulnerabilities. The speakers argue that despite extensive security efforts, including hardened libraries, static/dynamic analysis, security reviews, and bug bounty programs, DOM XSS remains a pervasive and costly problem for even the most security-conscious organizations. Trusted Types aims to solve this by introducing strong typing for sensitive DOM manipulation sinks, thereby restricting the direct use of attacker-controlled strings and enforcing security policies at the browser level.

The core motivation for Trusted Types stems from the persistent nature of DOM XSS, which is both exceptionally easy for developers to introduce and remarkably difficult for security professionals to detect, especially within large, complex web applications. By shifting the paradigm from reactive detection to proactive prevention, Trusted Types offers a mechanism to significantly reduce the attack surface, make security explicit, and transform XSS bugs into standard programming TypeErrors. This approach promises to make web applications inherently more secure against a vulnerability class that has plagued the web for nearly two decades, offering a path towards its complete eradication.

Background

▶ Watch: XSS is still a top vulnerability (2:00)

The presentation begins by highlighting the stark reality of web application security: despite substantial investment and sophisticated defenses, Cross-Site Scripting (XSS) remains a dominant threat. Jakub Vrana shares compelling internal data from Google's vulnerability rewards program (VRP), revealing that in the preceding year, half of all payments to external researchers were for web bugs, with XSS consistently being the most highly rewarded vulnerability type. This trend is not unique to Google; data from platforms like HackerOne and Mozilla corroborate that XSS is a top reported and rewarded vulnerability globally. This persistent threat underscores a systemic problem that traditional security measures have struggled to contain.

The talk specifically focuses on DOM-based XSS, a subset of XSS vulnerabilities where the malicious payload is executed entirely on the client-side due to flaws in the application's client-side JavaScript. A typical DOM XSS scenario involves attacker-controlled data, originating from a "source" (e.g., location.hash, URL parameters), flowing into a "sink" (e.g., innerHTML, eval(), document.write), leading to the execution of arbitrary JavaScript in the victim's browser. This effectively grants the attacker equivalent privileges to remote code execution within the user's session.

The speakers identify two primary reasons for the pervasiveness of DOM XSS:

  1. Ease of Introduction: Developers can inadvertently introduce DOM XSS with surprising ease. While assigning user-controlled data directly to innerHTML is a textbook example, the problem extends far beyond this single sink. There are numerous DOM APIs that, when fed unsanitized user input, can lead to XSS. Teaching thousands of developers to meticulously sanitize every piece of user data before it touches any of these diverse sinks is an incredibly challenging, if not impossible, task. Mistakes are inevitable, especially in rapidly evolving codebases.
  2. Difficulty of Detection: Detecting DOM XSS is notoriously hard for security professionals. Unlike server-side vulnerabilities, DOM XSS involves complex client-side data flows. A simple code snippet in isolation often provides no indication of vulnerability; understanding whether it's an XSS requires tracing the data's origin to an attacker-controlled source and its destination to a sensitive sink, potentially across the entire application's JavaScript codebase. This holistic analysis is extremely difficult for static analysis tools to accurately model and for human reviewers to consistently perform, particularly in large-scale applications with millions of lines of code. The speaker illustrates this with a series of code snippets, demonstrating how seemingly innocuous lines of code can become problematic depending on context, making comprehensive manual review impractical.

Current defensive strategies, such as developing hardened libraries, employing static and dynamic code analysis, conducting manual security reviews, and running bug bounty programs, have proven insufficient to eradicate DOM XSS. The inherent nature of the web platform, where powerful APIs accept generic strings, allows security-critical data flows to blend indistinguishably with benign ones, making the problem fundamentally difficult to solve at scale.

Key Findings

▶ Watch: Trusted Types: Strongly-typed DOM sinks for security (10:00)

The talk's key findings revolve around the identification of the root cause of persistent DOM XSS and the proposal of a novel architectural solution:

  • Strings are the Root Cause: The fundamental problem underlying DOM XSS is that sensitive DOM manipulation functions (sinks) in web browsers traditionally accept generic strings. These strings carry no inherent security context, making it impossible for the browser or JavaScript runtime to distinguish between benign, sanitized content and malicious, attacker-controlled payloads. This lack of type safety forces applications to rely on fragile, error-prone manual sanitization at every point where user data interacts with a sink.
  • DOM XSS is Pervasive and Costly: Despite significant security investments and advanced tooling, DOM XSS remains a top vulnerability type, leading to substantial bug bounty payouts and continuous security incidents. This demonstrates the failure of current mitigation strategies to address the problem at its core.
  • The Solution: Strong Typing for DOM Sinks: The core insight of Trusted Types is to introduce strong typing for all sensitive DOM sinks. Instead of accepting generic strings, these sinks will now require specific TrustedType objects. These objects embed security-critical information, ensuring that any data passed to a sink has been explicitly processed by a trusted, application-defined security policy.
  • Reduced Attack Surface: By enforcing strong typing, Trusted Types drastically reduces the attack surface. Instead of every line of code that touches the DOM being a potential XSS vector, only the code within explicitly defined and whitelisted security policies has the capability to create TrustedType objects and thus interact with sensitive sinks. This allows security teams to focus their review efforts on a significantly smaller, more manageable codebase.
  • Explicit Security and Debuggability: Trusted Types makes security explicit. The act of creating a TrustedType object through a policy clearly indicates a security-sensitive operation. Furthermore, if an application attempts to pass a raw string to a protected sink, the browser will throw a TypeError (when enforced). This transforms what would otherwise be a silent, exploitable security flaw into a standard, debuggable programming error, allowing developers to use familiar debugging tools to identify and fix issues.
  • Progressive Migration is Possible: The API is designed with migration in mind, offering a report-only mode and the concept of a default policy. This allows applications to gradually adopt Trusted Types without immediately breaking existing functionality, providing a pathway for large, complex codebases to transition.
  • A Chance to End DOM XSS: The speakers confidently assert that Trusted Types offers the first realistic opportunity in 18 years to completely eliminate DOM XSS as a class of vulnerabilities, moving beyond mere mitigation to fundamental prevention.

Technical Deep Dive

▶ Watch: Creating trusted objects using security policies (14:40)

The technical foundation of Trusted Types lies in its ability to introduce strong typing to browser DOM APIs that are traditionally vulnerable to XSS. The main idea is to replace generic string inputs for sensitive DOM sinks with specialized TrustedType objects. This leverages an existing browser behavior where DOM APIs like innerHTML can process objects that have a toString() method, implicitly converting them to strings. Trusted Types formalizes this by introducing specific object types that carry security guarantees.

Trusted Types are contextual, meaning different types are required for different kinds of sinks, reflecting the varying sanitization needs:

  • TrustedHTML: For sinks that expect HTML content, such as element.innerHTML, iframe.srcdoc, or document.write.
  • TrustedScript: For sinks that expect executable JavaScript code, like eval(), setTimeout(), script.textContent, or script.text.
  • TrustedScriptURL: For sinks that expect a URL pointing to a JavaScript file, such as script.src, worker.src, or import().

The enforcement of Trusted Types is seamlessly integrated with the Content Security Policy (CSP) header, utilizing a new trusted-types directive.

  • Non-Enforced Mode: When an application supports Trusted Types but doesn't enforce it via CSP, DOM sinks will still accept strings (potentially leading to XSS). However, they will also silently accept and unwrap TrustedType objects, allowing for progressive adoption.
  • Report-Only Mode: By using Content-Security-Policy-Report-Only: trusted-types *; report-uri /csp-report-endpoint, developers can deploy Trusted Types without breaking the application. When a string is assigned to a protected sink, the browser will still accept it but will send a violation report to the specified endpoint, providing visibility into potential XSS vectors.
  • Enforcement Mode: The true power comes with Content-Security-Policy: trusted-types *; .... In this mode, DOM sinks will stop accepting raw strings. Any attempt to assign a string to a protected sink will result in a TypeError in the application's JavaScript runtime, in addition to sending a violation report. This is a critical property, as it elevates security bugs to the level of standard programming errors, making them debuggable with conventional developer tools.

The creation of TrustedType objects is controlled through Policies. An application defines these policies using the trustedTypes.createPolicy() function:

Each policy has a unique name and a set of functions (createHTML, createScript, createScriptURL) that define the rules for converting a string into a TrustedType object. The security logic, such as an HTML sanitizer, resides entirely within these policy functions. Once a policy is created, its functions can be called to generate TrustedType objects: const safeHtml = sanitizerPolicy.createHTML(attackerControlledString);. This safeHtml object can then be safely passed to element.innerHTML.

Crucially, applications use the trusted-types directive in their CSP header to whitelist the names of allowed policies: Content-Security-Policy: trusted-types my-sanitizer another-policy; .... This means that only code within these explicitly named policies has the capability to create TrustedType objects. Any other part of the application that attempts to create a TrustedType object (or directly assign a string to a sink in enforcement mode) will be blocked. This dramatically reduces the "review surface" for security, as auditors can focus almost exclusively on the code within these whitelisted policies.

To aid in migration, Trusted Types introduces the concept of a default policy. If an application is in enforcement mode and a string is passed to a sink without being explicitly converted by a named policy, the browser will implicitly call the default policy (if one exists and is whitelisted). This allows developers to implement a "last-resort" sanitization or logging mechanism for legacy code during the migration phase:

Additionally, Trusted Types enhances security around javascript: URLs. By default, if Trusted Types are enforced, direct navigation to javascript: URLs is blocked. If a default policy is present, it will be invoked to process the javascript: URL's value, allowing for fine-grained control or complete blocking of such potentially malicious links. For example, javascript:void(0) could be explicitly allowed while other payloads are blocked.

The recommended deployment strategy for Trusted Types involves several steps:

  1. Migrate Core Libraries: Identify and update core libraries that interact directly with the DOM (e.g., client-side templating engines, HTML sanitizers, dynamic script loaders) to use Trusted Types. These are typically a small, well-defined subset of the codebase.
  2. Static Analysis: Employ static analysis tools (e.g., custom compilers, linters, grep checks) to identify and refactor any remaining direct string-to-sink assignments.
  3. Report-Only Deployment: Deploy the application with Trusted Types in report-only mode via CSP. Monitor violation reports to identify any missed XSS vectors or legacy code issues.
  4. Debug and Refactor: Analyze reported violations, debug them as TypeErrors, and migrate additional code as necessary.
  5. Enforcement: Once violations are minimized, switch to full enforcement mode via CSP.

A significant benefit of this approach is the fault-tolerance it provides. Once Trusted Types are enforced, any new code introduced into the application cannot inadvertently create a DOM XSS without explicitly going through a whitelisted policy. This ensures that the security posture established by Trusted Types remains robust over time, even as the codebase evolves. Furthermore, the API provides fine-grained control over both policy creation (via CSP whitelisting of names, preventing duplicates) and policy usage (by limiting the scope of policy objects in JavaScript modules or functions), allowing for highly compartmentalized security.

Demo / Proof of Concept

▶ Watch: Live demo: Trusted Types on Google Contacts (25:00)

The speakers provided a live demonstration using Chrome Canary, showcasing Trusted Types' capabilities in both a simple toy application and a real-world Google application.

1. Toy Application Demonstration:

The demo began with a basic web page featuring a text input field and two buttons: "Inner HTML" and "Sanitize."

  • Without Trusted Types Enforcement:
  • Entering an XSS payload like <img src=x onerror=alert(1)> into the input and clicking "Inner HTML" resulted in the alert(1) payload executing, demonstrating a classic DOM XSS.
  • Clicking "Sanitize" (which used DOMPurify without Trusted Types integration) successfully removed the onerror attribute, making the HTML safe and preventing the alert.
  • With Trusted Types Enforcement (No Default Policy):
  • The page was reloaded with a Content Security Policy (CSP) header that included trusted-types *; require-trusted-types-for 'script';.
  • Entering the same XSS payload and clicking "Inner HTML" now resulted in a TypeError in the browser console, stating that innerHTML was assigned a string value, which is disallowed by Trusted Types. The XSS payload was prevented from executing. This highlights how security bugs become standard, debuggable programming errors.
  • Clicking "Sanitize" still worked correctly. This is because DOMPurify has been updated to support Trusted Types via a RETURN_TRUSTED_TYPES: true option. When this option is enabled, DOMPurify's sanitization process creates a TrustedHTML object, which is then safely accepted by innerHTML.
  • With Trusted Types Enforcement (with Default Policy):
  • A default policy was installed using trustedTypes.createPolicy('default', { createHTML: (s) => DOMPurify.sanitize(s, {RETURN_TRUSTED_TYPES: true}) });. This policy essentially configured DOMPurify to be the fallback sanitizer for any string passed to an HTML sink.
  • Entering the XSS payload and clicking "Inner HTML" now resulted in the payload being automatically sanitized by the default policy (using DOMPurify), and no TypeError occurred. The output was safe HTML. This demonstrates how a default policy can help legacy code continue to function safely during migration.

2. Real-World Application Demonstration (contacts.google.com):

The speaker then showed contacts.google.com, an actual Google product that has been partially migrated to use Trusted Types in report-only mode.

  • The browser's developer tools revealed several active Trusted Types policies (e.g., _html, _script, _js_url, dompurify).
  • While interacting with the application, the speaker demonstrated editing a contact's "More" section. Upon saving, a CSP report-only violation was triggered.
  • The violation report, accessible in the developer console, provided detailed information: the specific JavaScript file (identified as part of the Google Maps API), the line number, the violated directive (trusted-types), the sink (script.src), and the string value that caused the violation. This clearly indicated that a third-party script (Google Maps API) was assigning a string to script.src without using Trusted Types, even though the main application was compliant.
  • This real-world example effectively illustrated the challenges of migrating large applications, especially those relying on third-party libraries, and how Trusted Types' report-only mode provides invaluable debugging information for identifying and addressing such issues systematically. The detailed CSP reports, including script origin and line number, make it practical to track down and fix violations.

The demo conclusively showed that Trusted Types is not just a theoretical concept but a practical, implemented solution in Chromium that can be deployed and debugged in real-world scenarios, offering concrete protection against DOM XSS.

Defensive Implications

▶ Watch: Benefits and the future of eliminating DOM XSS (30:00)

Trusted Types introduces profound defensive implications for web application security, moving beyond traditional mitigation techniques to offer a fundamental solution for DOM XSS.

  1. Elimination of DOM XSS as a Class: The most significant implication is the potential to completely eliminate DOM XSS vulnerabilities from web applications. By enforcing strong typing at the browser level, Trusted Types ensures that malicious strings cannot reach sensitive DOM sinks, thereby preventing the core mechanism of DOM XSS. This shifts the security paradigm from "detect and fix" to "prevent by design."
  1. Drastically Reduced Attack Surface: Trusted Types dramatically shrinks the attack surface. Instead of every line of JavaScript code being a potential vector for DOM XSS, only the explicitly defined and whitelisted security policies can create TrustedType objects. This confines the capability to introduce XSS to a very small, well-defined portion of the codebase.
  1. Reduced Security Review Surface: Consequently, security teams can focus their review efforts on these few, critical security policies. Instead of needing to audit an entire application for vulnerable data flows, reviewers can confidently ascertain the security of the application by meticulously examining the code within the whitelisted policies. This makes security audits more efficient, effective, and scalable.
  1. Security by Default (Fault Tolerance): Once Trusted Types is enforced via CSP, any new code introduced into the application that attempts to assign a raw string to a protected DOM sink will automatically fail with a TypeError. This provides robust, fault-tolerant security, ensuring that future development efforts do not inadvertently reintroduce DOM XSS vulnerabilities without explicit changes to the security policy. The application remains secure even as it evolves.
  1. Explicit Security Logic: Trusted Types forces applications to make their security logic explicit. Sanitization, escaping, and other security-critical data transformations must be encapsulated within named policies. This transparency makes it easier to understand, audit, and maintain the application's security posture.
  1. Improved Debuggability: By transforming XSS vulnerabilities into standard TypeErrors, Trusted Types allows developers to use familiar debugging tools (like Chrome's developer console) to identify, locate, and fix security issues. This reduces the specialized knowledge often required for XSS debugging and integrates security fixes into the regular development workflow.
  1. Enhanced Control and Isolation: Developers gain granular control over policy creation (via CSP whitelisting) and policy usage (by scoping policy objects in JavaScript modules or functions). This allows for strong isolation of security-sensitive code, ensuring that even if one policy is found to be flawed, its impact can be contained.
  1. Ecosystem Integration: Trusted Types is designed to integrate with existing web development practices and libraries. It works with popular client-side templating libraries (like React, with minor adjustments), and sanitization libraries like DOMPurify already offer modes to produce TrustedType objects. This ensures that developers can leverage existing tools while adopting the new API.
  1. Standardization and Browser Support: As a W3C specification draft and already implemented in Chromium (behind a flag), Trusted Types is on a path to becoming a web standard. This indicates future widespread browser support, making it a viable long-term solution for web developers.

By embracing Trusted Types, defenders can shift from a reactive stance against a persistently exploited vulnerability to a proactive, architectural solution that hardens web applications against DOM XSS from the ground up.

Key Takeaways

  • DOM XSS Remains a Critical Problem: Despite extensive security efforts and significant bug bounty payouts, DOM-based Cross-Site Scripting continues to be a top vulnerability, primarily because it's easy to introduce and extremely difficult to detect in complex web applications.
  • Trusted Types is a Foundational Solution: The new Trusted Types browser API fundamentally addresses DOM XSS by requiring strongly-typed objects (e.g., TrustedHTML, TrustedScript, TrustedScriptURL) instead of generic strings for sensitive DOM manipulation sinks, embedding security context directly into the data.
  • Enforcement via Content Security Policy (CSP): Trusted Types integrates with CSP, allowing applications to enforce strong typing, whitelist approved security policies, and receive violation reports. This enables both progressive migration (report-only mode) and strict prevention (enforcement mode).
  • Security Policies Centralize Logic: Applications define named policies that contain the specific, reviewed logic for converting untrusted strings into trusted types. This drastically reduces the attack surface, as only code within whitelisted policies can create objects capable of interacting with sensitive DOM sinks.
  • Improved Security Posture and Debuggability: Trusted Types makes security explicit, reduces the review surface to a few core policies, and transforms XSS vulnerabilities into standard TypeErrors, making them debuggable with conventional developer tools. This provides a robust, fault-tolerant security model.
  • Real-World Ready: Implemented in Chromium (Chrome Canary), with a W3C specification draft, and already deployed in parts of Google's applications (like contacts.google.com), Trusted Types is a practical solution ready for adoption and feedback from the wider security and development communities.

About the Speaker(s)

Jakub Vrana is a security engineer working at Google. His work focuses on securing web products within a large company that constantly releases and updates numerous web applications. His team employs a multi-faceted approach to security, including developing hardened libraries for front-end developers, using static and dynamic analysis to ensure adherence to security guidelines, conducting manual security reviews before product launches, and running a bug bounty program. Jakub's insights into the persistent challenges of DOM XSS, even within an organization with extensive security resources, underscore the critical need for a solution like Trusted Types.

Krzysztof Kotowicz is also a speaker from Google. While the transcript primarily features Jakub Vrana's voice, Krzysztof is listed as a co-speaker, indicating his significant contribution to the development and presentation of Trusted Types. As an expert from Google, he is likely involved in web security research and the implementation of security features within the Chrome browser and Google's vast web ecosystem.

Reviews

Dr. Zero (Offensive Security Researcher) — MUST SEE

For two decades, we've tried to patch DOM XSS with developer training and fragile sanitizers. Vrana and Kotowicz finally did the only thing that matters: they fixed the browser's underlying architecture to kill the bug class entirely.

Heather Calloway (CISO) — MUST SEE

This talk outlines a structural fix for DOM XSS that shifts the burden from developer training to browser-level enforcement. By reducing the security review surface to a few whitelisted policies, it gives AppSec teams a scalable way to govern client-side risk. Worth your application security leadership's immediate attention.

→ Top-rated talks at ZeroNights 2019

All talks from ZeroNights 2019