Insecure functionality - Password management - Elixir

Insecure functionality - Password management - Elixir

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

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
                |> 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

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

Compliant code

        
            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