Ecto.Adapters.SQL.query for sql query leads to sql injection attack?

If I am using Ecto.Adapters.SQL.query for sql query does it leads to sql injection attack?

1 Like

Depends in how you build the query. If you’re using a static query, with parameters passed separately then you’re fine. If you’re dynamically building the query itself based on user input you’re opening routes for sql injection.

Can you please give an example for parameterized query and without parametrized query.

# Safe
Ecto.Adapters.SQL.query(MyRepo, "SELECT $1::integer + $2", [input_a, input_b])
# Unsafe
Ecto.Adapters.SQL.query(MyRepo, "SELECT #{input_a} + #{input_b}")
# Unsafe
query = "SELECT " <> input_a <> " + " <> input_b
Ecto.Adapters.SQL.query(MyRepo, query)

Whenever any user input is part of the query parameter and not only the list after the query it’s most likely not safe.

7 Likes