Unbounded query cache growth from interpolated JSON paths and splice lists enables memory exhaustion denial of service
Description
JSON path elements interpolated into json_extract_path/2 or field[^key] become part of the query expression and of its cache key, and so does the length of a list given to splice/1 in a fragment. An attacker who controls such a key or list length creates a new cache entry with every request. With ecto_sql each entry is also a new prepared statement on the database connection.
Interpolated path elements in json_extract_path/2 were added in Ecto v3.4.0 (cb2f039) and splice/1 in v3.11.0 (eb03f45). The documentation of both shows interpolated values. The query cache was disabled for values/2 sources after a similar report (#4470), but not for these two cases.
Workaround
Users are advised to upgrade immediately. Those who cannot upgrade can mitigate this vulnerability in different ways.
Validate external data
Validate any external data before interpolating it into json_extract_path or splice.
Using query parameters
Pass the path as a query parameter so it is not part of the cache key. With PostgreSQL:
from i in Item,
where: fragment("? #> ?", i.meta, type(^path, {:array, :string})) == ^valueDisable the query cache
Alternatively, disable the cache for these queries with Repo.all(query, query_cache: false).
Impact
An application is affected when it passes request data into an interpolated JSON path (json_extract_path(field, ^path), json_extract_path(field, [^key]) or field[^key]), or a request-controlled list into splice/1, and runs the query through a repository with the default query_cache: true. Typical cases are filter and sort endpoints over JSON columns. Each request with a new key adds memory that is never released, in the BEAM, where the cache is shared by the whole repository, and with ecto_sql in the database server, where prepared statements are kept per connection. Large keys amplify this: in the PoC, every 1 MB of request data retained about 2 MB in the application and 3 MB in PostgreSQL. Sustained requests exhaust memory in the application node, the database server, or both. The PoC used a single connection; with a larger pool, each connection that runs a query prepares its own statement.
References
- Patch: github.com/
elixir-ecto/ ecto/ commit/ d0e97d8a6e274c81c25fbf08087da8d8b9bae0ea - Interpolated path elements in
json_extract_path/2(v3.4.0): github.com/elixir-ecto/ ecto/ commit/ cb2f03964dac324a9771f84f5088e395326e6de8 splice/1in fragments (v3.11.0): github.com/elixir-ecto/ ecto/ commit/ eb03f45b999e2bf67ffae92811233eb6e56dba55 - Query cache disabled for
values/2sources: github.com/elixir-ecto/ ecto/ issues/ 4470 - Earlier report of unbounded query cache growth: github.com/
elixir-ecto/ ecto/ issues/ 1031