Improper Resource Allocation
Need
Prevent unnecessary resource consumption due to inefficient algorithms or improper programming practices
Context
• Usage of Elixir (v1.11+) for building scalable and concurrent applications
Description
1. Non compliant code
defmodule Vulnerable do
def huge_list(n) when is_integer(n) do
Enum.to_list(1..n)
end
endThe `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.
2. Steps
• Consider the nature of the problem you're trying to solve and choose the appropriate data structure.
• If possible, use lazy evaluation to avoid creating large data structures in memory.
• Apply a limit to the input size if it's under external control.
• If the function is intended to create large data structures, consider alternative strategies like writing the data to disk.
3. Secure code example
defmodule Secure do
def huge_list(n) when is_integer(n) and n <= 10000 do
Enum.to_list(1..n)
end
endIn 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