Time-based SQL Injection - Elixir

Time-based SQL Injection - Elixir

Need

To prevent SQL injection attacks

Context

  • Usage of Elixir (v1.12+) for building scalable and fault-tolerant applications
  • Usage of Ecto.Repo for interacting with databases

Description

Non compliant code

        defmodule MyApp.UserController do
  use MyApp.Web, :controller

  def index(conn, params) do
    users = MyApp.Repo.query!("SELECT * FROM users WHERE name = '#{params["name"]}'")
    render conn, "index.html", users: users
  end
end
        
        

The Elixir code directly interpolates user input into a SQL query, which could lead to SQL injection attacks if the user input is not properly sanitized.

Steps

  • Use parameterized queries instead of directly interpolating user input into SQL queries
  • Pass the user input as a parameter to the query

Compliant code

        defmodule MyApp.UserController do
  use MyApp.Web, :controller

  def index(conn, params) do
    users = MyApp.Repo.query!("SELECT * FROM users WHERE name = $1", [params["name"]])
    render conn, "index.html", users: users
  end
end
        
        

The secure Elixir code uses parameterized queries to prevent SQL injection attacks. The user input is no longer directly interpolated into the SQL query, but instead, it is passed as a parameter to the query.

References