logo

Improper Resource Allocation - Elixir


Need

Prevent unnecessary resource consumption due to inefficient algorithms or improper programming practices


Context

  1. Usage of Elixir (v1.11+) for building scalable and concurrent applications

Description

Insecure Code Example

defmodule Vulnerable do
  def huge_list(n) when is_integer(n) do
    Enum.to_list(1..n)
  end
end

The `huge_list` function creates a list from 1 to `n`. If `n` is a large number, this function could consume a large amount of memory, possibly leading to an OutOfMemory error or significantly slowing down the system.

Steps

  1. Consider the nature of the problem you're trying to solve and choose the appropriate data structure.
  2. If possible, use lazy evaluation to avoid creating large data structures in memory.
  3. Apply a limit to the input size if it's under external control.
  4. If the function is intended to create large data structures, consider alternative strategies like writing the data to disk.

Secure Code Example

defmodule Secure do
  def huge_list(n) when is_integer(n) and n <= 10000 do
    Enum.to_list(1..n)
  end
end

In the secure example, a guard clause has been added to limit `n` to 10,000, preventing the creation of extremely large lists. The actual limit should be determined based on the specific requirements and resources of your system.


References

  • 067 - Improper Resource Allocation

  • Last updated

    2023/09/18