logo

SQL Injection via Headers - Elixir


Need

Ensure integrity and confidentiality of data and prevent unauthorized database operations


Context

  1. Usage of Elixir (v1.10+) for building scalable and fault-tolerant applications
  2. Usage of Plug.Conn for handling requests
  3. Usage of Ecto for database operations

Description

Insecure Code Example

def handle_req(%Plug.Conn{headers: headers} = conn, _) do
  id_client = List.keyfind(headers, "idClient", 0) |> elem(1)
  MyApp.Repo.query("SELECT * FROM clients WHERE id = #{id_client}")
end

The code above is vulnerable as it uses the 'idClient' header value directly in a SQL query. This allows an attacker to inject arbitrary SQL code into the query through the 'idClient' header.

Steps

  1. Use query binding instead of string interpolation to create SQL queries.
  2. Ensure user input can't modify the intended SQL query structure.
  3. Regularly update your dependencies to include patches for security vulnerabilities.

Secure Code Example

def handle_req(%Plug.Conn{headers: headers} = conn, _) do
  id_client = List.keyfind(headers, "idClient", 0) |> elem(1)
  MyApp.Repo.query("SELECT * FROM clients WHERE id = ?", [id_client])
end

The secure code uses query binding to create the SQL query, which ensures the input from 'idClient' header is properly escaped and treated as a value, not a part of the SQL command. This prevents SQL Injection attacks.


References

  • 155 - SQL Injection via Headers

  • Last updated

    2023/09/18