Prevent resource exhaustion and potential denial of service attacks
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.
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.