NoSQL Security Cheat Sheet / NoSQL 安全速查表¶
Introduction / 介绍¶
NoSQL databases (MongoDB, CouchDB, Cassandra etc.) power many modern applications with flexible schemas and horizontal scale. This cheat sheet summarizes guidance to reduce risk when using NoSQL systems.
NoSQL 数据库(MongoDB、CouchDB、Cassandra 等)凭借灵活的模式和横向扩展能力,为许多现代应用程序提供动力。此速查表总结了在使用 NoSQL 系统时降低风险的建议。
Threats & Common Failure Modes / 威胁与常见故障模式¶
- NoSQL Injection — Unsafe construction of query objects or query strings from untrusted input.
中文:NoSQL 注入 — 从不受信任的输入中不安全地构建查询对象或查询字符串。 - Exposed Management Interfaces — Admin GUIs, database ports or REST endpoints exposed to the internet.
中文:暴露的管理接口 — 向互联网暴露的行政 GUI、数据库端口或 REST 端点。 - Weak/No Authentication & Authorization — Default open access or excessive privileges for clients.
中文:弱/无认证与授权 — 默认开放访问或客户端过度的权限。 - Insecure Network Exposure — No TLS, open ports, insufficient network segmentation.
中文:不安全的网络暴露 — 无 TLS、开放端口、网络分段不足。 - Insecure Defaults — Default admin accounts, default passwords, unsecured configs.
中文:不安全的默认设置 — 默认管理员账户、默认密码、未加密的配置。 - Poor Access Control Models — Coarse roles allowing lateral abuse.
中文:较差的访问控制模型 — 粗粒度角色允许横向滥用。 - Insecure Serialization / Deserialization — Remote code execution via unsafe object deserialization.
中文:不安全的序列化/反序列化 — 通过不安全对象反序列化执行远程代码。 - Misconfigured CORS / Public APIs — APIs accidentally allow cross-origin requests or wide access.
中文:配置错误的 CORS / 公共 API — API 无意中允许跨源请求或广泛访问。 - Credential & Secret Leaks — Hardcoded DB credentials in code, images, CI logs.
中文:凭证与秘密泄露 — 代码、图像、CI 日志中硬编码的数据库凭证。 - Unsafe Backup Exposure — Backups left unencrypted or publicly accessible.
中文:不安全的备份暴露 — 备份未加密或公开可访问。 - Supply-chain / Dependency Risks — Vulnerable drivers, ORMs/ODMs, or plugins.
中文:供应链/依赖风险 — 易受攻击的驱动程序、ORM/ODM 或插件。
Secure-by-Design Principles / 安全设计原则¶
- Treat all input as untrusted — validate, sanitize, and normalize.
中文:将所有输入视为不可信 — 验证、清理和标准化。 - Use least privilege — narrow roles for users, services, and operators.
中文:使用最小权限 — 窄化用户、服务和操作员的角色。 - Defense in depth — combine network controls, auth, input validation, and monitoring.
中文:多层次防御 — 结合网络控制、身份验证、输入验证和监控。 - Secure defaults — change default ports/accounts, enable auth and TLS by default.
中文:安全默认设置 — 更改默认端口/账户,默认启用身份验证和 TLS。 - Automate secrets & rotation — vaults and short-lived credentials.
中文:自动化秘密和轮换 — 保险库和短期凭证。 - Monitor & audit — log access and detect anomalies.
中文:监控与审计 — 记录访问并检测异常。
Practical Defenses & Examples / 实用防御与示例¶
Prevent NoSQL Injection / 预防NoSQL注入¶
Unsafe (string-based filter building — Node.js / MongoDB):
不安全(基于字符串的过滤器构建 — Node.js / MongoDB):
// DANGEROUS: building query from untrusted input
const q = "{ name: '" + req.query.name + "' }";
const filter = eval("(" + q + ")"); // NEVER do this
db.collection('users').find(filter)
Safe (use driver query objects / parameterization):
安全(使用驱动查询对象 / 参数化):
Building a query object does not prevent operator injection when an untrusted value is itself an object. For example, MongoDB interprets { name: { $ne: "" } } as a not-equal query. Validate the expected scalar type before constructing the filter; do not pass client-supplied objects through as field values.
在不受信任的值本身是对象的情况下构建查询对象并不能防止操作符注入。例如,MongoDB将 { name: { $ne: "" } } 解释为 不等于查询。在构建过滤器之前验证预期的标量类型;不要将客户端提供的对象作为字段值传递。
const name = req.query.name;
if (typeof name !== 'string') throw new Error("Invalid name");
const filter = { name };
db.collection('users').find(filter)
Additional pattern rejection:
附加模式拒绝:
// Reject a pattern in the serialized request body.
if (JSON.stringify(req.body).includes('"$')) throw Error("Invalid input");
This JSON.stringify() check is a denylist, not an operator allowlist. It also rejects ordinary string values that begin with $, and it does not validate allowed fields or their types. Use field-specific validation before building queries.
此JSON.stringify()检查是一个黑名单,而不是操作符白名单。它还拒绝以$开头的普通字符串值,并且不验证允许的字段或其类型。在构建查询之前使用字段特定验证。
Notes:
注意:
- Do not accept raw JSON fragments from the client to execute as queries.
中文:切勿接受客户端提供的原始 JSON 片段以执行查询。 - Disallow client-controlled query operators (like
$where,$regex, or$expr) unless strictly required and validated.
中文:除非绝对必要且经过验证,否则禁止使用客户端控制的查询操作符(如$where、$regex或$expr)。 - For text-based search parameters, use safe driver APIs (e.g.,
$textwith controlled input).
中文:对于基于文本的搜索参数,请使用安全的驱动程序 API(例如,使用受控输入的$text)。
Use Secure Driver / ODM Patterns¶
- Prefer high-level APIs (ODM/ORM) that build queries safely (e.g., Mongoose, Spring Data, Datastax driver patterns).
中文:优先使用高级 API(ODM/ORM),这些 API 可以安全地构建查询(例如,Mongoose、Spring Data、Datastax 驱动程序模式)。 - Avoid
.eval()-like functionality and raw query execution from untrusted data.
中文:避免使用类似.eval()的功能以及从不受信任的数据中执行原始查询。 - Sanitize and validate any raw expressions before passing to the DB.
中文:在传递到数据库之前,对任何原始表达式进行清理和验证。
Example — PyMongo safe usage / 示例 — PyMongo 安全使用¶
from pymongo import MongoClient
client = MongoClient(uri, tls=True)
collection = client.mydb.users
if not isinstance(email_input, str):
raise ValueError("Invalid email")
user = collection.find_one({"email": email_input})
Example in Java / Java 示例¶
This example uses the Java driver's equality filter builder with a string value:
此示例使用 Java 驱动程序的 等值过滤器构建器 与字符串值:
MongoCollection<Document> collection = this.getCollection();
Bson expression = Filters.eq("borough", userInput);
FindIterable<Document> restaurants = collection.find(expression);
Authentication & Authorization / 身份验证与授权¶
- Enable authentication (do not run databases unauthenticated).
中文:启用身份验证(不要在不进行身份验证的情况下运行数据库)。 - Use role-based access control (RBAC), least privilege for service accounts.
中文:使用基于角色的访问控制(RBAC),为服务账户提供最小权限。 - Use separate users for admin/backup/readonly/application.
中文:使用 独立的用户 进行管理员/备份/只读/应用程序操作。 - Use identity federation or short-lived credentials when supported (e.g., AWS IAM -> DynamoDB).
中文:当支持时,使用身份联合或短期凭证(例如,AWS IAM -> DynamoDB)。
For more information please check following cheat sheets:
有关更多信息,请查看以下速查表:
Authentication Cheat Sheet) (身份验证备忘单)
Authorization Cheat Sheet) (授权速查表)
Network & Transport Security / 网络与传输安全¶
- Bind services to internal interfaces, not
0.0.0.0.
中文:将服务绑定到内部接口,而不是0.0.0.0。 - Use network segmentation / private subnets and security groups.
中文:使用 网络分段/私有子网 和安全组。 - Enforce TLS (in transit encryption) for driver connections and admin consoles.
中文:强制执行TLS(传输中加密)以用于驱动器连接和管理控制台。 - Turn off remote management or restrict it to admin networks/VPNs.
中文:关闭远程管理或将其限制在管理员网络/VPN 中。
Configuration Hardening / 配置加固¶
- Change default ports and disable sample/demo users.
中文:更改默认端口并禁用示例/演示用户。 - Turn off or restrict features that execute code on the server, such as MongoDB server-side JavaScript.
中文:关闭或限制在服务器上执行代码的功能,例如 MongoDB 服务器端 JavaScript。 - Require TLS for internal replication links where supported.
中文:在支持的情况下,要求内部复制链接使用TLS。
Secrets Management / 秘密管理¶
- Do not hardcode DB credentials — use a secret manager (Vault, AWS Secrets Manager, Azure Key Vault).
中文:不要将数据库凭据硬编码 — 使用密钥管理器(Vault、AWS Secrets Manager、Azure Key Vault)。 - Avoid baking credentials into container images or environment variables in CI logs.
中文:避免将凭据嵌入到容器镜像或CI日志中的环境变量中。 - Rotate credentials regularly and use ephemeral tokens when possible.
中文:定期轮换凭据,并在可能的情况下使用临时令牌。
Logging, Monitoring & Auditing / 日志记录、监控与审计¶
- Enable audit logging (connection attempts, admin actions, failed auth).
中文:启用审计日志(连接尝试、管理员操作、失败的认证)。 - Send logs to a tamper-evident SIEM.
中文:将日志发送到防篡改的SIEM系统。 - Alert on anomalous patterns (spike in queries, slow queries, large data exports).
中文:检测异常模式警报(查询激增、慢查询、大量数据导出) - Monitor for suspicious commands (e.g., admin actions,
$where, map-reduce jobs).
中文:监控可疑命令(例如,管理员操作、$where、map-reduce作业)
Backups & Snapshots / 备份与快照¶
- Encrypt backups at rest and during transfer.
中文:在静态存储和传输过程中加密备份 - Restrict access to backup storage.
中文:限制对备份存储的访问 - Sanitize backups for PII as required by policy.
中文:根据政策要求对包含个人身份信息的备份进行清理 - Validate restore procedures regularly.
中文:定期验证恢复程序
Quick NoSQL Security Checklist / 快速NoSQL安全检查清单¶
- Enable authentication & RBAC
中文:启用身份验证和基于角色的访问控制 - Enforce TLS for client and node communication
中文:强制客户端和节点通信使用TLS - Bind DB to internal IPs / use private networks
中文:将数据库绑定到内部 IP 地址/使用私有网络 - Use least privilege service accounts
中文:使用最小权限服务帐户 - Disallow client-controlled query operators unless validated
中文:除非验证,否则不允许客户端控制的查询操作 - Avoid raw query execution / eval on server
中文:避免在服务器上执行原始查询/eval - Store credentials in secret manager & rotate them
中文:在密钥管理器中存储凭据并定期轮换 - Harden configs (disable unsafe defaults)
中文:强化配置(禁用不安全默认设置) - Encrypt and secure backups
中文:加密并保护备份 - Monitor/audit DB access and admin actions
中文:监控/审计数据库访问和管理操作 - Keep DB and drivers patched
中文:保持数据库和驱动程序的补丁更新
Do’s and Don’ts / 做与不做¶
Do:
执行:
- Use driver query objects rather than building query strings.
中文:使用驱动查询对象而不是构建查询字符串。 - Validate and whitelist user-supplied fields (columns/keys).
中文:验证并白名单用户提供的字段(列/键)。 - Restrict management interfaces and require MFA for admin access.
中文:限制管理接口并要求管理员访问时使用多因素认证。 - Automate security testing in CI/CD pipelines.
中文:在 CI/CD 管道中自动化安全测试。
Don’t:
不要:
- Expose DB ports/admin consoles to the public Internet.
中文:将数据库端口/管理控制台暴露给公共互联网。 - Accept raw JSON queries from clients or eval untrusted strings.
中文:接受来自客户端的原始 JSON 查询或评估不受信任的字符串。 - Use root/admin DB accounts for application connections.
中文:使用 root/admin 数据库账户进行应用程序连接。 - Rely only on network controls to protect badly written queries.
中文:仅依赖网络控制来保护编写不良的查询。
Examples of Dangerous Patterns (brief) / 危险模式示例(简要)¶
- Accepting client-controlled
$whereexpressions executes untrusted JavaScript inside MongoDB and can consume excessive resources. Use standard query operators instead, and disable server-side scripting when it is not needed.
中文:接受客户端控制的$where表达式会在 MongoDB 内执行不受信任的 JavaScript,并可能消耗过多资源。请使用标准查询操作符,并在不需要时禁用服务器端脚本禁用服务器端脚本。 - Concatenating user input into query language strings or shell commands for DB tools.
中文:将用户输入连接到查询语言字符串或用于数据库工具的 shell 命令。 - Leaving MongoDB unsecured (no auth) listening on public IP.
中文:MongoDB未加密(无认证)监听公网IP.
References / 参考¶
- MongoDB: Security Checklist for Self-Managed Deployments) (MongoDB:自托管部署的安全清单)
- Amazon DynamoDB: Preventative Security Best Practices) (Amazon DynamoDB:预防性安全最佳实践)
- WSTG - Testing for NoSQL Injection (WSTG - 测试NoSQL注入)
- No SQL, No Injection?) (无SQL,无注入?)