在服务器发送的 JavaScript 代码上安全使用 eval()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10489874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Safe usage of eval() on server-sent JavaScript code
提问by Hyman
I'm using Node.js and Socket.io. I've written an application which can send JavaScript snippets from the server and execute them on the client. The JavaScript is sent via Secure WebSocket (WSS), and the client has a listener which will execute any code passed to it via the server.
我正在使用 Node.js 和 Socket.io。我编写了一个应用程序,它可以从服务器发送 JavaScript 片段并在客户端上执行它们。JavaScript 通过 Secure WebSocket (WSS) 发送,客户端有一个侦听器,它将执行通过服务器传递给它的任何代码。
This short script demonstrates the principle: http://jsfiddle.net/KMURe/and you can think of the onScript function as the socket listener.
这个简短的脚本演示了原理:http: //jsfiddle.net/KMURe/,您可以将 onScript 函数视为套接字侦听器。
Question
问题
What security protocols can I put in place to make this transaction safe? Would a secure websocket channel make it difficult for a third party to act as a middle man (altering the code before it's sent to the client)?
我可以采用哪些安全协议来确保此交易安全?安全的 websocket 通道是否会使第三方难以充当中间人(在将代码发送给客户端之前更改代码)?
Some Use Cases..
一些用例..
- Dynamically assigned distributed computation.
- Browser client can dynamically learn from the server.
- Update browser behavior in unison.
- 动态分配的分布式计算。
- 浏览器客户端可以动态地向服务器学习。
- 统一更新浏览器行为。
采纳答案by Joseph
eval()
, even if you have legit use, is just dangerous. You should avoid using it at all costs.use it with care.
eval()
,即使您有合法用途,也是危险的。你应该不惜一切代价避免使用它。小心使用它。
However, if it's really needed, then you can use strict mode via "use strict"
command. When eval()
is executed in a strict function, the eval's content will not leak in the immediate scope. The code in an eval will be contained in eval()
itself (as if it has it's own scope). In the demo, try removing the trailing x
and eval()
will return undefined
.
但是,如果确实需要,则可以通过"use strict"
command使用严格模式。当 eval()
在一个严格的函数执行中,eval的内容将不会在不久的范围泄露。eval 中的代码将包含在eval()
其自身中(就好像它有自己的范围一样)。在演示中,尝试删除尾部x
和eval()
返回undefined
。
But still, using eval()
is dangerous. It's better if you find alternatives like JSON with custom string commands that will be parsed client-side.
但是,使用仍然eval()
是危险的。如果您找到诸如 JSON 之类的替代品,其中包含将在客户端解析的自定义字符串命令,那就更好了。