我认为不信任任何输入是网络上众所周知的最佳实践.判决

"All input is evil."

可能是输入验证方面引用最多的引用.现在,对于HTML,您可以使用诸如DOMPurify之类的工具对其进行清理.

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

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?

Am I missing something?

推荐答案

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

  1. Apply exception handlers in the appropriate place as JSON.parse() can throw an exception.
  2. 不要假设那里有什么数据,在使用之前必须明确测试数据.
  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. 不要将这些传入的数据放在可以对其进行进一步判断的地方,例如直接放在页面的HTML中,或直接注入SQL语句中,而无需进一步消毒以确保其在该环境中是安全的.

因此,要直接回答您的问题,除了使用正文解析器之外,还有更多的事情要做,尽管它是第一次处理数据的非常好的前线.从正文解析器获得数据后,接下来的处理步骤在很多情况下都很重要,可能需要格外小心.


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;
    }
}

Json相关问答推荐

为什么JQ筛选器不将原始输入打印为$var|.';文档?

如何在Haskell中解析JSON,其中字段的名称可以是多个值之一,但应该转换为单个Haskell类型?

无法从JSON解析ZonedDateTime,但可以使用格式化程序很好地解析

有没有办法让serde_json正确/不正确地处理NaN、inf和-inf(IEEE 754特殊标准)?

来自json的可分析的构建报告

递归解码嵌套列表(具有任意深度的列表列表)

Jolt 转换数组对象并将某些字段移动到嵌套数组

如何在 JSonPath 中按值查找列表中的所有元素

如何使用 jq 在连续的 json 记录流上调用操作

在 CodePipeline 中调用 lambda 时传递用户参数

使用 jq 和 awk 拆分大型 JSON 文件

通过sql查询读取嵌套Json

如何将从嵌套 Select 返回的空值转换为空数组?

Servicestack 返回数组而不是带有数组的对象

TypeError: b'1' 不是 JSON 可序列化的

POST:在 url 本身中发送 post 请求

在 .NET 中缩小缩进的 JSON 字符串

有没有一种快速的方法可以在文本编辑器中将 JavaScript 对象转换为有效的 JSON?

类型是接口或抽象类,不能实例化

将 Pandas 数据框转换为嵌套 JSON