logo

Lack of data validation - Special Characters - Elixir


Need

To prevent unexpected behavior and potential security risks from unvalidated user input.


Context

  1. Usage of Elixir (1.12.0 and above) for building scalable and fault-tolerant applications
  2. Usage of Phoenix Framework for building web applications

Description

Insecure Code Example

defmodule MyAppWeb.UserController do
  use MyAppWeb, :controller

  def create(conn, %{"user" => %{"name" => name}}) do
    {:ok, user} = MyApp.Accounts.create_user(name)
    render(conn, "show.html", user: user)
  end
end

In this example, the user's name is accepted without validation. If a special character is included in the name, it can cause unexpected behavior or security vulnerabilities.

Steps

  1. Implement data validation for all user inputs.
  2. Use regular expressions to restrict the characters that can be included in the user's name.
  3. Handle validation errors gracefully and inform the user of the requirements.

Secure Code Example

defmodule MyAppWeb.UserController do
  use MyAppWeb, :controller

  def create(conn, %{"user" => %{"name" => name}}) do
    case MyApp.Accounts.create_user(name) do
      {:ok, user} ->
        render(conn, "show.html", user: user)
      {:error, changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end
end

defmodule MyApp.Accounts.User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    field :name, :string
  end

  def changeset(user, attrs) do
    user
    |> cast(attrs, [:name])
    |> validate_format(:name, ~r/^[a-zA-Z0-9_]*$/)
  end
end

In the secure code, the user's name is validated using a regular expression, ensuring that it contains only alphanumeric characters and underscores. If the validation fails, an error is returned and can be handled by the controller.


References

  • 340 - Lack of data validation - Special Characters

  • Last updated

    2023/09/18