Unauthorized File Creation - Elixir

Unauthorized File Creation - Elixir

Need

Prevent unauthorized users from creating files

Context

  • Usage of Elixir for building scalable and fault-tolerant applications
  • Usage of Phoenix web framework for building web applications

Description

Non compliant code

        
            defmodule MyApp.FileController do
              use MyApp, :controller
            
              def create(conn, %{"file" => file_params}) do
                # Create a new file
                {:ok, file} = MyApp.File.create_file(file_params)
            
                conn
                |> put_status(:created)
                |> render("show.json", file: file)
              end
            end
            
        
        

This code is vulnerable because it does not perform any access control check before creating a file. If a malicious user could craft a request to this endpoint, they could create a file regardless of their authorization level.

Steps

  • Implement an authorization check function (e.g., MyApp.Authorization.check_permission/2) that verifies if a user has a specific permission.
  • Before performing any sensitive operations (like creating a file), use this function to check if the current user has the necessary permissions.
  • If the user does not have the necessary permissions, deny the request.

Compliant code

        
            defmodule MyApp.FileController do
              use MyApp, :controller
            
              def create(conn, %{"file" => file_params}) do
                # Check if the user has the necessary permissions
                if MyApp.Authorization.check_permission(conn.assigns[:current_user], :create_file) do
                  # Create a new file
                  {:ok, file} = MyApp.File.create_file(file_params)
            
                  conn
                  |> put_status(:created)
                  |> render("show.json", file: file)
                else
                  conn
                  |> put_status(:forbidden)
                  |> json(%{error: "You do not have the necessary permissions to perform this action."})
                end
              end
            end
            
        
        

In the secure version, the application checks if the current user has the necessary permissions to create a file before performing the action. If they do not, the request is denied.

References