希望使用 mongodb 防止对 node.js 应用程序的 NoSQL 注入(inject)攻击。
var mongoose = require('mongoose'); // "^5.5.9"
var Schema = mongoose.Schema;
var historySchema = new Schema({
userId: {
type: String,
index: true,
},
message: {},
date: {
type: Date,
default: Date.now,
}
});
var history = mongoose.model('history', historySchema);
// the following is to illustrate the logic, not actual code
function getHistory(user){
history.find({userId: user}, function(err, docs) {
console.log(docs)
}
}
基于 this answer to a similar question ,我的理解是使用 Mongoose 并将字段定义为字符串应该可以防止查询注入(inject)。但是,通过将 user
输入更改为查询对象,可以返回所有用户。例如:
getHistory({$ne: 1}) // returns the history for all users
我知道在它到达 Mongoose 查询之前防止这种类型的攻击的其他方法,比如使用 mongo-sanitize .但是我想知道我定义模式的方式是否有问题,或者是否不能期望 Mongoose 根据模式转换输入。
提前致谢!
最佳答案
这部分已经足够好了,你不需要其他任何东西。有接收字符串并使用该字符串的方法。
最好的方法是在处理任何事情之前在顶层验证可以修改的输入(通常是 HTTP 请求)(我可以推荐 https://github.com/hapijs/joi 它易于使用,您可以检查是否有所有必填字段以及是否所有字段格式正确)。
因此,在它到达您的 Controller 之前将验证放入中间件。或者在你的 Controller 的开头。
从那时起,您就可以完全控制所有代码,并且相信自己通过验证得到的结果,因此不会发生有人传递对象而不是字符串并通过验证的情况。
关于node.js - 防止 NoSQL 注入(inject) : Isn't mongoose supposed to convert inputs based on given schema?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56187802/