GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Bottle

NoSQL Injection in Bottle apps typically occurs when the application accepts raw JSON or form data and passes it directly into a MongoDB filter via PyMongo. Attackers exploit this by injecting operator objects like {"$gt": ""} or {"$ne": null} to bypass authentication or dump collections. If you aren't validating types, you're essentially handing the attacker the keys to the database.

The Vulnerable Pattern

from bottle import post, request
from pymongo import MongoClient

db = MongoClient(‘mongodb://localhost:27017/‘).app_db

@post(‘/api/user’) def get_user(): # VULNERABLE: Direct injection point. # Attacker sends: {“username”: {“$ne”: null}} query = request.json user = db.users.find_one(query) return {“username”: user[‘username’]} if user else {“error”: “not found”}

The Secure Implementation

The exploit works because PyMongo interprets nested dictionaries as query operators. By passing the raw `request.json` object into `find_one()`, the attacker controls the query logic. The fix is simple: never trust the structure of the input. Explicitly define the query document and cast user-supplied values to the expected type (usually `str` or `int`). For high-scale apps, use a schema validator like Pydantic or Marshmallow to enforce strict input types before they reach the database layer.

from bottle import post, request, abort
from pymongo import MongoClient

db = MongoClient(‘mongodb://localhost:27017/‘).app_db

@post(‘/api/user’) def get_user(): data = request.json if not data or ‘username’ not in data: abort(400, “Missing username”)

# SECURE: Cast input to string to prevent operator injection
# This forces the query to look for a literal string value
safe_username = str(data.get('username'))

user = db.users.find_one({"username": safe_username})
return {"username": user['username']} if user else {"error": "not found"}</code></pre>
System Alert • ID: 6467
Target: Bottle API
Potential Vulnerability

Your Bottle API might be exposed to NoSQL Injection

74% of Bottle 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.