How can I make external code 'safe' to run? Just ban eval()?

前端 未结 6 1027
情书的邮戳
情书的邮戳 2020-12-30 14:40

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

6条回答
  •  温柔的废话
    2020-12-30 14:57

    Or are there other ways to evaluate code

    You can't filter out calls to eval() at a script-parsing level because JavaScript is a Turing-complete language in which it is possible to obfuscate calls. eg. see svinto's workaround. You could hide window.eval by overwriting it with a null value, but there are indeed other ways to evaluate code, including (just off the top of my head):

    • new Function('code')()
    • document.write('%3Cscript>code%3C/script>')
    • document.createElement('script').appendChild(document.createTextNode('code'))
    • window.setTimeout('code', 0);
    • window.open(...).eval('code')
    • location.href='javascript:code'
    • in IE, style/node.setExpression('someproperty', 'code')
    • in some browsers, node.onsomeevent= 'code';
    • in older browsers, Object.prototype.eval('code')

    or cause mass panic in javascript?

    Well createElement('iframe').src='http​://evil.iframeexploitz.ru/aff=2345' is one of the worse attacks you can expect... but really, when a script has control, it can do anything a user can on your site. It can make them post “I'm a big old paedophile!” a thousand times on your forums and then delete their own account. For example.

    do I have to resort to demanding the author supplies a web service interface?

    Yes, or:

    • do nothing and let users who want this functionality download GreaseMonkey
    • vet every script submission yourself
    • use your own (potentially JavaScript-like) mini-language over which you actually have control

    an example of the latter that may interest you is Google Caja. I'm not entirely sure I'd trust it; it's a hard job and they've certainly had some security holes so far, but it's about the best there is if you really must take this approach.

提交回复
热议问题