Ensure integrity and confidentiality of data and prevent unauthorized database operations
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.
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.