GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Flask

NoSQL Injection (NoSQLi) in Flask/MongoDB environments occurs when raw, untrusted user-controlled objects are passed directly into query filters. Attackers exploit this by injecting MongoDB operators like $ne (not equal), $gt (greater than), or $regex to bypass authentication or dump databases. If you're passing request.json or request.form directly into a find() call without sanitization, you're giving attackers full control over your query logic.

The Vulnerable Pattern

@app.route('/api/v1/login', methods=['POST'])
def login():
    # VULNERABLE: Direct injection via JSON object
    # Attacker payload: {"username": "admin", "password": {"$ne": "invalid"}}
    # This results in: db.users.find_one({'username': 'admin', 'password': {'$ne': 'invalid'}})
    # The query evaluates to true because the password is indeed not 'invalid'.
    data = request.json
    user = db.users.find_one({
        'username': data.get('username'),
        'password': data.get('password')
    })
    if user:
        return {'status': 'success'}
    return {'status': 'fail'}, 401

The Secure Implementation

The exploit works because PyMongo interprets nested dictionaries as query operators. The fix is simple: never trust the structure of the input object. By casting the values to `str()`, any injected dictionary payload like `{"$gt": ""}` becomes the literal string "{'$gt': ''}", which will fail to match the actual password hash in the database. For complex applications, use a schema validation library like Marshmallow or Pydantic to enforce strict data types and patterns before the data ever reaches your database driver.

@app.route('/api/v1/login', methods=['POST'])
def login():
    # SECURE: Explicit type enforcement and sanitization
    data = request.json
# Force inputs to strings to neutralize operator dictionaries
username = str(data.get('username', ''))
password = str(data.get('password', ''))

user = db.users.find_one({
    'username': username,
    'password': password
})

if user:
    return {'status': 'success'}
return {'status': 'fail'}, 401</code></pre>
System Alert • ID: 5903
Target: Flask API
Potential Vulnerability

Your Flask API might be exposed to NoSQL Injection

74% of Flask apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.