NoSQL 注入检测 —— 原理、示例与自动化检测
MongoDB 这类数据库的查询是文档而不是字符串,所以传统 SQL 注入的防护手段不适用。只要把请求里的 JSON 对象原样丢进查询条件,攻击者就能用 $ne、$gt、$regex 这类操作符绕过登录校验。
漏洞危害
- 用 $ne 运算符绕过账号密码校验,直接登录任意账户
- 用 $regex 逐位爆破口令与 token
- 拖走整张集合的数据
代码示例(JavaScript)
❌ 危险写法
// 危险写法:整个请求体丢进查询条件
app.post('/login', async (req, res) => {
const user = await db.collection('users').findOne({
username: req.body.username,
password: req.body.password,
});
// 提交 {"username":"admin","password":{"$ne":null}} 即可登录成功
});
✅ 安全写法
// 安全写法:白名单取值 + 强制类型
app.post('/login', async (req, res) => {
const username = String(req.body.username || '');
const password = String(req.body.password || '');
if (!username || !password) return res.status(400).end();
const user = await db.collection('users').findOne({ username });
const ok = user && await bcrypt.compare(password, user.pwdHash);
if (!ok) return res.status(401).end();
});
煋鉴如何检测
- req.body / req.query 整体作为查询文档传入 find / findOne / update
- 没有把参数强制转成字符串,对象型参数可以带操作符
- MongoDB 查询里拼 $where 字符串(等价于服务端执行 JS)