logo

Improper Type Assignation - Elixir


Need

To prevent errors and potential security issues caused by assigning the wrong type of value to a variable


Context

  1. Usage of Elixir for building scalable and fault-tolerant applications
  2. Usage of Elixir for building scalable and fault-tolerant applications
  3. Usage of dynamically typed language

Description

Insecure Code Example

defmodule VulnerableCode do
  def add_one(input) do
    input + 1
  end
end

This Elixir code is vulnerable because it assigns a string to a variable that is expected to be a number. If a string is supplied instead of a number, an error will occur when trying to perform an arithmetic operation.

Steps

  1. Perform type checking before using the variable.
  2. Handle the error case when the value is not of the expected type.

Secure Code Example

defmodule SecureCode do
  def add_one(input) when is_number(input) do
    input + 1
  end

  def add_one(_input) do
    {:error, "Input must be a number"}
  end
end

This Elixir code is safe because it checks the type of the input before performing the arithmetic operation. If the input is not a number, an error message is returned instead of causing a runtime error.


References

  • 113 - Improper Type Assignation

  • Last updated

    2023/09/18