Fix NoSQL Injection in Rails
NoSQL injection in Rails typically manifests in applications using Mongoid or similar ODMs. The vulnerability arises when unsanitized user-controlled hashes are passed directly into query methods. Attackers leverage MongoDB operators like $ne (not equal), $gt (greater than), or $regex to bypass authentication logic or exfiltrate data by manipulating the query structure via crafted HTTP parameters.
The Vulnerable Pattern
def authenticate
# VULNERABLE: params[:password] can be a hash like { '$ne' => '' }
# This allows an attacker to login as any user without knowing the password.
user = User.find_by(email: params[:email], password: params[:password])
if user
session[:user_id] = user.id
end
end
The Secure Implementation
The exploit works because Rails' Rack-based parameter parsing converts 'password[$ne]=1' into a Ruby Hash: { '$ne' => '1' }. When this hash is passed to a Mongoid query, the ODM interprets '$ne' as a MongoDB operator rather than a literal string. To fix this, you must enforce scalar types. Using .to_s on incoming parameters ensures that even if an attacker sends a hash, it is converted into a benign string representation, stripping the query of its malicious logic. Alternatively, use Strong Parameters with explicit permit requirements for scalar types (e.g., params.permit(:email, :password)).
def authenticate # SECURE: Force input to string to neutralize nested hash operators safe_email = params[:email].to_s safe_password = params[:password].to_s
user = User.find_by(email: safe_email, password: safe_password) if user session[:user_id] = user.id end end
Your Rails API
might be exposed to NoSQL Injection
74% of Rails apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
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.