Prevent injection attacks, server resource exhaustion, and improve the overall security by applying server-side data validation
defmodule InsecureApp do
use Plug.Router
plug :match
plug :dispatch
post "/data" do
user_data = conn.params["user_data"]
Repo.insert(%Data{content: user_data})
send_resp(conn, 200, "Data received")
end
run InsecureApp
end
This insecure code snippet represents a web service written in Elixir. The code is vulnerable because it lacks input validation for the data being sent to the server. It directly takes the user data from the request and inserts it into the database. An attacker can use special characters to inject harmful strings (like SQLi or XSS payloads) or large amounts of data to exhaust the server's resources.
defmodule SecureApp do
use Plug.Router
import Plug.Conn
plug :match
plug :dispatch
defp validate_data(data) do
if String.length(data) > 1000,
do: {:error, "Data too long"}
sanitized_data = String.replace(data, ~r/[<>"';()&]/, "")
{:ok, sanitized_data}
end
post "/data" do
case conn.params["user_data"] |> validate_data do
{:ok, valid_data} ->
Repo.insert(%Data{content: valid_data})
send_resp(conn, 200, "Data received")
{:error, _reason} ->
send_resp(conn, 400, "Invalid data")
end
end
run SecureApp
end
This secure code snippet represents a web service written in Elixir with data validation. The 'validate_data' function checks the length of the user data and uses 'String.replace' function to escape dangerous characters. This way, the possibility of injection attacks or server resource exhaustion is significantly mitigated.