node.js - 防止 NoSQL 注入(inject) : Isn't mongoose supposed to convert inputs based on given schema?

标签 node.js mongodb mongoose

希望使用 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/

相关文章:

node.js - 使用 forever 在 Ubuntu 上运行 node.js 服务器

node.js - MongoDB:动态计数

node.js - 为什么 Mongoose 连接在单独的模块中挂起?

javascript - 如何使用 $in 查询 mongodb 中 id 存储在 `var ids` 数组中的文档?

javascript - 如何使用mongo shell加载多个js文件到数据库?

node.js - Mongoose 查询改变对象顺序

node.js - ES7 - 如何用 await 替换 Promise?

node.js - 无法使用 Node.js 登录 Vtiger api

url - Socket.io 在 URL 中调用 http ://undefined/. ...

html - 如何使用带有标准 HTML 而不是 Jade 的 Piler?