Over time, we have gotten used to integrate more and more content on our web pages. Sometimes these content come from third parties (social networks widgets, advertising, etc). It implies two consequences: the webpages size continues to rise, and we display to the users some content that we can’t fully control.
Some of these external content are integrated via the <iframe> tag, and you should pay special attention to these elements for your website’s security. To limit the risks, the W3C added the sandbox attribute in the HTML5 specifications, allowing to restrict the actions available from an iframe (supported by major recent browsers).
In terms of security, a best practice when you manipulate elements that you don’t control, is to “compartmentalize” the environment of these elements: only authorize what is strictly necessary, to limit the potential impacts.
So, the sandbox attribute has been created to limit the action available from an iframe within your page.
Once you specify this attribute on a iframe:
<iframe sandbox src=”...”></iframe>
the following restrictions apply:
- AJAX requests can’t be initiated (the iframe has its own “origin”, different from your page, and thus violated the standard CORS mechanism respected by default by modern browsers)
- You limit the storage capabilities on the browser (eg: using cookies or localStorage is impossible)
- It’s impossible to create a new window, a popup
- Sending a form is prohibited
- Flash, Silverlight plugins, or Java applets are not loaded
- The Pointer Lock API (that provides information related to mouse movements) is blocked
Remove some restrictions
The sandbox attribute accepts multiple values that will allow you to relax the default policy as needed:
- allow-forms: form submission is allowed
- allow-scripts: scripts are executed
- allow-same-origin: the iframe uses the same “origin” that the page, so it no longer faces to CORS mechanism restrictions (permission to use AJAX requests, localStorage, cookies…)
- allow-top-navigation: the iframe can navigate to its top-level browsing context
- allow-popups: you can open a new window/a popup
- allow-pointer-lock: the Pointer Lock API is operable
Note that you can’t reauthorize plugins execution.
For example, if your iframe needs to open a popup to a third service, and requires authentication to access this service, you’ll have to add these values:
- allow-forms (the restriction applies to the iframe, but also to elements resulting)
<iframe sandbox=”allow-same-origin allow-forms allow-popups” src=”...”></iframe>
Note that it’s not advisable to add both values allow-scripts and allow-same-origin: these two values will allow the iframe to access and modify your DOM. In this case, a malicious iframe could perform all sorts of operations, and could even remove its own sandbox attribute!