简体   繁体   English

JSON.parse 的 Node.js 实现

[英]Node.js Implementation of JSON.parse

I need to get javascript object from untrusted json.我需要从不受信任的 json 中获取 javascript 对象。

Initially it comes as string and there are two ways of doing the task: eval() and JSON.parse() .最初它以字符串形式出现,有两种方法可以完成任务: eval()JSON.parse()

Where I can see Node.js implementation of JSON.parse , because I'm afraid that it uses eval under the hood and there can be security gaps.我在哪里可以看到JSON.parse Node.js 实现,因为我担心它在JSON.parse使用 eval 并且可能存在安全漏洞。

I was trying to check v8 repo and even tried Function.prototype.toSource() in Firefox - no result.我试图检查v8库,甚至在 Firefox 中尝试过Function.prototype.toSource() - 没有结果。

Can anybody provide me with some proofs that I shouldn't worry to use it ?任何人都可以向我提供一些我不应该担心使用它的证据吗?

V8 developer here. V8 开发人员在这里。 JSON.parse does not use eval under the hood -- that's precisely the point of having JSON.parse , and why it's strongly recommended to use that (rather than eval ) for parsing JSON data. JSON.parse并没有在JSON.parse使用eval —— 这正是拥有JSON.parse ,以及为什么强烈建议使用它(而不是eval )来解析 JSON 数据。

As feeela already pointed out, if you want to verify this yourself, look at the source: https://github.com/v8/v8/blob/master/src/json-parser.cc正如feeela已经指出的那样,如果你想自己验证这一点,请查看源: https : //github.com/v8/v8/blob/master/src/json-parser.cc

Or run an experiment:或者运行一个实验:

var bad_json_data = 'console.log("executed!"); "{foo:1}"';
var o1 = eval(bad_json_data);  // Prints to console.
var o2 = JSON.parse(bad_json_data);  // SyntaxError!

That said, you always have to be careful with untrusted input.也就是说,您必须始终小心不受信任的输入。 Using JSON.parse to convert the JSON string to an object is safe, but afterwards you still have to be careful what you're using that object for (as one random example, its property values could still allow SQL injection attacks if you try to store them in a database).使用JSON.parse将 JSON 字符串转换为对象是安全的,但之后您仍然必须小心使用该对象的目的(作为一个随机示例,如果您尝试,其属性值仍然可能允许 SQL 注入攻击)将它们存储在数据库中)。

You cannot parse Functions/Classes as JSON.您不能将函数/类解析为 JSON。 And if there are functions they would be represented as strings.如果有函数,它们将被表示为字符串。 You can check that if u try:如果您尝试,您可以检查:

 const obj = { a: () => console.log("test") } console.log(JSON.stringify(obj)) // prints {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM