I\'d like to be able to allow community members to supply their own javascript code for others to use, because the users\' imaginations are collectively far greater than any
Since HTML5 has now become available you can use a sandbox for untrusted JavaScript code.
The OWASP HTML5 Security Cheat Sheet comments on Sandboxed frames:
- Use the sandbox attribute of an iframe for untrusted content.
The sandbox attribute of an iframe enables restrictions on content within a
iframe. The following restrictions are active when the sandbox attribute is set:
All markup is treated as being from a unique origin.
All forms and scripts are disabled.
- All links are prevented from targeting other browsing contexts.
- All features that triggers automatically are blocked.
All plugins are disabled.
It is possible to have a fine-grained control over
iframecapabilities using the value of thesandboxattribute.In old versions of user agents where this feature is not supported, this attribute will be ignored. Use this feature as an additional layer of protection or check if the browser supports sandboxed frames and only show the untrusted content if supported.
Apart from this attribute, to prevent Clickjacking attacks and unsolicited framing it is encouraged to use the header
X-Frame-Optionswhich supports thedenyandsame-originvalues. Other solutions like framebustingif(window!== window.top) { window.top.location = location; }are not recommended.
You can allow scripts to run while keeping the other restrictions in place. However, you should make sure that scripts run from a different domain than your main content in order to prevent XSS attacks by an attacker redirecting a user to load the page directly (i.e. not via your IFrame).
This will restrict scripts from using eval to attack your main domain, but it may be that this would also prevent the scripts from actually being powerful enough for your needs. Any interaction with your main domain would have to be via Window.postMessage. If this is too restrictive then @bobince's answer still has the best suggestions for workarounds.
Please see my other answer for details of how a sandbox can be safely implemented.