Inadequate File Size Control - Elixir

Inadequate File Size Control - Elixir

Need

Prevent resource exhaustion and potential denial of service attacks

Context

  • Usage of Elixir for building scalable and fault-tolerant applications
  • Usage of Plug.Upload for handling file uploads in Elixir
  • File uploads are handled using Plug.Upload

Description

Non compliant code

        defmodule VulnerableController do
  use MyApp.Web, :controller

  def upload(conn, %{"file" => %Plug.Upload{} = upload}) do
    {:ok, _} = File.cp(upload.path, "./uploads/#{upload.filename}")
    send_resp(conn, 200, "File uploaded successfully")
  end
end
        
        

The following Elixir code is vulnerable because it does not impose a limit on the size of the uploaded file. An attacker could upload a very large file to consume server resources and potentially cause a denial of service.

Steps

  • Install the 'arc' library which allows to impose a limit on the size of the uploaded files.
  • Define a function to check the size of the uploaded file before copying it to the server storage.
  • If the file size exceeds the limit, reject the upload and send an appropriate response to the client.

Compliant code

        defmodule SecureController do
  use MyApp.Web, :controller

  def upload(conn, %{"file" => %Plug.Upload{} = upload}) do
    if File.size(upload.path) > 10_000_000 do
      send_resp(conn, 400, "File size exceeds limit")
    else
      {:ok, _} = File.cp(upload.path, "./uploads/#{upload.filename}")
      send_resp(conn, 200, "File uploaded successfully")
    end
  end
end
        
        

The following Elixir code is secure because it checks the size of the uploaded file before processing it. If the file size exceeds the limit, the upload is rejected.

References