GuardAPI Logo
GuardAPI
Automated Security Protocol

How to fix NoSQL Injection
in Plug

Executive Summary

NoSQL Injection in Elixir/Plug environments occurs when untrusted input is fed directly into database query filters. Since Plug.Parsers automatically decodes JSON objects into Elixir Maps, an attacker can replace a projected string value with a nested map containing MongoDB operators like $ne, $gt, or $regex. This allows them to bypass authentication or leak sensitive data by altering the query logic.

The Vulnerable Pattern

VULNERABLE CODE
defmodule MyApp.Router do
  use Plug.Router
  plug :match
  plug Plug.Parsers, parsers: [:json], pass: ["application/json"], json_decoder: Jason
  plug :dispatch

post “/login” do # VULNERABLE: conn.params[“token”] could be %{“$ne” => ""} token = conn.params[“token”] case Mongo.find_one(:mongo, “users”, %{“session_token” => token}) do nil -> send_resp(conn, 401, “Unauthorized”) user -> send_resp(conn, 200, “Welcome #{user[“name”]}”) end end end

The Secure Implementation

The exploit leverages the fact that many NoSQL drivers for Elixir accept Maps as valid query values. In the vulnerable example, if an attacker sends `{"token": {"$ne": ""}}`, the query becomes `{"session_token": {"$ne": ""}}`, which matches the first user in the DB. The secure implementation uses Elixir's pattern matching (`is_binary/1`) to ensure the input is a primitive string. If the attacker attempts to pass a map, the guard fails, and the injection is neutralized before hitting the database layer.

SECURE CODE
defmodule MyApp.Router do
  use Plug.Router
  # ... (middleware setup)

post “/login” do # SECURE: Use pattern matching to enforce that the input is a binary (string) case conn.params[“token”] do token when is_binary(token) -> case Mongo.find_one(:mongo, “users”, %{“session_token” => token}) do nil -> send_resp(conn, 401, “Unauthorized”) user -> send_resp(conn, 200, “Welcome #{user[“name”]}”) end _ -> # Reject maps/lists to prevent operator injection send_resp(conn, 400, “Invalid Input Type”) end end end

System Alert • ID: 5742
Target: Plug API
Potential Vulnerability

Your Plug API might be exposed to NoSQL Injection

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