logo

Database

Need

Prevent injection of malicious characters

Context

• Usage of Elixir (v1.10+) for building scalable and fault-tolerant applications

• Usage of Phoenix framework for building web applications

Description

1. Non compliant code

defmodule MyAppWeb.UserController do
  use MyAppWeb, :controller

  def create(conn, %{"user" => user_params}) do
    %User{} |> User.changeset(user_params) |> Repo.insert!()
    send_resp(conn, 200, "User created")
  end
end

In this Elixir code, the application takes user input directly from the request parameters and uses it to create a new User record. This is insecure because there's no validation on the user_params. An attacker could inject potentially malicious characters or pass in invalid data for certain fields.

2. Steps

• Always validate user input on the server-side before using it.

• Use Ecto changesets or a similar mechanism for data validation.

3. Secure code example

defmodule MyAppWeb.UserController do
  use MyAppWeb, :controller

  def create(conn, %{"user" => user_params}) do
    changeset = User.changeset(%User{}, user_params)

    if changeset.valid? do
      send_resp(conn, 200, "User created")...

In this Elixir code, the application validates user input before using it to create a new User record. The changeset.valid? check ensures that the user_params data is valid before attempting to insert it into the database.