What is the best (most secure) way to restrict which websites can iframe embed by web application?
For example, everyone should be denied who is not on the list:
As a follow up question, given any restrictions for the above, what is the most secure way to find out server side which one of the white-listed sites is doing the embedding?
This is well-supported by modern browsers.
Add a Content Security Policy with a frame-ancestors
directive
Content-Security-Policy: frame-ancestors 'self' https://www.example.org;
You must use the HTTP version of CSP here. frame-ancestors
is not supported in the <meta>
tag version.
This has better browser support because it has been around longer, but the differences aren't really significant these days. People aren't going to bother framing your site if the only browser that can see it is Internet Explorer.
Use the X-Frame-Options
HTTP header.
X-Frame-Options ALLOW-FROM http://example.com/
See also the MSDN documentation which has this advice:
Note that the Allow-From token does not support wildcards or listing of multiple origins. For cases where the server wishes to allow more than one page to frame its content, the following design pattern is recommended:
- The outer IFRAME supplies its own origin information, using a querystring parameter on the Inner IFRAME's src attribute. This can obviously be specified by an attacker, but that's OK.
- The server for the Inner IFRAME verifies the supplied Origin information meets whatever criteria business practices call for. For example, the server that serves the IFRAME containing a social network's "Like" button, might check to see that the supplied Origin matches the Origin expected for that Like button, and that the owner of the specified Origin has a valid affiliate relationship, etc.
- If satisfied with the information supplied, the server for the Inner IFRAME sends an X-FRAME-OPTIONS: allow-from suppliedorigin header
- The Browser then enforces the X-FRAME-OPTIONS directive.