SQL Injection via Headers - Elixir

SQL Injection via Headers - Elixir

Need

Ensure integrity and confidentiality of data and prevent unauthorized database operations

Context

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

Description

Non compliant code

        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

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

Compliant code

        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