Search code examples
javascriptiframexmlhttprequestsandbox

How can I limit what domains a sandboxed iframe can connect to?


I'm creating something like an app ecosystem where each app runs in a sandboxed iframe and processes sensitive data. I want to allow scripts, but I don't want the iframe to communicate with any 3rd party server or it might leak this data.

Is there a way to enforce a whitelist like you can with Chrome extensions? Am I going about this the wrong way?


Solution

  • You will want to limit what domains can be connected to for all things, not just XHR (an img tag can leak data just as well). Modern browsers offer a feature to do this called Content Security Policy.

    In particular, to whitelist domains, you will want to return a header like the following:

    Content-Security-Policy: default-src 'self' safedomain.com securedomain.com
    

    Like anything security related, make sure you read up on the topic and understand the implications of what you are dealing with. Copy-pasting code from a Stack Overflow answer is not enough.

    Also remember that some older browsers do not support this feature and will silently not enforce it, so you will probably want to detect this and prevent those browsers from exposing sensitive data.