javascriptiframecookies

Recommended method to prevent any content inside iframe from setting cookies


I get the content to be put inside an iframe from a source I do not trust. For a particular need to be met, I want the content (which might include javascript) to be unable to set cookies at all. What is the recommended method to achieve that?

Edit: I recognize this is similar to this question. I should have mentioned this earlier, but the iframe has a cross-origin source. I want to disable the content inside from setting cookies even on its own source. Does sandboxing achieve that? Thanks.


Solution

  • The short answer:

    The HTML5 sandbox attribute prevents an iframe from reading/writing cookies. This is true for both same-origin and cross-origin iframes.

    The allow-scripts attribute enables JavaScript but does not interfere with restrictions on cookies.

    <iframe sandbox="allow-scripts" src="..."></iframe>
    


    The long answer:

    So if you're not fully convinced, this one is for you...

    According to the W3C Working Draft (2010) and W3C Recommendation (2014), when the user agent (browser) parses the sandbox attribute, it has to add certain flags, which are then used to put restrictions on the content within the iframe. One of those flags are meant to force the content into a unique origin, and prevent it from reading/writing cookies:

    The sandbox attribute, when specified, enables a set of extra restrictions on any content hosted by the iframe.

    While the sandbox attribute is specified, the iframe element's nested browsing context must have the flags given in the following list set.

    ...

    ...

    The sandboxed origin browsing context flag, unless the sandbox attribute's value, when split on spaces, is found to have the allow-same-origin keyword set

    This flag forces content into a unique origin, thus preventing it from accessing other content from the same origin.

    This flag also prevents script from reading from or writing to the document.cookie IDL attribute, and blocks access to localStorage. [WEBSTORAGE]

    When a sandboxed iframe attempts to write a cookie, the following exception is raised:

    Uncaught DOMException: Failed to set the 'cookie' property on 'Document': The document is sandboxed and lacks the 'allow-same-origin' flag.

    and no cookie is ever written.

    Since the sandboxed iframe cannot write cookies at all, it will not be able to set cookies even on its originating site. (In fact, this would be one of the use-cases for using the allow-same-origin keyword).

    The allow-same-origin attribute is intended for two cases.

    ...

    Second, it can be used to embed content from a third-party site, sandboxed to prevent that site from opening popup windows, etc, without preventing the embedded page from communicating back to its originating site, using the database APIs to store data, etc.