javascript 是否需要清理 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25983090/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:20:50  来源:igfitidea点击:

Is sanitizing JSON necessary?

javascriptnode.jsjsonsanitizationdompurify

提问by Golo Roden

I think it's a well-known best practice on the web to mistrust any input. The sentence

我认为不信任任何输入是网络上众所周知的最佳实践。这句话

"All input is evil."

“所有的输入都是邪恶的。”

is probably the most cited quote with respect to input validation. Now, for HTML you can use tools such as DOMPurifyto sanitize it.

可能是有关输入验证的引用最多的引用。现在,对于 HTML,您可以使用DOMPurify等工具对其进行清理。

My question is if I have a Node.js server running Express and body-parsermiddleware to receive and parse JSON, do I need to run any sanitizing as well?

我的问题是,如果我有一个 Node.js 服务器运行 Express 和body-parser中间件来接收和解析 JSON,我是否还需要运行任何清理?

My (maybe naive?) thoughts on this are that JSON is only data, no code, and if somebody sends invalid JSON, body-parser (which uses JSON.parse()internally) will fail anyway, so I know that my app will receive a valid JavaScript object. As long as I don't run eval on that or call a function, I should be fine, shouldn't I?

我(可能是天真的?)对此的想法是 JSON 只是数据,没有代码,如果有人发送无效的 JSON,body-parser(JSON.parse()内部使用)无论如何都会失败,所以我知道我的应用程序将收到一个有效的 JavaScript 对象. 只要我不对其运行 eval 或调用函数,我应该没问题,不是吗?

Am I missing something?

我错过了什么吗?

采纳答案by jfriend00

Since JSON.parse()does not run any code in the data to be parsed, it is not vulnerable the way eval()is, but there are still things you should do to protect the integrity of your server and application such as:

由于JSON.parse()不会在要解析的数据中运行任何代码,因此它并不容易受到攻击eval(),但是您仍然应该采取一些措施来保护服务器和应用程序的完整性,例如:

  1. Apply exception handlers in the appropriate place as JSON.parse()can throw an exception.
  2. Don't make assumptions about what data is there, you must explicitly test for data before using it.
  3. Only process properties you are specifically looking for (avoiding other things that might be in the JSON).
  4. Validate all incoming data as legitimate, acceptable values.
  5. Sanitize the length of data (to prevent DOS issues with overly large data).
  6. Don't put this incoming data into places where it could be further evaluated such as directly into the HTML of the page or injected directly into SQL statements without further sanitization to make sure it is safe for that environment.
  1. 在适当的地方应用异常处理程序,因为它JSON.parse()可以抛出异常。
  2. 不要假设那里有什么数据,您必须在使用数据之前明确测试数据。
  3. 仅处理您专门查找的属性(避免 JSON 中可能存在的其他内容)。
  4. 将所有传入数据验证为合法、可接受的值。
  5. 清理数据长度(以防止因数据过大而导致 DOS 问题)。
  6. 不要将这些传入数据放在可以进一步评估的地方,例如直接放入页面的 HTML 中或直接注入 SQL 语句中,而无需进一步清理以确保它对该环境是安全的。

So, to answer your question directly, "yes" there is more to do than just using body-parser though it is a perfectly fine front line for first processing the data. The next steps for what you do with the data once you get it from body-parser do matter in many cases and can require extra care.

因此,要直接回答您的问题,“是的”除了使用 body-parser 之外还有更多工作要做,尽管它是首先处理数据的完美前线。从 body-parser 获取数据后,接下来对数据执行的操作在许多情况下都很重要,并且可能需要格外小心。



As an example, here's a parsing function that expects an object with properties that applies some of these checks and gives you a filtered result that only contains the properties you were expecting:

例如,这里有一个解析函数,它期望一个对象具有应用这些检查中的一些属性的属性,并为您提供仅包含您期望的属性的过滤结果:

// pass expected list of properties and optional maxLen
// returns obj or null
function safeJSONParse(str, propArray, maxLen) {
    var parsedObj, safeObj = {};
    try {
        if (maxLen && str.length > maxLen) {
            return null;
        } else {
            parsedObj = JSON.parse(str);
            if (typeof parsedObj !== "object" || Array.isArray(parsedObj)) {
                safeObj = parseObj;
            } else {
                // copy only expected properties to the safeObj
                propArray.forEach(function(prop) {
                    if (parsedObj.hasOwnProperty(prop)) {
                        safeObj[prop] = parseObj[prop];
                    }
                });
            }
            return safeObj;
        }
    } catch(e) {
        return null;
    }
}

回答by Chris Tavares

You should be fine. Early users of JSON would often call eval() on the received string, which is of course a huge security hole. But JSON.parse, as you state, handles the majority of these kinds of sanity checks.

你应该没事。JSON 的早期用户经常会在收到的字符串上调用 eval(),这当然是一个巨大的安全漏洞。但是,正如您所说,JSON.parse 处理大多数这些类型的健全性检查。

As long as you make sure not to take something out of a received JSON object and pass it directly into a sql query, for example, you should be fine.

例如,只要您确保不从接收到的 JSON 对象中取出某些内容并将其直接传递到 sql 查询中,就应该没问题。