logo

NoSQL Injection - Elixir


Need

To prevent unauthorized data access and manipulation through NoSQL Injection attacks


Context

  1. Usage of Elixir (v1.11+) for building scalable and fault-tolerant applications
  2. Usage of MongoDB driver for interacting with MongoDB database

Description

Insecure Code Example

defmodule MyAppWeb.PageController do
  use MyAppWeb, :controller

  def show(conn, %{"id" => id}) do
    page = Mongo.find(:mongo, "pages", %{"_id" => id}) |> Enum.to_list()
    json(conn, page)
  end
end

In this insecure code, the Elixir/Phoenix application accepts an ID from user input and uses it directly in a MongoDB query. This can be exploited for a NoSQL Injection attack, leading to unauthorized data access or manipulation.

Steps

  1. Don't use user input directly in NoSQL queries.
  2. Sanitize user input before using it in a query.
  3. Use parameterized queries or prepared statements if available.

Secure Code Example

defmodule MyAppWeb.PageController do
  use MyAppWeb, :controller

  def show(conn, %{"id" => id}) do
    id = String.replace(id, "$", "") |> String.replace(".", "")
    page = Mongo.find(:mongo, "pages", %{"_id" => id}) |> Enum.to_list()
    json(conn, page)
  end
end

In this secure code, the application now sanitizes the user input by replacing potential NoSQL Injection attack characters '$' and '.'. The sanitized input is then used in the MongoDB query.


References

  • 106 - NoSQL Injection

  • Last updated

    2023/09/18