logo

Database

Need

To prevent unauthorized data access and manipulation through NoSQL Injection attacks

Context

• Usage of Elixir (v1.11+) for building scalable and fault-tolerant applications

• Usage of MongoDB driver for interacting with MongoDB database

Description

1. Non compliant code

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.

2. Steps

• Don't use user input directly in NoSQL queries.

• Sanitize user input before using it in a query.

• Use parameterized queries or prepared statements if available.

3. 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...

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