--- url: "https://web.dev/articles/sandboxed-iframes" titulek: "Play safely in sandboxed IFrames | Articles | web.dev" h1: "Play safely in sandboxed IFrames Stay organized with collections Save and categorize content based on your preferences." popis: "" jazyk: "en" kanonicka: "https://web.dev/articles/sandboxed-iframes" drobecky: ["Articles", "Play safely in sandboxed IFrames"] zdroj: "live" wayback_snapshot: "" stazeno: "2026-09-13 23:13:10" znaku: 19133 slov: 2982 kodovani: "iso-8859-2" sha256: "00412ffb5d1b443449108b94b15ae98a88eb368097c77550f21c7056501a3cd0" --- Play safely in sandboxed IFrames Stay organized with collections Save and categorize content based on your preferences. Mike West Constructing a rich experience on today's web almost unavoidably involves embedding components and content over which you have no real control. Third-party widgets can drive engagement and play a critical role in the overall user experience, and user-generated content is sometimes even more important than a site's native content. Abstaining from either isn't really an option, but both increase the risk that Something Bad⢠could happen on your site. Each widget that you embed -- every ad, every social media widget -- is a potential attack vector for those with malicious intent: [Content Security Policy (CSP)](http://www.html5rocks.com/tutorials/security/content-security-policy/) can mitigate the risks associated with both of these types of content by giving you the ability to whitelist specifically trusted sources of script and other content. This is a major step in the right direction, but it's worth noting that the protection that most CSP directives offer is binary: the resource is allowed, or it isn't. There are times when it would be useful to say "I'm not sure I actually *trust* this source of content, but it's soooo pretty! Embed it please, Browser, but don't let it break my site." Least Privilege In essence, we're looking for a mechanism that will allow us to grant content we embed only the minimum level of capability necessary to do its job. If a widget doesn't *need* to pop up a new window, taking away access to window.open can't hurt. If it doesn't require Flash, turning off plugin support shouldn't be a problem. We're as secure as we can be if we follow the [principle of least privilege](http://en.wikipedia.org/wiki/Principle_of_least_privilege), and block each and every feature that isn't directly relevant to functionality we'd like to use. The result is that we no longer have to blindly trust that some piece of embedded content won't take advantage of privileges it shouldn't be using. It simply won't have access to the functionality in the first place. `iframe` elements are the first step toward a good framework for such a solution. Loading some untrusted component in an `iframe` provides a measure of separation between your application and the content you'd like to load. The framed content won't have access to your page's DOM, or data you've stored locally, nor will it be able to draw to arbitrary positions on the page; it's limited in scope to the frame's outline. The separation isn't truly robust, however. The contained page still has a number of options for annoying or malicious behavior: autoplaying video, plugins, and popups are the tip of the iceberg. The [**`sandbox`** attribute of the `iframe` element](http://www.whatwg.org/specs/web-apps/current-work/multipage/the-iframe-element.html#attr-iframe-sandbox) gives us just what we need to tighten the restrictions on framed content. We can instruct the browser to load a specific frame's content in a low-privilege environment, allowing only the subset of capabilities necessary to do whatever work needs doing. Twust, but verify Twitter's "Tweet" button is a great example of functionality that can be more safely embedded on your site via a sandbox. Twitter allows you to [embed the button via an iframe](https://dev.twitter.com/docs/tweet-button#using-an-iframe) with the following code: `` To figure out what we can lock down, let's carefully examine what capabilities the button requires. The HTML that's loaded into the frame executes a bit of JavaScript from Twitter's servers, and generates a popup populated with a tweeting interface when clicked. That interface needs access to Twitter's cookies in order to tie the tweet to the correct account, and needs the ability to submit the tweeting form. That's pretty much it; the frame doesn't need to load any plugins, it doesn't need to navigate the top-level window, or any of a number of other bits of functionality. Since it doesn't need those privileges, let's remove them by sandboxing the frame's content. Sandboxing works on the basis of a whitelist. We begin by removing all permissions possible, and then turn individual capabilities back on by adding specific flags to the sandbox's configuration. For the Twitter widget, we've decided to enable JavaScript, popups, form submission, and twitter.com's cookies. We can do so by adding a `sandbox` attribute to the `iframe` with the following value: `` That's it. We've given the frame all the capabilities it requires, and the browser will helpfully deny it access to any of the privileges that we didn't explicitly grant it via the `sandbox` attribute's value. Granular Control over Capabilities We saw a few of the possible sandboxing flags in the example above, let's now dig through the inner workings of the attribute in a little more detail. Given an iframe with an empty sandbox attribute, the framed document will be fully sandboxed, subjecting it to the following restrictions: JavaScript will not execute in the framed document. This not only includes JavaScript explicitly loaded via script tags, but also inline event handlers and javascript: URLs. This also means that content contained in noscript tags will be displayed, exactly as though the user had disabled script herself. The framed document is loaded into a unique origin, which means that all same-origin checks will fail; unique origins match no other origins ever, not even themselves. Among other impacts, this means that the document has no access to data stored in any origin's cookies or any other storage mechanisms (DOM storage, Indexed DB, etc.). The framed document cannot create new windows or dialogs (via `window.open` or `target="_blank"`, for instance). Forms cannot be submitted. Plugins will not load. The framed document can only navigate itself, not its top-level parent. Setting `window.top.location` will throw an exception, and clicking on link with `target="_top"` will have no effect. Features that trigger automatically (autofocused form elements, autoplaying videos, etc.) are blocked. Pointer lock cannot be obtained. The `seamless` attribute is ignored on `iframes` the framed document contains. This is nicely draconian, and a document loaded into a fully sandboxed `iframe` poses very little risk indeed. Of course, it also can't do much of value: you might be able to get away with a full sandbox for some static content, but most of the time you'll want to loosen things up a bit. With the exception of plugins, each of these restrictions can be lifted by adding a flag to the sandbox attribute's value. Sandboxed documents can never run plugins, as plugins are unsandboxed native code, but everything else is fair game: **`allow-forms`** allows form submission. **`allow-popups`** allows (shock!) popups. **`allow-pointer-lock`** allows (surprise!) pointer lock. **`allow-same-origin`** allows the document to maintain its origin; pages loaded from `https://example.com/` will retain access to that origin's data. **`allow-scripts`** allows JavaScript execution, and also allows features to trigger automatically (as they'd be trivial to implement via JavaScript). **`allow-top-navigation`** allows the document to break out of the frame by navigating the top-level window. With these in mind, we can evaluate exactly why we ended up with the specific set of sandboxing flags in the Twitter example above: **`allow-scripts`** is required, as the page loaded into the frame runs some JavaScript to deal with user interaction. **`allow-popups`** is required, as the button pops up a tweeting form in a new window. **`allow-forms`** is required, as the tweeting form should be submittable. **`allow-same-origin`** is necessary, as twitter.com's cookies would otherwise be inaccessible, and the user couldn't log in to post the form. One important thing to note is that the sandboxing flags applied to a frame also apply to any windows or frames created in the sandbox. This means that we have to add **`allow-forms`** to the frame's sandbox, even though the form only exists in the window that the frame pops up. With the `sandbox` attribute in place, the widget gets only the permissions it requires, and capabilities like plugins, top navigation, and pointer lock remain blocked. We've reduced the risk of embedding the widget, with no ill-effects. It's a win for everyone concerned. Privilege Separation Sandboxing third-party content in order to run their untrusted code in a low-privilege environment is fairly obviously beneficial. But what about your own code? You trust yourself, right? So why worry about sandboxing? I'd turn that question around: if your code doesn't need plugins, why give it access to plugins? At best, it's a privilege you never use, at worst it's a potential vector for attackers to get a foot in the door. Everyone's code has bugs, and practically every application is vulnerable to exploitation in one way or another. Sandboxing your own code means that even if an attacker successfully subverts your application, they won't be given *full* access to the application's origin; they'll only be able to do things the application could do. Still bad, but not as bad as it could be. You can reduce the risk even further by breaking your application up into logical pieces and sandboxing each piece with the minimal privilege possible. This technique is very common in native code: Chrome, for example, breaks itself into a high-privilege browser process that has access to the local hard-drive and can make network connections, and many low-privilege renderer processes that do the heavy lifting of parsing untrusted content. Renderers don't need to touch the disk, the browser takes care of giving them all the information they need to render a page. Even if a clever hacker finds a way to corrupt a renderer, she hasn't gotten very far, as the renderer can't do much of interest on its own: all high-privilege access must be routed through the browser's process. Attackers will need to find several holes in different pieces of the system order to do any damage, which hugely reduces the risk of successful pwnage. Safely sandboxing `eval()` With sandboxing and the [`postMessage` API](https://developer.mozilla.org/docs/DOM/window.postMessage), the success of this model is fairly straightforward to apply to the web. Pieces of your application can live in sandboxed `iframe`s, and the parent document can broker communication between them by posting messages and listening for responses. This sort of structure ensures that exploits in any one piece of the app do the minimum damage possible. It also has the advantage of forcing you to create clear integration points, so you know exactly where you need to be careful about validating input and output. Let's walk through a toy example, just to see how that might work. [Evalbox](/static/demos/evalbox) is an exciting application that takes a string, and evaluates it as JavaScript. Wow, right? Just what you've been waiting for all these long years. It's a fairly dangerous application, of course, as allowing arbitrary JavaScript to execute means that any and all data an origin has to offer is up for grabs. We'll mitigate the risk of Bad Things⢠happening by ensuring that the code is executed inside of a sandbox, which makes it quite a bit safer. We'll work our way through the code from the inside out, starting with the frame's contents: `