logo

Insecure functionality - Password management - Elixir


Need

Secure password management


Context

  1. Usage of Elixir (v1.12+) for building scalable and fault-tolerant applications
  2. Usage of Phoenix framework for web application development

Description

Insecure Code Example


            def update_password(conn, %{"id" => id, "password" => password}) do
                user = Accounts.get_user!(id)
                user
                |> User.changeset(%{password: password})
                |> Repo.update!()
                conn
                |> put_flash(:info, "Password updated successfully.")
                |> redirect(to: "/")
            end
            

This example represents a password update function in a web application written in Elixir using the Phoenix framework. The function does not verify whether the current user has the right to change the password for the user id provided in the params. An attacker can use this function to change the password of any user, knowing only their user id.

Steps

  1. Check if the current user's id matches the id in the parameters.
  2. If not, return an error response.

Secure Code Example


            def update_password(conn, %{"id" => id, "password" => password}) do
                current_user = get_session(conn, :current_user)
                if current_user.id == id do
                    user = Accounts.get_user!(id)
                    user
                    |> User.changeset(%{password: password})
                    |> Repo.update!()
                    conn
                    |> put_flash(:info, "Password updated successfully.")
                    |> redirect(to: "/")
                else
                    conn
                    |> put_flash(:error, "You do not have permission to change this user's password.")
                    |> redirect(to: "/")
                end
            end
            

This is the secure version of the previous code. It includes a check to verify that the current user (taken from the session) is the same user for whom the password is being changed.


References

  • 271 - Insecure functionality - Password management

  • Last updated

    2023/09/18