gpt4 book ai didi

javascript - 在使用 JSON.parse 之前应该如何清理不受信任的 JSON?

转载 作者:行者123 更新时间:2023-12-05 00:36:43 26 4
gpt4 key购买 nike

给定一个用户提供的 JSON 字符串,我们如何在运行 JSON.parse(untrustedString) 之前对其进行清理?
我主要关心的是原型(prototype)污染,但我也想知道我还应该注意什么?如果只是原型(prototype)污染有风险,那么我认为可以通过正则表达式处理,但我怀疑还有其他问题?
例如,this article on the dangers of parsing untrusted JSON and then creating a copy of the object. :

Now consider some malicious JSON data sent to this endpoint.

{
"user": {
"__proto__": {
"admin": true
}
}
}

If this JSON is sent, JSON.parse will produce an object with a__proto__ property. If the copying library works as described above,it will copy the admin property onto the prototype ofreq.session.user!

最佳答案

My primary concern is about prototype pollution


请注意 JSON.parse不会污染任何原型(prototype)对象。如果 JSON 字符串有 "__proto__"键,那么该键将像任何其他键一样被创建,并且无论该 JSON 中的对应值是什么,它将最终作为该属性值,而不是原型(prototype)对象 ( Object.prototype)。
风险在于您之后对该对象的处理方式。如果您执行(深度)复制,带有属性分配或 Object.assign ,那么您可能会改变原型(prototype)对象。

how can we sanitize it before running JSON.parse(untrustedString)? ... I assume that could be handled via regex


不要为此使用正则表达式。使用 JSON.parse 的第二个参数:

const cleaner = (key, value) => key === "__proto__" ? undefined : value;

// demo
let json = '{"user":{"__proto__":{"admin": true}}}';

console.log(JSON.parse(json));
console.log(JSON.parse(json, cleaner));

关于javascript - 在使用 JSON.parse 之前应该如何清理不受信任的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63926663/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com