logo

Database

Insecure functionality - Password management

Need

Secure password management

Context

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

• Usage of Phoenix framework for web application development

Description

1. Non compliant code


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

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.

2. Steps

• Check if the current user's id matches the id in the parameters.

• If not, return an error response.

3. 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})
                    conn...

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.